instance_id stringlengths 13 45 | pull_number int64 7 30.1k | repo stringclasses 83
values | version stringclasses 68
values | base_commit stringlengths 40 40 | created_at stringdate 2013-05-16 18:15:55 2025-01-08 15:12:50 | patch stringlengths 347 35.2k | test_patch stringlengths 432 113k | non_py_patch stringlengths 0 18.3k | new_components listlengths 0 40 | FAIL_TO_PASS listlengths 1 2.53k | PASS_TO_PASS listlengths 0 1.7k | problem_statement stringlengths 607 52.7k | hints_text stringlengths 0 57.4k | environment_setup_commit stringclasses 167
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tobymao__sqlglot-3899 | 3,899 | tobymao/sqlglot | null | 6f1527fd3ebd16f49edb351f050a1db687824530 | 2024-08-12T21:17:38Z | diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index b3df9a71ca..0aefb7eb64 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -1605,9 +1605,9 @@ def sha256_sql(self: Generator, expression: exp.SHA2) -> str:
return self.func(f"SHA{expression.text('length') or '256'}", expression.this)
-def sequence_sql(self: Generator, expression: exp.GenerateSeries):
- start = expression.args["start"]
- end = expression.args["end"]
+def sequence_sql(self: Generator, expression: exp.GenerateSeries | exp.GenerateDateArray) -> str:
+ start = expression.args.get("start")
+ end = expression.args.get("end")
step = expression.args.get("step")
if isinstance(start, exp.Cast):
@@ -1617,8 +1617,8 @@ def sequence_sql(self: Generator, expression: exp.GenerateSeries):
else:
target_type = None
- if target_type and target_type.is_type("timestamp"):
- if target_type is start.to:
+ if start and end and target_type and target_type.is_type("date", "timestamp"):
+ if isinstance(start, exp.Cast) and target_type is start.to:
end = exp.cast(end, target_type)
else:
start = exp.cast(start, target_type)
diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index ddd252cc2e..1bccd7436c 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -233,7 +233,7 @@ def _generate_datetime_array_sql(
# BQ's GENERATE_DATE_ARRAY & GENERATE_TIMESTAMP_ARRAY are transformed to DuckDB'S GENERATE_SERIES
gen_series: t.Union[exp.GenerateSeries, exp.Cast] = exp.GenerateSeries(
- start=start, end=end, step=expression.args.get("interval")
+ start=start, end=end, step=expression.args.get("step")
)
if is_generate_date_array:
diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py
index 2b1a1333be..e3a2bca1a3 100644
--- a/sqlglot/dialects/hive.py
+++ b/sqlglot/dialects/hive.py
@@ -509,6 +509,7 @@ class Generator(generator.Generator):
e: f"STORED AS {self.sql(e, 'this') if isinstance(e.this, exp.InputOutputFormat) else e.name.upper()}",
exp.FromBase64: rename_func("UNBASE64"),
exp.GenerateSeries: sequence_sql,
+ exp.GenerateDateArray: sequence_sql,
exp.If: if_sql(),
exp.ILike: no_ilike_sql,
exp.IsNan: rename_func("ISNAN"),
diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py
index 145a7d1cb2..81767abd90 100644
--- a/sqlglot/dialects/mysql.py
+++ b/sqlglot/dialects/mysql.py
@@ -753,6 +753,9 @@ class Generator(generator.Generator):
exp.TsOrDsDiff: lambda self, e: self.func("DATEDIFF", e.this, e.expression),
exp.TsOrDsToDate: _ts_or_ds_to_date_sql,
exp.UnixToTime: _unix_to_time_sql,
+ exp.Unnest: transforms.preprocess(
+ [transforms.unnest_generate_date_array_using_recursive_cte()]
+ ),
exp.Week: _remove_ts_or_ds_to_date(),
exp.WeekOfYear: _remove_ts_or_ds_to_date(rename_func("WEEKOFYEAR")),
exp.Year: _remove_ts_or_ds_to_date(),
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py
index e739df7e9d..6f7f9aabc5 100644
--- a/sqlglot/dialects/postgres.py
+++ b/sqlglot/dialects/postgres.py
@@ -584,21 +584,32 @@ def commentcolumnconstraint_sql(self, expression: exp.CommentColumnConstraint) -
def unnest_sql(self, expression: exp.Unnest) -> str:
if len(expression.expressions) == 1:
+ arg = expression.expressions[0]
+ if isinstance(arg, exp.GenerateDateArray):
+ generate_series: exp.Expression = exp.GenerateSeries(**arg.args)
+ if isinstance(expression.parent, (exp.From, exp.Join)):
+ generate_series = (
+ exp.select("value::date")
+ .from_(generate_series.as_("value"))
+ .subquery(expression.args.get("alias") or "_unnested_generate_series")
+ )
+ return self.sql(generate_series)
+
from sqlglot.optimizer.annotate_types import annotate_types
- this = annotate_types(expression.expressions[0])
+ this = annotate_types(arg)
if this.is_type("array<json>"):
while isinstance(this, exp.Cast):
this = this.this
- arg = self.sql(exp.cast(this, exp.DataType.Type.JSON))
+ arg_as_json = self.sql(exp.cast(this, exp.DataType.Type.JSON))
alias = self.sql(expression, "alias")
alias = f" AS {alias}" if alias else ""
if expression.args.get("offset"):
self.unsupported("Unsupported JSON_ARRAY_ELEMENTS with offset")
- return f"JSON_ARRAY_ELEMENTS({arg}){alias}"
+ return f"JSON_ARRAY_ELEMENTS({arg_as_json}){alias}"
return super().unnest_sql(expression)
diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py
index adce6c3784..4c6fc5f344 100644
--- a/sqlglot/dialects/presto.py
+++ b/sqlglot/dialects/presto.py
@@ -427,6 +427,7 @@ class Generator(generator.Generator):
exp.FromTimeZone: lambda self,
e: f"WITH_TIMEZONE({self.sql(e, 'this')}, {self.sql(e, 'zone')}) AT TIME ZONE 'UTC'",
exp.GenerateSeries: sequence_sql,
+ exp.GenerateDateArray: sequence_sql,
exp.Group: transforms.preprocess([transforms.unalias_group]),
exp.GroupConcat: lambda self, e: self.func(
"ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator")
diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py
index b39a9a5024..74a8038428 100644
--- a/sqlglot/dialects/redshift.py
+++ b/sqlglot/dialects/redshift.py
@@ -209,6 +209,13 @@ class Generator(Postgres.Generator):
exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
exp.UnixToTime: lambda self,
e: f"(TIMESTAMP 'epoch' + {self.sql(e.this)} * INTERVAL '1 SECOND')",
+ exp.Unnest: transforms.preprocess(
+ [
+ transforms.unnest_generate_date_array_using_recursive_cte(
+ bubble_up_recursive_cte=True
+ )
+ ]
+ ),
}
# Postgres maps exp.Pivot to no_pivot_sql, but Redshift support pivots
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index 981dba15c6..9e625b827f 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -180,6 +180,44 @@ 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")
+
+ if not start or not end or not isinstance(step, exp.Interval) or step.name != "1":
+ continue
+
+ unit = step.args.get("unit")
+
+ # 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("value", "int"), exp.cast(start, "date")]
+ ).as_("value")
+
+ # 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_alias = unnest.args.get("alias")
+ if unnest_alias:
+ unnest_alias = unnest_alias.copy()
+
+ unnest.set("expressions", [number_sequence])
+ unnest.replace(exp.select(date_add).from_(unnest.copy()).subquery(unnest_alias))
+
+ return expression
+
+
class Snowflake(Dialect):
# https://docs.snowflake.com/en/sql-reference/identifiers-syntax
NORMALIZATION_STRATEGY = NormalizationStrategy.UPPERCASE
@@ -767,6 +805,7 @@ class Generator(generator.Generator):
transforms.eliminate_distinct_on,
transforms.explode_to_unnest(),
transforms.eliminate_semi_and_anti_joins,
+ _unnest_generate_date_array,
]
),
exp.SHA: rename_func("SHA1"),
diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py
index cd42f9e139..2468b54e8c 100644
--- a/sqlglot/dialects/tsql.py
+++ b/sqlglot/dialects/tsql.py
@@ -882,6 +882,13 @@ class Generator(generator.Generator):
exp.Trim: trim_sql,
exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
+ exp.Unnest: transforms.preprocess(
+ [
+ transforms.unnest_generate_date_array_using_recursive_cte(
+ bubble_up_recursive_cte=True
+ )
+ ]
+ ),
}
TRANSFORMS.pop(exp.ReturnsProperty)
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index a3bbac282b..f3e486add0 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -5347,12 +5347,12 @@ class GapFill(Func):
# https://cloud.google.com/bigquery/docs/reference/standard-sql/array_functions#generate_date_array
class GenerateDateArray(Func):
- arg_types = {"start": True, "end": True, "interval": False}
+ arg_types = {"start": True, "end": True, "step": False}
# https://cloud.google.com/bigquery/docs/reference/standard-sql/array_functions#generate_timestamp_array
class GenerateTimestampArray(Func):
- arg_types = {"start": True, "end": True, "interval": True}
+ arg_types = {"start": True, "end": True, "step": True}
class Greatest(Func):
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index 12b71a678b..1027253bac 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -186,8 +186,7 @@ class Parser(metaclass=_Parser):
"GENERATE_DATE_ARRAY": lambda args: exp.GenerateDateArray(
start=seq_get(args, 0),
end=seq_get(args, 1),
- interval=seq_get(args, 2)
- or exp.Interval(this=exp.Literal.number(1), unit=exp.var("DAY")),
+ step=seq_get(args, 2) or exp.Interval(this=exp.Literal.number(1), unit=exp.var("DAY")),
),
"GLOB": lambda args: exp.Glob(this=seq_get(args, 1), expression=seq_get(args, 0)),
"HEX": build_hex,
diff --git a/sqlglot/transforms.py b/sqlglot/transforms.py
index d38e1866b7..27b26e0f99 100644
--- a/sqlglot/transforms.py
+++ b/sqlglot/transforms.py
@@ -55,6 +55,61 @@ def _to_sql(self, expression: exp.Expression) -> str:
return _to_sql
+def unnest_generate_date_array_using_recursive_cte(
+ bubble_up_recursive_cte: bool = False,
+) -> t.Callable[[exp.Expression], exp.Expression]:
+ def _unnest_generate_date_array_using_recursive_cte(
+ expression: exp.Expression,
+ ) -> exp.Expression:
+ if (
+ isinstance(expression, exp.Unnest)
+ and isinstance(expression.parent, (exp.From, exp.Join))
+ and len(expression.expressions) == 1
+ and isinstance(expression.expressions[0], exp.GenerateDateArray)
+ ):
+ generate_date_array = expression.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):
+ return expression
+
+ start = exp.cast(start, "date")
+ date_add = exp.func(
+ "date_add", "date_value", exp.Literal.number(step.name), step.args.get("unit")
+ )
+ cast_date_add = exp.cast(date_add, "date")
+
+ base_query = exp.select(start.as_("date_value"))
+ recursive_query = (
+ exp.select(cast_date_add.as_("date_value"))
+ .from_("_generated_dates")
+ .where(cast_date_add < exp.cast(end, "date"))
+ )
+ cte_query = base_query.union(recursive_query, distinct=False)
+ generate_dates_query = exp.select("date_value").from_("_generated_dates")
+
+ query_to_add_cte: exp.Query = generate_dates_query
+
+ if bubble_up_recursive_cte:
+ parent: t.Optional[exp.Expression] = expression.parent
+
+ while parent:
+ if isinstance(parent, exp.Query):
+ query_to_add_cte = parent
+ parent = parent.parent
+
+ query_to_add_cte.with_(
+ "_generated_dates(date_value)", as_=cte_query, recursive=True, copy=False
+ )
+ return generate_dates_query.subquery("_generated_dates")
+
+ return expression
+
+ return _unnest_generate_date_array_using_recursive_cte
+
+
def unnest_generate_series(expression: exp.Expression) -> exp.Expression:
"""Unnests GENERATE_SERIES or SEQUENCE table references."""
this = expression.this
| diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py
index 522c42cd6f..e1f944cbf1 100644
--- a/tests/dialects/test_dialect.py
+++ b/tests/dialects/test_dialect.py
@@ -2603,3 +2603,21 @@ def test_string_functions(self):
"trino": f"SELECT {pad_func}('bar', 5, ' ')",
},
)
+
+ def test_generate_date_array(self):
+ self.validate_all(
+ "SELECT * FROM UNNEST(GENERATE_DATE_ARRAY(DATE '2020-01-01', DATE '2020-02-01', INTERVAL 1 WEEK))",
+ write={
+ "bigquery": "SELECT * FROM UNNEST(GENERATE_DATE_ARRAY(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), INTERVAL '1' WEEK))",
+ "databricks": "SELECT * FROM EXPLODE(SEQUENCE(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), INTERVAL '1' WEEK))",
+ "duckdb": "SELECT * FROM UNNEST(CAST(GENERATE_SERIES(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), (7 * INTERVAL '1' DAY)) AS DATE[]))",
+ "mysql": "SELECT * FROM (WITH RECURSIVE _generated_dates(date_value) AS (SELECT CAST('2020-01-01' AS DATE) AS date_value UNION ALL SELECT CAST(DATE_ADD(date_value, INTERVAL 1 WEEK) AS DATE) AS date_value FROM _generated_dates WHERE CAST(DATE_ADD(date_value, INTERVAL 1 WEEK) AS DATE) < CAST('2020-02-01' AS DATE)) SELECT date_value FROM _generated_dates) AS _generated_dates",
+ "postgres": "SELECT * FROM (SELECT CAST(value AS DATE) FROM GENERATE_SERIES(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), INTERVAL '1 WEEK') AS value) AS _unnested_generate_series",
+ "presto": "SELECT * FROM UNNEST(SEQUENCE(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), (1 * INTERVAL '7' DAY)))",
+ "redshift": "WITH RECURSIVE _generated_dates(date_value) AS (SELECT CAST('2020-01-01' AS DATE) AS date_value UNION ALL SELECT CAST(DATEADD(WEEK, 1, date_value) AS DATE) AS date_value FROM _generated_dates WHERE CAST(DATEADD(WEEK, 1, date_value) AS DATE) < CAST('2020-02-01' AS DATE)) SELECT * FROM (SELECT date_value FROM _generated_dates) AS _generated_dates",
+ "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))",
+ "spark": "SELECT * FROM EXPLODE(SEQUENCE(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), INTERVAL '1' WEEK))",
+ "trino": "SELECT * FROM UNNEST(SEQUENCE(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), (1 * INTERVAL '7' DAY)))",
+ "tsql": "WITH _generated_dates(date_value) AS (SELECT CAST('2020-01-01' AS DATE) AS date_value UNION ALL SELECT CAST(DATEADD(WEEK, 1, date_value) AS DATE) AS date_value FROM _generated_dates WHERE CAST(DATEADD(WEEK, 1, date_value) AS DATE) < CAST('2020-02-01' AS DATE)) SELECT * FROM (SELECT date_value FROM _generated_dates) AS _generated_dates",
+ },
+ )
| [] | [
"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_defin... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Feat!: transpile Unnest(GenerateDateArray(...)) to various dialects
xref: https://github.com/TobikoData/sqlmesh/pull/2990
The motivation here is to make it easier to generate a date spine across several different dialects, by simply building a sqlglot expression that we can transpile when targeting them.
cc @sungchun12
----------
</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>
</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 | ||
astropy__astropy-16812 | 16,812 | astropy/astropy | v5.3 | c241103c11954d3c1cfe3c1840b1ece72479c522 | 2024-08-09T12:23:08Z | diff --git a/astropy/modeling/core.py b/astropy/modeling/core.py
index 1226f8cdf021..0e2393b6a895 100644
--- a/astropy/modeling/core.py
+++ b/astropy/modeling/core.py
@@ -2529,6 +2529,17 @@ def _initialize_constraints(self, kwargs):
values = kwargs.pop(constraint, [])
self._mconstraints[constraint] = values
+ def _reset_parameters(self, *args, **kwargs):
+ """
+ Reset parameters on the models to those specified.
+
+ Parameters can be specified either as positional arguments or keyword
+ arguments, as in the model initializer. Any parameters not specified
+ will be reset to their default values.
+ """
+ self._initialize_parameters(args, kwargs)
+ self._initialize_slices()
+
def _initialize_parameters(self, args, kwargs):
"""
Initialize the _parameters array that stores raw parameter values for
| diff --git a/astropy/modeling/tests/test_core.py b/astropy/modeling/tests/test_core.py
index 097a35cd60d2..3f4c460b243f 100644
--- a/astropy/modeling/tests/test_core.py
+++ b/astropy/modeling/tests/test_core.py
@@ -26,7 +26,7 @@
custom_model,
fix_inputs,
)
-from astropy.modeling.parameters import Parameter
+from astropy.modeling.parameters import InputParameterError, Parameter
from astropy.modeling.separable import separability_matrix
from astropy.tests.helper import PYTEST_LT_8_0, assert_quantity_allclose
from astropy.utils.compat.optional_deps import HAS_SCIPY
@@ -1570,3 +1570,84 @@ def test_has_constraints_with_sync_constraints():
model.sync_constraints = False
assert model.has_fixed
+
+
+def test_reset_parameters_simple():
+ # We test this as if it was a public method as once it has been used
+ # successfully internally we may make it public.
+
+ g = models.Gaussian1D(4, 2, 3)
+
+ # Check that calling reset_parameters with no arguments resets the
+ # parameters to default values
+ g._reset_parameters()
+ assert g.amplitude == 1
+ assert g.mean == 0
+ assert g.stddev == 1
+
+ # Set parameters via positional arguments
+ g._reset_parameters(5, 6, 7)
+ assert g.amplitude == 5
+ assert g.mean == 6
+ assert g.stddev == 7
+
+ # Set only some of the parameters via keyword arguments
+ g._reset_parameters(mean=8)
+ assert g.amplitude == 1
+ assert g.mean == 8
+ assert g.stddev == 1
+
+ # Set one of the parameters to an array
+ g._reset_parameters(amplitude=np.ones((2, 3, 4)))
+ assert_equal(g.amplitude, np.ones((2, 3, 4)))
+ assert g.mean == 0
+ assert g.stddev == 1
+
+ # Make sure we don't allow incompatible shapes to be passed
+ with pytest.raises(
+ InputParameterError,
+ match=re.escape(
+ "All parameter arrays must have shapes that are mutually compatible "
+ ),
+ ):
+ g._reset_parameters(amplitude=np.ones((2, 3, 4)), stddev=np.ones((8,)))
+
+
+def test_reset_parameters_compound():
+ # As above, but for compound models
+
+ c = models.Gaussian1D(4, 2, 3) + models.Const1D(9)
+
+ # Check that calling reset_parameters with no arguments resets the
+ # parameters to default values
+ c._reset_parameters()
+ assert c.amplitude_0 == 1
+ assert c.mean_0 == 0
+ assert c.stddev_0 == 1
+
+ # Set parameters via positional arguments
+ c._reset_parameters(5, 6, 7)
+ assert c.amplitude_0 == 5
+ assert c.mean_0 == 6
+ assert c.stddev_0 == 7
+
+ # Set only some of the parameters via keyword arguments
+ c._reset_parameters(mean_0=8)
+ assert c.amplitude_0 == 1
+ assert c.mean_0 == 8
+ assert c.stddev_0 == 1
+
+ # Set one of the parameters to an array
+ c._reset_parameters(amplitude_0=np.ones((2, 3, 4)))
+ assert_equal(c.amplitude_0, np.ones((2, 3, 4)))
+ assert c.mean_0 == 0
+ assert c.stddev_0 == 1
+
+ # Make sure we don't allow incompatible shapes to be passed
+ with pytest.raises(
+ InputParameterError,
+ match=re.escape(
+ "All parameter arrays must have shapes that are mutually compatible "
+ ),
+ ):
+ c._reset_parameters(amplitude_0=np.ones((2, 3, 4)), stddev_0=np.ones((8,)))
| [
{
"components": [
{
"doc": "Reset parameters on the models to those specified.\n\nParameters can be specified either as positional arguments or keyword\narguments, as in the model initializer. Any parameters not specified\nwill be reset to their default values.",
"lines": [
2532,... | [
"astropy/modeling/tests/test_core.py::test_reset_parameters_simple",
"astropy/modeling/tests/test_core.py::test_reset_parameters_compound"
] | [
"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_cu... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Provide a way to reinitialize the parameter values of a model
This provides a (simple) public method to reinitialize parameters in a model either to default values, or to specific values in the same way as through the model initializer. For example:
```python
In [1]: from astropy.modeling.models import Gaussian1D
In [3]: g = Gaussian1D(2, 3, 4)
In [4]: g.reset_parameters()
In [5]: g
Out[5]: <Gaussian1D(amplitude=1., mean=0., stddev=1.)>
In [6]: g.reset_parameters(5, 6, 7)
In [7]: g
Out[7]: <Gaussian1D(amplitude=5., mean=6., stddev=7.)>
In [8]: g.reset_parameters(mean=3) # all other parameters reset to default
In [9]: g
Out[9]: <Gaussian1D(amplitude=1., mean=3., stddev=1.)>
In [10]: g.reset_parameters(amplitude=[1, 2, 3]) # setting to array
In [11]: g
Out[11]: <Gaussian1D(amplitude=[1., 2., 3.], mean=0., stddev=1.)>
In [14]: g.reset_parameters(amplitude=3 * u.Jy) # adding units
In [15]: g
Out[15]: <Gaussian1D(amplitude=3. Jy, mean=0., stddev=1.)>
In [16]: g.reset_parameters(amplitude=3 * u.m) # changing to different units
In [17]: g
Out[17]: <Gaussian1D(amplitude=3. m, mean=0., stddev=1.)>
```
This is an alternative to https://github.com/astropy/astropy/pull/16806 and https://github.com/astropy/astropy/issues/16710
Closes #16806
Closes #16710
Closes #16593
- [ ] 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._reset_parameters:)
def _reset_parameters(self, *args, **kwargs):
"""Reset parameters on the models to those specified.
Parameters can be specified either as positional arguments or keyword
arguments, as in the model initializer. Any parameters not specified
will be reset to their default values."""
[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>> | Here is the discussion in the issues of the pull request.
<issues>
Provide a way to make a copy of a model with different parameter values, or be more flexible with parameter shape
GIven a model with scalar or array parameters, I would like to be able to easily make another model which has different parameter values (either scalar or array), while preserving other things (e.g. constraints, polynomial degree, etc). One can try the naive approach of making a copy of the model and then changing the parameters, but this doesn't always work:
### Common imports
```python
from astropy.modeling.models import Polynomial1D
import numpy as np
```
### Scalar :arrow_forward: Scalar
This case works fine:
```python
poly = Polynomial1D(2, c0=1, c1=3, c2=5)
poly.c0.fixed = True
poly.c1.bounds = [0, 10]
poly2 = poly.copy()
poly2.c0=1.5
poly2.c1=3.2
poly2.c2 = 5.5
```
### Array :arrow_forward: scalar
```python
poly = Polynomial1D(2, c0=np.ones((10, 10)), c1=np.ones((10, 10)) * 3, c2=np.ones((10, 10)) * 5)
poly.c0.fixed = True
poly.c1.bounds = [0, 10]
poly2 = poly.copy()
poly2.c0=1.5
poly2.c1=3.2
poly2.c2 = 5.5
```
This works ok because scalars are broadcastable to arrays. This is not ideal though as one temporarily has a copy of all the arrays in memory, and if the arrays are big it might be annoying.
### Array :arrow_forward: array
This does not work if the new array shape is not broadcastable to the old one:
```python
poly = Polynomial1D(2, c0=np.ones((10, 10)), c1=np.ones((10, 10)) * 3, c2=np.ones((10, 10)) * 5)
poly.c0.fixed = True
poly.c1.bounds = [0, 10]
poly2 = poly.copy()
poly2.c0=np.arange(5)
```
The error is:
```
InputParameterError: Value for parameter c0 does not match shape or size
expected by model ((5,), 5) vs ((10, 10), 100)
```
### Scalar :arrow_forward: Array
This does not work at all:
```python
poly = Polynomial1D(2, c0=1, c1=3, c2=5)
poly.c0.fixed = True
poly.c1.bounds = [0, 10]
poly2 = poly.copy()
poly2.c0=np.arange(5)
```
the error is:
```
InputParameterError: Value for parameter c0 does not match shape or size
expected by model ((5,), 5) vs ((1,), 1)
```
### Possible solutions
One option would not be to check the dimensions whenever parameters are set, but to instead validate them at the point where the model is called - otherwise it is not possible to change the parameters to have a shape that is not broadcastable to the current one.
Another option would be to have a way to do e.g. ``poly.copy_with_new_parameters(c0=np.arange(5), ...)`` or similar, that is, do a copy but replace the parameter *value* with the ones provided in the method call.
I'm open to other ideas though!
----------
https://github.com/astropy/astropy/pull/15750 would have worked for this.
`replace` is the new paradigm for dataclasses (which `astropy.models` are conceptually, if not in actual code).
`singledispatch` allows for us to make a function in astropy (or better yet a companion utility library), called `replace` that dispatches like this:
```python
@singledispatch
def replace(obj: Any, /, **kwargs: Any) -> Any:
raise NotImplementedError
@replace.register # a superset of python's dataclasses.replace!
def replace(obj: DataclassInstance, /, **kwargs: Any) -> DataclassInstance:
from dataclasses import replace
return replace(obj, **kwargs)
@replace.register # it works on anything!
def replace(obj: AstropyModel, /, **kwargs: Any) -> AstropyModel:
... whatever mechanism we want
return newobj
```
With this dispatcher, each sub-package in `astropy` can register copy-and-modify methods into a single tool.
Stick an example in the docstring `Examples` and it's easily discoverable.
Ok so after digging into this further, it *is* possible to get some of these examples to work by setting the parameter value instead of the top-level parameter, so e.g.:
```
poly = Polynomial1D(2, c0=1, c1=3, c2=5)
poly.c0.fixed = True
poly.c1.bounds = [0, 10]
poly2 = poly.copy()
poly2.c0.value=np.arange(5)
```
works, and if parameters are set with incompatible shapes an error is raised at model evaluation time, which I think is sensible. I guess the question is then should ``Model.__setattr__`` be more permissive to match what is possible by setting ``Parameter.value`` directly?
See #16710 for a bug that occurs when doing this though
--------------------
</issues> | 2d281019494aaebf522f6626c0dae37510c16688 | |
joke2k__faker-2081 | 2,081 | joke2k/faker | null | 5f05544cb49a355462726237e21babc534793878 | 2024-08-07T08:20:38Z | diff --git a/faker/providers/address/en_MS/__init__.py b/faker/providers/address/en_MS/__init__.py
new file mode 100644
index 0000000000..f614c3c018
--- /dev/null
+++ b/faker/providers/address/en_MS/__init__.py
@@ -0,0 +1,490 @@
+from collections import OrderedDict
+from typing import Optional
+
+from ... import ElementsType
+from ..en import Provider as AddressProvider
+
+# https://en.wikipedia.org/wiki/Addresses_in_Malaysia
+
+
+class Provider(AddressProvider):
+ # 'Bandar' and 'Taman' are the most common township prefix
+ # https://en.wikipedia.org/wiki/Template:Greater_Kuala_Lumpur > Townships
+ # https://en.wikipedia.org/wiki/Template:Johor > Townships
+ # https://en.wikipedia.org/wiki/Template:Kedah > Townships
+ # https://en.wikipedia.org/wiki/Template:Kelantan > Townships
+ # https://en.wikipedia.org/wiki/Template:Melaka > Townships
+ # https://en.wikipedia.org/wiki/Template:Negeri_Sembilan > Townships
+ # https://en.wikipedia.org/wiki/Template:Perak > Townships
+ # https://en.wikipedia.org/wiki/Template:Penang > Townships
+ # https://en.wikipedia.org/wiki/Template:Selangor > Townships
+ # https://en.wikipedia.org/wiki/Template:Terengganu > Townships
+
+ city_prefixes = (
+ "Alam",
+ "Apartment",
+ "Ara",
+ "Bandar",
+ "Bandar",
+ "Bandar",
+ "Bandar",
+ "Bandar",
+ "Bandar",
+ "Bandar Bukit",
+ "Bandar Seri",
+ "Bandar Sri",
+ "Bandar Baru",
+ "Batu",
+ "Bukit",
+ "Desa",
+ "Damansara",
+ "Kampung",
+ "Kampung Baru",
+ "Kampung Baru",
+ "Kondominium",
+ "Kota",
+ "Laman",
+ "Lembah",
+ "Medan",
+ "Pandan",
+ "Pangsapuri",
+ "Petaling",
+ "Puncak",
+ "Seri",
+ "Sri",
+ "Taman",
+ "Taman",
+ "Taman",
+ "Taman",
+ "Taman",
+ "Taman",
+ "Taman Desa",
+ )
+
+ city_suffixes = (
+ "Aman",
+ "Amanjaya",
+ "Anggerik",
+ "Angkasa",
+ "Antarabangsa",
+ "Awan",
+ "Bahagia",
+ "Bangsar",
+ "Baru",
+ "Belakong",
+ "Bendahara",
+ "Bestari",
+ "Bintang",
+ "Brickfields",
+ "Casa",
+ "Changkat",
+ "Country Heights",
+ "Damansara",
+ "Damai",
+ "Dato Harun",
+ "Delima",
+ "Duta",
+ "Flora",
+ "Gembira",
+ "Genting",
+ "Harmoni",
+ "Hartamas",
+ "Impian",
+ "Indah",
+ "Intan",
+ "Jasa",
+ "Jaya",
+ "Keramat",
+ "Kerinchi",
+ "Kiara",
+ "Kinrara",
+ "Kuchai",
+ "Laksamana",
+ "Mahkota",
+ "Maluri",
+ "Manggis",
+ "Maxwell",
+ "Medan",
+ "Melawati",
+ "Menjalara",
+ "Meru",
+ "Mulia",
+ "Mutiara",
+ "Pahlawan",
+ "Perdana",
+ "Pertama",
+ "Permai",
+ "Pelangi",
+ "Petaling",
+ "Pinang",
+ "Puchong",
+ "Puteri",
+ "Putra",
+ "Rahman",
+ "Rahmat",
+ "Raya",
+ "Razak",
+ "Ria",
+ "Saujana",
+ "Segambut",
+ "Selamat",
+ "Selatan",
+ "Semarak",
+ "Sentosa",
+ "Seputeh",
+ "Setapak",
+ "Setia Jaya",
+ "Sinar",
+ "Sungai Besi",
+ "Sungai Buaya",
+ "Sungai Long",
+ "Suria",
+ "Tasik Puteri",
+ "Tengah",
+ "Timur",
+ "Tinggi",
+ "Tropika",
+ "Tun Hussein Onn",
+ "Tun Perak",
+ "Tunku",
+ "Ulu",
+ "Utama",
+ "Utara",
+ "Wangi",
+ )
+
+ # https://en.wikipedia.org/wiki/States_and_federal_territories_of_Malaysia
+ states = {
+ "JHR": ["Johor Darul Ta'zim", "Johor"],
+ "KDH": ["Kedah Darul Aman", "Kedah"],
+ "KTN": ["Kelantan Darul Naim", "Kelantan"],
+ "KUL": ["KL", "Kuala Lumpur", "WP Kuala Lumpur"],
+ "LBN": ["Labuan"],
+ "MLK": ["Malacca", "Melaka"],
+ "NSN": ["Negeri Sembilan Darul Khusus", "Negeri Sembilan"],
+ "PHG": ["Pahang Darul Makmur", "Pahang"],
+ "PNG": ["Penang", "Pulau Pinang"],
+ "PRK": ["Perak Darul Ridzuan", "Perak"],
+ "PLS": ["Perlis Indera Kayangan", "Perlis"],
+ "PJY": ["Putrajaya"],
+ "SBH": ["Sabah"],
+ "SWK": ["Sarawak"],
+ "SGR": ["Selangor Darul Ehsan", "Selangor"],
+ "TRG": ["Terengganu Darul Iman", "Terengganu"],
+ }
+
+ states_postcode = {
+ "PLS": [(1000, 2800)],
+ "KDH": [(5000, 9810)],
+ "PNG": [(10000, 14400)],
+ "KTN": [(15000, 18500)],
+ "TRG": [(20000, 24300)],
+ "PHG": [
+ (25000, 28800),
+ (39000, 39200),
+ (49000, 69000),
+ ],
+ "PRK": [(30000, 36810)],
+ "SGR": [(40000, 48300), (63000, 68100)],
+ "KUL": [(50000, 60000)],
+ "PJY": [(62000, 62988)],
+ "NSN": [(70000, 73509)],
+ "MLK": [(75000, 78309)],
+ "JHR": [(79000, 86900)],
+ "LBN": [(87000, 87033)],
+ "SBH": [(88000, 91309)],
+ "SWK": [(93000, 98859)],
+ }
+
+ city_prefix_abbrs: ElementsType[str] = (
+ "SS",
+ "Seksyen ",
+ "PJS",
+ "PJU",
+ "USJ ",
+ )
+
+ def city_prefix_abbr(self) -> str:
+ return self.random_element(self.city_prefix_abbrs)
+
+ city_formats: ElementsType[str] = (
+ "{{city_prefix}} {{city_suffix}}",
+ "{{city_prefix}} {{city_suffix}}",
+ "{{city_prefix}} {{city_suffix}}",
+ "{{city_prefix}} {{city_suffix}}",
+ "{{city_prefix}} {{city_suffix}}",
+ "{{city_prefix}} {{city_suffix}}",
+ "{{city_prefix_abbr}}%",
+ "{{city_prefix_abbr}}%#",
+ "{{city_prefix_abbr}}%#?",
+ )
+
+ def city(self) -> str:
+ pattern: str = self.bothify(self.random_element(self.city_formats))
+ return self.generator.parse(pattern)
+
+ # https://en.wikipedia.org/wiki/List_of_roads_in_Kuala_Lumpur#Standard_translations
+ street_prefixes: ElementsType[str] = [
+ "Jln",
+ "Jln",
+ "Jalan",
+ "Jalan",
+ "Jalan",
+ "Lorong",
+ ]
+
+ def street_prefix(self) -> str:
+ return self.random_element(self.street_prefixes)
+
+ # https://en.wikipedia.org/wiki/List_of_roads_in_Kuala_Lumpur
+ # https://en.wikipedia.org/wiki/List_of_roads_in_Ipoh
+ # https://en.wikipedia.org/wiki/Transportation_in_Seremban#Inner_city_roads
+ # https://en.wikipedia.org/wiki/List_of_streets_in_George_Town,_Penang
+ street_suffixes: ElementsType[str] = [
+ "Air Itam",
+ "Alor",
+ "Ampang",
+ "Ampang Hilir",
+ "Anson",
+ "Ariffin",
+ "Bangsar",
+ "Baru",
+ "Bellamy",
+ "Birch",
+ "Bijih Timah",
+ "Bukit Aman",
+ "Bukit Bintang",
+ "Bukit Petaling",
+ "Bukit Tunku",
+ "Cantonment",
+ "Cenderawasih",
+ "Chan Sow Lin",
+ "Chow Kit",
+ "Cinta",
+ "Cochrane",
+ "Conlay",
+ "D. S. Ramanathan",
+ "Damansara",
+ "Dang Wangi",
+ "Davis",
+ "Dewan Bahasa",
+ "Dato Abdul Rahman",
+ "Dato'Keramat",
+ "Dato' Maharaja Lela",
+ "Doraisamy",
+ "Eaton",
+ "Faraday",
+ "Galloway",
+ "Genting Klang",
+ "Gereja",
+ "Hang Jebat",
+ "Hang Kasturi",
+ "Hang Lekir",
+ "Hang Lekiu",
+ "Hang Tuah",
+ "Hospital",
+ "Imbi",
+ "Istana",
+ "Jelutong",
+ "Kampung Attap",
+ "Kebun Bunga",
+ "Kedah",
+ "Keliling",
+ "Kia Peng",
+ "Kinabalu",
+ "Kuala Kangsar",
+ "Kuching",
+ "Ledang",
+ "Lembah Permai",
+ "Loke Yew",
+ "Lt. Adnan",
+ "Lumba Kuda",
+ "Madras",
+ "Magazine",
+ "Maharajalela",
+ "Masjid",
+ "Maxwell",
+ "Mohana Chandran",
+ "Muda",
+ "P. Ramlee",
+ "Padang Kota Lama",
+ "Pahang",
+ "Pantai Baharu",
+ "Parlimen",
+ "Pasar",
+ "Pasar Besar",
+ "Perak",
+ "Perdana",
+ "Petaling",
+ "Prangin",
+ "Pudu",
+ "Pudu Lama",
+ "Raja",
+ "Raja Abdullah",
+ "Raja Chulan",
+ "Raja Laut",
+ "Rakyat",
+ "Residensi",
+ "Robson",
+ "S.P. Seenivasagam",
+ "Samarahan 1",
+ "Selamat",
+ "Sempadan",
+ "Sentul",
+ "Serian 1",
+ "Sasaran",
+ "Sin Chee",
+ "Sultan Abdul Samad",
+ "Sultan Azlan Shah",
+ "Sultan Iskandar",
+ "Sultan Ismail",
+ "Sultan Sulaiman",
+ "Sungai Besi",
+ "Syed Putra",
+ "Tan Cheng Lock",
+ "Thambipillay",
+ "Tugu",
+ "Tuanku Abdul Halim",
+ "Tuanku Abdul Rahman",
+ "Tun Abdul Razak",
+ "Tun Dr Ismail",
+ "Tun H S Lee",
+ "Tun Ismail",
+ "Tun Perak",
+ "Tun Razak",
+ "Tun Sambanthan",
+ "U-Thant",
+ "Utama",
+ "Vermont",
+ "Vivekananda",
+ "Wan Kadir",
+ "Wesley",
+ "Wisma Putra",
+ "Yaacob Latif",
+ "Yap Ah Loy",
+ "Yap Ah Shak",
+ "Yap Kwan Seng",
+ "Yew",
+ "Zaaba",
+ "Zainal Abidin",
+ ]
+
+ street_name_formats: ElementsType[str] = (
+ "{{street_prefix}} %",
+ "{{street_prefix}} %/%",
+ "{{street_prefix}} %/%#",
+ "{{street_prefix}} %/%?",
+ "{{street_prefix}} %/%#?",
+ "{{street_prefix}} %?",
+ "{{street_prefix}} %#?",
+ "{{street_prefix}} {{street_suffix}}",
+ "{{street_prefix}} {{street_suffix}} %",
+ "{{street_prefix}} {{street_suffix}} %/%",
+ "{{street_prefix}} {{street_suffix}} %/%#",
+ "{{street_prefix}} {{street_suffix}} %/%?",
+ "{{street_prefix}} {{street_suffix}} %/%#?",
+ "{{street_prefix}} {{street_suffix}} %?",
+ "{{street_prefix}} {{street_suffix}} %#?",
+ )
+
+ def street_name(self) -> str:
+ """
+ :example: 'Crist Parks'
+ """
+ pattern: str = self.bothify(self.random_element(self.street_name_formats))
+ return self.generator.parse(pattern)
+
+ building_prefixes: ElementsType[str] = [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "No. ",
+ "No. ",
+ "No. ",
+ "Lot ",
+ ]
+
+ def building_prefix(self) -> str:
+ return self.random_element(self.building_prefixes)
+
+ building_number_formats: ElementsType[str] = (
+ "%",
+ "%",
+ "%",
+ "%#",
+ "%#",
+ "%#",
+ "%#",
+ "%##",
+ "%-%",
+ "?-##-##",
+ "%?-##",
+ )
+
+ def building_number(self) -> str:
+ return self.bothify(self.random_element(self.building_number_formats))
+
+ street_address_formats: ElementsType[str] = (
+ "{{building_prefix}}{{building_number}}, {{street_name}}",
+ )
+
+ def city_state(self) -> str:
+ """Return the complete city address with matching postcode and state
+
+ Example: 55100 Bukit Bintang, Kuala Lumpur
+ """
+ state = self.random_element(self.states.keys())
+ postcode = self.postcode_in_state(state)
+ city = self.city()
+ state_name = self.random_element(self.states[state])
+
+ return f"{postcode} {city}, {state_name}"
+
+ # https://en.wikipedia.org/wiki/Addresses_in_Malaysia
+ # street number, street name, region, and town/city, state.
+ address_formats = OrderedDict(
+ (("{{street_address}}, {{city}}, {{city_state}}", 100.0),)
+ )
+
+ def city_prefix(self) -> str:
+ return self.random_element(self.city_prefixes)
+
+ def administrative_unit(self) -> str:
+ return self.random_element(self.states[self.random_element(self.states.keys())])
+
+ state = administrative_unit
+
+ def postcode_in_state(self, state_abbr: Optional[str] = None) -> str:
+ """
+ :returns: A random postcode within the provided state
+
+ :param state: A state
+
+ Example: 55100
+ https://en.wikipedia.org/wiki/Postal_codes_in_Malaysia#States
+ """
+
+ if state_abbr is None:
+ state_abbr = self.random_element(self.states.keys())
+
+ try:
+ # some states have multiple ranges so first pick one, then generate a random postcode
+ range = self.generator.random.choice(self.states_postcode[state_abbr])
+ postcode = "%d" % (self.generator.random.randint(*range))
+
+ # zero left pad up until desired length (some have length 3 or 4)
+ target_postcode_len = 5
+ current_postcode_len = len(postcode)
+ if current_postcode_len < target_postcode_len:
+ pad = target_postcode_len - current_postcode_len
+ postcode = f"{'0'*pad}{postcode}"
+
+ return postcode
+ except KeyError as e:
+ raise KeyError("State Abbreviation not found in list") from e
+
+ def postcode(self) -> str:
+ return self.postcode_in_state(None)
| diff --git a/tests/providers/test_address.py b/tests/providers/test_address.py
index 45607994cf..518c59fd88 100644
--- a/tests/providers/test_address.py
+++ b/tests/providers/test_address.py
@@ -19,6 +19,7 @@
from faker.providers.address.en_GB import Provider as EnGbAddressProvider
from faker.providers.address.en_IE import Provider as EnIeAddressProvider
from faker.providers.address.en_IN import Provider as EnInAddressProvider
+from faker.providers.address.en_MS import Provider as EnMsAddressProvider
from faker.providers.address.en_NZ import Provider as EnNzAddressProvider
from faker.providers.address.en_PH import Provider as EnPhAddressProvider
from faker.providers.address.en_US import Provider as EnUsAddressProvider
@@ -2030,6 +2031,91 @@ def test_city_with_postcode(self, faker, num_samples):
assert match.group("city") in RoRoAddressProvider.cities
+class TestEnMs:
+ """Test en_MS address provider methods"""
+
+ def test_city_prefix_abbr(self, faker, num_samples):
+ for _ in range(num_samples):
+ city_prefix_abbr = faker.city_prefix_abbr()
+ assert isinstance(city_prefix_abbr, str)
+ assert city_prefix_abbr in EnMsAddressProvider.city_prefix_abbrs
+
+ def test_city_prefix(self, faker, num_samples):
+ for _ in range(num_samples):
+ city_prefix = faker.city_prefix()
+ assert isinstance(city_prefix, str)
+ assert city_prefix in EnMsAddressProvider.city_prefixes
+
+ def test_city(self, faker, num_samples):
+ for _ in range(num_samples):
+ city = faker.city()
+ assert isinstance(city, str)
+ assert "%" not in city
+ assert "#" not in city
+ assert "?" not in city
+
+ def test_street_prefix(self, faker, num_samples):
+ for _ in range(num_samples):
+ street_prefix = faker.street_prefix()
+ assert isinstance(street_prefix, str)
+ assert street_prefix in EnMsAddressProvider.street_prefixes
+
+ def test_street_name(self, faker, num_samples):
+ for _ in range(num_samples):
+ street_name = faker.street_name()
+ assert isinstance(street_name, str)
+
+ def test_building_prefix(self, faker, num_samples):
+ for _ in range(num_samples):
+ building_prefix = faker.building_prefix()
+ assert isinstance(building_prefix, str)
+
+ def test_building_number(self, faker, num_samples):
+ for _ in range(num_samples):
+ building_number = faker.building_number()
+ assert isinstance(building_number, str)
+
+ def test_city_state(self, faker, num_samples):
+ for _ in range(num_samples):
+ city_state = faker.city_state()
+ assert isinstance(city_state, str)
+
+ @pytest.mark.parametrize(
+ "fn_name",
+ [
+ ("administrative_unit"),
+ ("state"),
+ ],
+ )
+ def test_state_administrative_unit(self, faker, num_samples, fn_name):
+ for _ in range(num_samples):
+ state = getattr(faker, fn_name)()
+ assert isinstance(state, str)
+ assert state in [
+ x for v in EnMsAddressProvider.states.values() for x in v
+ ]
+
+ def test_postcode_in_state(self, faker, num_samples):
+ for _ in range(num_samples):
+ for state_abbr in EnMsAddressProvider.states.keys():
+ code = faker.postcode_in_state(state_abbr)
+ assert re.fullmatch(r"\d{5}", code)
+ assert (
+ int(code) >= EnMsAddressProvider.states_postcode[state_abbr][0][0]
+ )
+ assert (
+ int(code) <= EnMsAddressProvider.states_postcode[state_abbr][-1][1]
+ )
+
+ with pytest.raises(KeyError):
+ faker.postcode_in_state("XX")
+
+ def test_postcode(self, faker, num_samples):
+ for _ in range(num_samples):
+ code = faker.postcode()
+ assert re.fullmatch(r"\d{5}", code)
+
+
class TestEnNz:
"""Test en_NZ address provider methods"""
| [
{
"components": [
{
"doc": "",
"lines": [
10,
490
],
"name": "Provider",
"signature": "class Provider(AddressProvider):",
"type": "class"
},
{
"doc": "",
"lines": [
207,
208
],
... | [
"tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes",
"tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes_as_default",
"tests/providers/test_address.py::TestBaseProvider::test_alpha_3_country_codes",
"tests/providers/test_address.py::TestBaseProvider::test... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add en_MS Malaysian provider
### What does this change
Add the en_MS provider just for addresses. This is pretty much a straight port from [PHP Faker](https://github.com/fzaninotto/Faker/blob/master/src/Faker/Provider/ms_MY/Address.php) with some improved state abbreviations.
----------
</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/address/en_MS/__init__.py]
(definition of Provider:)
class Provider(AddressProvider):
(definition of Provider.city_prefix_abbr:)
def city_prefix_abbr(self) -> str:
(definition of Provider.city:)
def city(self) -> str:
(definition of Provider.street_prefix:)
def street_prefix(self) -> str:
(definition of Provider.street_name:)
def street_name(self) -> str:
""":example: 'Crist Parks'"""
(definition of Provider.building_prefix:)
def building_prefix(self) -> str:
(definition of Provider.building_number:)
def building_number(self) -> str:
(definition of Provider.city_state:)
def city_state(self) -> str:
"""Return the complete city address with matching postcode and state
Example: 55100 Bukit Bintang, Kuala Lumpur"""
(definition of Provider.city_prefix:)
def city_prefix(self) -> str:
(definition of Provider.administrative_unit:)
def administrative_unit(self) -> str:
(definition of Provider.postcode_in_state:)
def postcode_in_state(self, state_abbr: Optional[str] = None) -> str:
""":returns: A random postcode within the provided state
:param state: A state
Example: 55100
https://en.wikipedia.org/wiki/Postal_codes_in_Malaysia#States"""
(definition of Provider.postcode:)
def postcode(self) -> str:
[end of new definitions in faker/providers/address/en_MS/__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 | ||
tobymao__sqlglot-3883 | 3,883 | tobymao/sqlglot | null | 3e4fcf7e8f6a322c14470de6c5dbba152bc9b2fe | 2024-08-07T08:18:11Z | diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py
index 2fa355e58f..145a7d1cb2 100644
--- a/sqlglot/dialects/mysql.py
+++ b/sqlglot/dialects/mysql.py
@@ -302,6 +302,9 @@ class Parser(parser.Parser):
FUNCTIONS = {
**parser.Parser.FUNCTIONS,
+ "CONVERT_TZ": lambda args: exp.ConvertTimezone(
+ source_tz=seq_get(args, 1), target_tz=seq_get(args, 2), timestamp=seq_get(args, 0)
+ ),
"DATE": lambda args: exp.TsOrDsToDate(this=seq_get(args, 0)),
"DATE_ADD": build_date_delta_with_interval(exp.DateAdd),
"DATE_FORMAT": build_formatted_time(exp.TimeToStr, "mysql"),
@@ -1213,3 +1216,10 @@ def timestamptrunc_sql(self, expression: exp.TimestampTrunc) -> str:
dateadd = build_date_delta_with_interval(exp.DateAdd)([start_ts, interval])
return self.sql(dateadd)
+
+ def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
+ from_tz = expression.args.get("source_tz")
+ to_tz = expression.args.get("target_tz")
+ dt = expression.args.get("timestamp")
+
+ return self.func("CONVERT_TZ", dt, from_tz, to_tz)
diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py
index 5e1fa4322e..b39a9a5024 100644
--- a/sqlglot/dialects/redshift.py
+++ b/sqlglot/dialects/redshift.py
@@ -17,6 +17,7 @@
from sqlglot.dialects.postgres import Postgres
from sqlglot.helper import seq_get
from sqlglot.tokens import TokenType
+from sqlglot.parser import build_convert_timezone
if t.TYPE_CHECKING:
from sqlglot._typing import E
@@ -63,6 +64,7 @@ class Parser(Postgres.Parser):
unit=exp.var("month"),
return_type=exp.DataType.build("TIMESTAMP"),
),
+ "CONVERT_TIMEZONE": lambda args: build_convert_timezone(args, "UTC"),
"DATEADD": _build_date_delta(exp.TsOrDsAdd),
"DATE_ADD": _build_date_delta(exp.TsOrDsAdd),
"DATEDIFF": _build_date_delta(exp.TsOrDsDiff),
@@ -155,6 +157,7 @@ class Generator(Postgres.Generator):
HEX_FUNC = "TO_HEX"
PARSE_JSON_NAME = "JSON_PARSE"
ARRAY_CONCAT_IS_VAR_LEN = False
+ SUPPORTS_CONVERT_TIMEZONE = True
# Redshift doesn't have `WITH` as part of their with_properties so we remove it
WITH_PROPERTIES_PREFIX = " "
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index 81db3190f7..58fdb62015 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -122,12 +122,6 @@ def _regexpilike_sql(self: Snowflake.Generator, expression: exp.RegexpILike) ->
)
-def _build_convert_timezone(args: t.List) -> t.Union[exp.Anonymous, exp.AtTimeZone]:
- if len(args) == 3:
- return exp.Anonymous(this="CONVERT_TIMEZONE", expressions=args)
- return exp.AtTimeZone(this=seq_get(args, 1), zone=seq_get(args, 0))
-
-
def _build_regexp_replace(args: t.List) -> exp.RegexpReplace:
regexp_replace = exp.RegexpReplace.from_arg_list(args)
@@ -268,7 +262,6 @@ class Parser(parser.Parser):
"BITXOR": binary_from_function(exp.BitwiseXor),
"BIT_XOR": binary_from_function(exp.BitwiseXor),
"BOOLXOR": binary_from_function(exp.Xor),
- "CONVERT_TIMEZONE": _build_convert_timezone,
"DATE": _build_datetime("DATE", exp.DataType.Type.DATE),
"DATE_TRUNC": _date_trunc_to_time,
"DATEADD": _build_date_time_add(exp.DateAdd),
@@ -694,6 +687,7 @@ class Generator(generator.Generator):
STAR_EXCEPT = "EXCLUDE"
SUPPORTS_EXPLODING_PROJECTIONS = False
ARRAY_CONCAT_IS_VAR_LEN = False
+ SUPPORTS_CONVERT_TIMEZONE = True
TRANSFORMS = {
**generator.Generator.TRANSFORMS,
diff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py
index 35944d52a8..410c12e010 100644
--- a/sqlglot/dialects/spark.py
+++ b/sqlglot/dialects/spark.py
@@ -132,6 +132,7 @@ def _parse_generated_as_identity(
class Generator(Spark2.Generator):
SUPPORTS_TO_NUMBER = True
PAD_FILL_PATTERN_IS_REQUIRED = False
+ SUPPORTS_CONVERT_TIMEZONE = True
TYPE_MAPPING = {
**Spark2.Generator.TYPE_MAPPING,
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 5250f37948..40036f50dd 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -4840,6 +4840,10 @@ class Convert(Func):
arg_types = {"this": True, "expression": True, "style": False}
+class ConvertTimezone(Func):
+ arg_types = {"source_tz": False, "target_tz": True, "timestamp": True}
+
+
class GenerateSeries(Func):
arg_types = {"start": True, "end": True, "step": False, "is_end_exclusive": False}
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index 3b61cb5755..63ccfcbfb7 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -378,6 +378,9 @@ class Generator(metaclass=_Generator):
# Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version
ARRAY_CONCAT_IS_VAR_LEN = True
+ # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone
+ SUPPORTS_CONVERT_TIMEZONE = False
+
# The name to generate for the JSONPath expression. If `None`, only `this` will be generated
PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
@@ -4079,3 +4082,20 @@ def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT
rhs = self.expressions(expression)
return self.func(name, expression.this, rhs)
+
+ def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
+ if self.SUPPORTS_CONVERT_TIMEZONE:
+ return self.function_fallback_sql(expression)
+
+ source_tz = expression.args.get("source_tz")
+ target_tz = expression.args.get("target_tz")
+ timestamp = expression.args.get("timestamp")
+
+ if source_tz and timestamp:
+ timestamp = exp.AtTimeZone(
+ this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
+ )
+
+ expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
+
+ return self.sql(expr)
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index cd02877435..ec1c8f6be2 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -128,6 +128,18 @@ def build_array_constructor(
return array_exp
+def build_convert_timezone(
+ args: t.List, default_source_tz: t.Optional[str] = None
+) -> t.Union[exp.ConvertTimezone, exp.Anonymous]:
+ if len(args) == 2:
+ source_tz = exp.Literal.string(default_source_tz) if default_source_tz else None
+ return exp.ConvertTimezone(
+ source_tz=source_tz, target_tz=seq_get(args, 0), timestamp=seq_get(args, 1)
+ )
+
+ return exp.ConvertTimezone.from_arg_list(args)
+
+
class _Parser(type):
def __new__(cls, clsname, bases, attrs):
klass = super().__new__(cls, clsname, bases, attrs)
@@ -166,6 +178,7 @@ class Parser(metaclass=_Parser):
safe=not dialect.STRICT_STRING_CONCAT,
coalesce=dialect.CONCAT_COALESCE,
),
+ "CONVERT_TIMEZONE": build_convert_timezone,
"DATE_TO_DATE_STR": lambda args: exp.Cast(
this=seq_get(args, 0),
to=exp.DataType(this=exp.DataType.Type.TEXT),
| diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py
index 9e672ec1f1..22d8f624ab 100644
--- a/tests/dialects/test_redshift.py
+++ b/tests/dialects/test_redshift.py
@@ -433,6 +433,11 @@ def test_identity(self):
self.validate_identity("SELECT ARRAY(1, 2, 3)")
self.validate_identity("SELECT ARRAY[1, 2, 3]")
+ self.validate_identity(
+ """SELECT CONVERT_TIMEZONE('America/New_York', '2024-08-06 09:10:00.000')""",
+ """SELECT CONVERT_TIMEZONE('UTC', 'America/New_York', '2024-08-06 09:10:00.000')""",
+ )
+
def test_values(self):
# Test crazy-sized VALUES clause to UNION ALL conversion to ensure we don't get RecursionError
values = [str(v) for v in range(0, 10000)]
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py
index 16ef019699..78d01b20d9 100644
--- a/tests/dialects/test_snowflake.py
+++ b/tests/dialects/test_snowflake.py
@@ -865,6 +865,28 @@ def test_snowflake(self):
"""SELECT CAST(['foo'] AS VARIANT)[0]""",
)
+ self.validate_all(
+ "SELECT CONVERT_TIMEZONE('America/New_York', '2024-08-06 09:10:00.000')",
+ write={
+ "snowflake": "SELECT CONVERT_TIMEZONE('America/New_York', '2024-08-06 09:10:00.000')",
+ "spark": "SELECT CONVERT_TIMEZONE('America/New_York', '2024-08-06 09:10:00.000')",
+ "databricks": "SELECT CONVERT_TIMEZONE('America/New_York', '2024-08-06 09:10:00.000')",
+ "redshift": "SELECT CONVERT_TIMEZONE('America/New_York', '2024-08-06 09:10:00.000')",
+ },
+ )
+
+ self.validate_all(
+ "SELECT CONVERT_TIMEZONE('America/Los_Angeles', 'America/New_York', '2024-08-06 09:10:00.000')",
+ write={
+ "snowflake": "SELECT CONVERT_TIMEZONE('America/Los_Angeles', 'America/New_York', '2024-08-06 09:10:00.000')",
+ "spark": "SELECT CONVERT_TIMEZONE('America/Los_Angeles', 'America/New_York', '2024-08-06 09:10:00.000')",
+ "databricks": "SELECT CONVERT_TIMEZONE('America/Los_Angeles', 'America/New_York', '2024-08-06 09:10:00.000')",
+ "redshift": "SELECT CONVERT_TIMEZONE('America/Los_Angeles', 'America/New_York', '2024-08-06 09:10:00.000')",
+ "mysql": "SELECT CONVERT_TZ('2024-08-06 09:10:00.000', 'America/Los_Angeles', 'America/New_York')",
+ "duckdb": "SELECT CAST('2024-08-06 09:10:00.000' AS TIMESTAMP) AT TIME ZONE 'America/Los_Angeles' AT TIME ZONE 'America/New_York'",
+ },
+ )
+
def test_null_treatment(self):
self.validate_all(
r"SELECT FIRST_VALUE(TABLE1.COLUMN1) OVER (PARTITION BY RANDOM_COLUMN1, RANDOM_COLUMN2 ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS MY_ALIAS FROM TABLE1",
| [] | [
"tests/dialects/test_redshift.py::TestRedshift::test_identity",
"tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"
] | [
"tests/dialects/test_redshift.py::TestRedshift::test_alter_table",
"tests/dialects/test_redshift.py::TestRedshift::test_column_unnesting",
"tests/dialects/test_redshift.py::TestRedshift::test_create_table_like",
"tests/dialects/test_redshift.py::TestRedshift::test_join_markers",
"tests/dialects/test_redshif... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(duckdb): Transpile Snowflake's CONVERT_TIMEZONE 3-arg version
Fixes #3875
This PR attempts to transpile Snowflake's `CONVERT_TIMEZONE(source_tz, target_tz, timestamp_ntz)` 3-arg version to DuckDB.
Although there isn't a 1:1 mapping, the same result can be acquired by generating nested `TIMEZONE()` calls in DuckDB:
```SQL
TIMEZONE(target_tz, TIMEZONE(source_tz, timestamp_ntz::TIMESTAMP))
```
For instance:
```
Snowflake
--------------
SELECT CONVERT_TIMEZONE('AMERICA/LOS_ANGELES', 'AMERICA/NEW_YORK', '2024-08-06 09:10:00.000')
2024-08-06 12:10:00.000
DuckDB
------------
SELECT TIMEZONE('America/New_York', TIMEZONE('America/Los_Angeles', CAST('2024-08-06 09:10:00.000' AS TIMESTAMP)))
2024-08-06 12:10:00
```
Docs
--------
[Snowflake CONVERT_TIMEZONE](https://docs.snowflake.com/en/sql-reference/functions/convert_timezone) | [DuckDB TIMEZONE](https://duckdb.org/docs/sql/functions/timestamptz.html#timezonetext-timestamp)
----------
</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>
</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>
transpile from snowflake to duckdb with convert timezone is not working
**Fully reproducible code snippet**
The following snowflake query is transpile into a duckdb and fails
```
SELECT date_trunc('month', CONVERT_TIMEZONE('UTC', 'Europe/Berlin', anchor_hour)) AS ANCHOR,
SUM(sum_paid_usd) AS SUM_PAID,
SUM(CASE WHEN anchor_hour > current_timestamp() THEN sum_due_not_paid ELSE 0 END) AS SUM_UPCOMING,
SUM(CASE WHEN anchor_hour < current_timestamp() THEN sum_due_not_paid ELSE 0 END) AS SUM_OVERDUE,
SUM(count_paid_through_hb_usd) AS COUNT_PAID,
SUM(CASE WHEN anchor_hour > current_timestamp() THEN count_due_not_paid ELSE 0 END) AS COUNT_UPCOMING,
SUM(CASE WHEN anchor_hour < current_timestamp() THEN count_due_not_paid ELSE 0 END) AS COUNT_OVERDUE,
FROM pdt_mongo_payment_reporting_aggregated
WHERE company_id = '1111' AND anchor_hour BETWEEN '2023-12-31 23:00:00+00:00' AND '2024-07-31 21:59:59.999000+00:00'
GROUP BY 1
ORDER BY 1 ASC;
```
python code `transpile(raw, read="snowflake", write="duckdb", pretty=True)[0]`
Output query:
```
SELECT
DATE_TRUNC('MONTH', CONVERT_TIMEZONE('UTC', 'Europe/Berlin', anchor_hour)) AS ANCHOR,
SUM(sum_paid_usd) AS SUM_PAID,
SUM(CASE WHEN anchor_hour > CURRENT_TIMESTAMP THEN sum_due_not_paid ELSE 0 END) AS SUM_UPCOMING,
SUM(CASE WHEN anchor_hour < CURRENT_TIMESTAMP THEN sum_due_not_paid ELSE 0 END) AS SUM_OVERDUE,
SUM(count_paid_through_hb_usd) AS COUNT_PAID,
SUM(CASE WHEN anchor_hour > CURRENT_TIMESTAMP THEN count_due_not_paid ELSE 0 END) AS COUNT_UPCOMING,
SUM(CASE WHEN anchor_hour < CURRENT_TIMESTAMP THEN count_due_not_paid ELSE 0 END) AS COUNT_OVERDUE
FROM pdt_mongo_payment_reporting_aggregated
WHERE
company_id = '1111'
AND anchor_hour BETWEEN '2023-12-31 23:00:00+00:00' AND '2024-07-31 21:59:59.999000+00:00'
GROUP BY
1
ORDER BY
1 ASC```
The `CONVERT_TIMEZONE` is not correct. fixing it to `timezone('Europe/Berlin', anchor_hour)` solves the issue. I believe that the issue is that we are converting from specific TZ to another TZ but I'm not sure.
----------
Hey @milonimrod,
Thanks for reporting this. From what I see, in Snowflake `CONVERT_TIMEZONE` has two versions depending on the parameter count, with the 3-arg version being `CONVERT_TIMEZONE(source_tz, target_tz, timestamp_ntz)`; This means that Snowflake can take a `TIMESTAMP` without timezone information and transform it to `target_tz` as if it was originally in `source_tz`.
DuckDB also has two versions of `TIMEZONE(text, timestamp / timestamp_tz)`, but the version that accepts a timestamp **without** timezone information will convert it to the `target_tz` as if it was originally in local time. Your solution works because you used `UTC`, but if the `source_tz` was different there'd be a difference in results afaict.
I've not been able to find a complete Snowflake -> DuckDB transpilation for it yet but hopefully it can be pieced together.
Hi @milonimrod,
I'm trying to understand how we can transform the 3-arg variant in Snowflake. DuckDB doesn't have a similar function where you can specify the source timezone, i.e. what timezone the input timestamp's in. It seems like in your example you omitted `'UTC'` altogether, but I'm not sure if this is correct. Is `anchor_hour` already a timestamp with UTC time zone, i.e. has type `TIMESTAMPTZ`? If not, DuckDB's [docs](https://duckdb.org/docs/sql/functions/timestamptz.html#timezonetext-timestamp) indicate that it will be interpreted in local time.
The 3-arg variant is not being transpiled intentionally because other dialects don't support this concept IIRC. I'm leaning towards closing this as not planned for now, but feel free to share ideas and I'll take another look later.
Hi, thank you for the quick response. Is there a way to create the mapping in duckDB by running the 3 args version as two nested calls?
The first will be to convert FROM tz1 to UTC and the second call from UTC TO tz2.
Is this an option?
--------------------
</issues> | ceb42fabad60312699e4b15936aeebac00e22e4d | |
boto__botocore-3233 | 3,233 | boto/botocore | null | b3fb4d01d35cabd896b64f66afbd013b245069d8 | 2024-08-06T15:22:16Z | diff --git a/.changes/next-release/enhancement-signing-83434.json b/.changes/next-release/enhancement-signing-83434.json
new file mode 100644
index 0000000000..a90654a772
--- /dev/null
+++ b/.changes/next-release/enhancement-signing-83434.json
@@ -0,0 +1,5 @@
+{
+ "type": "feature",
+ "category": "signing",
+ "description": "Adds internal support for the new 'auth' trait to allow a priority list of auth types for a service or operation."
+}
diff --git a/botocore/args.py b/botocore/args.py
index 758a3c3c92..741ca77886 100644
--- a/botocore/args.py
+++ b/botocore/args.py
@@ -268,6 +268,9 @@ def compute_client_args(
client_config.disable_request_compression
),
client_context_params=client_config.client_context_params,
+ sigv4a_signing_region_set=(
+ client_config.sigv4a_signing_region_set
+ ),
)
self._compute_retry_config(config_kwargs)
self._compute_connect_timeout(config_kwargs)
diff --git a/botocore/auth.py b/botocore/auth.py
index 6b296cfaaa..66e605a665 100644
--- a/botocore/auth.py
+++ b/botocore/auth.py
@@ -35,7 +35,12 @@
urlsplit,
urlunsplit,
)
-from botocore.exceptions import NoAuthTokenError, NoCredentialsError
+from botocore.exceptions import (
+ NoAuthTokenError,
+ NoCredentialsError,
+ UnknownSignatureVersionError,
+ UnsupportedSignatureVersionError,
+)
from botocore.utils import (
is_valid_ipv6_endpoint_url,
normalize_url_path,
@@ -1132,6 +1137,19 @@ def add_auth(self, request):
request.headers['Authorization'] = auth_header
+def resolve_auth_type(auth_trait):
+ for auth_type in auth_trait:
+ if auth_type == 'smithy.api#noAuth':
+ return AUTH_TYPE_TO_SIGNATURE_VERSION[auth_type]
+ elif auth_type in AUTH_TYPE_TO_SIGNATURE_VERSION:
+ signature_version = AUTH_TYPE_TO_SIGNATURE_VERSION[auth_type]
+ if signature_version in AUTH_TYPE_MAPS:
+ return signature_version
+ else:
+ raise UnknownSignatureVersionError(signature_version=auth_type)
+ raise UnsupportedSignatureVersionError(signature_version=auth_trait)
+
+
AUTH_TYPE_MAPS = {
'v2': SigV2Auth,
'v3': SigV3Auth,
@@ -1160,3 +1178,10 @@ def add_auth(self, request):
's3v4-query': S3SigV4QueryAuth,
}
)
+
+AUTH_TYPE_TO_SIGNATURE_VERSION = {
+ 'aws.auth#sigv4': 'v4',
+ 'aws.auth#sigv4a': 'v4a',
+ 'smithy.api#httpBearerAuth': 'bearer',
+ 'smithy.api#noAuth': 'none',
+}
diff --git a/botocore/client.py b/botocore/client.py
index e57d1ded31..ab1be75365 100644
--- a/botocore/client.py
+++ b/botocore/client.py
@@ -14,7 +14,7 @@
from botocore import waiter, xform_name
from botocore.args import ClientArgsCreator
-from botocore.auth import AUTH_TYPE_MAPS
+from botocore.auth import AUTH_TYPE_MAPS, resolve_auth_type
from botocore.awsrequest import prepare_request_dict
from botocore.compress import maybe_compress_request
from botocore.config import Config
@@ -148,15 +148,19 @@ def create_client(
region_name, client_config = self._normalize_fips_region(
region_name, client_config
)
+ if auth := service_model.metadata.get('auth'):
+ service_signature_version = resolve_auth_type(auth)
+ else:
+ service_signature_version = service_model.metadata.get(
+ 'signatureVersion'
+ )
endpoint_bridge = ClientEndpointBridge(
self._endpoint_resolver,
scoped_config,
client_config,
service_signing_name=service_model.metadata.get('signingName'),
config_store=self._config_store,
- service_signature_version=service_model.metadata.get(
- 'signatureVersion'
- ),
+ service_signature_version=service_signature_version,
)
client_args = self._get_client_args(
service_model,
@@ -487,7 +491,7 @@ def _default_s3_presign_to_sigv2(self, signature_version, **kwargs):
return
if signature_version.startswith('v4-s3express'):
- return f'{signature_version}'
+ return signature_version
for suffix in ['-query', '-presign-post']:
if signature_version.endswith(suffix):
@@ -953,8 +957,10 @@ def _make_api_call(self, operation_name, api_params):
'client_region': self.meta.region_name,
'client_config': self.meta.config,
'has_streaming_input': operation_model.has_streaming_input,
- 'auth_type': operation_model.auth_type,
+ 'auth_type': operation_model.resolved_auth_type,
+ 'unsigned_payload': operation_model.unsigned_payload,
}
+
api_params = self._emit_api_params(
api_params=api_params,
operation_model=operation_model,
diff --git a/botocore/config.py b/botocore/config.py
index 87b52b6f1a..587dc95ad8 100644
--- a/botocore/config.py
+++ b/botocore/config.py
@@ -221,6 +221,12 @@ class Config:
Defaults to None.
+ :type sigv4a_signing_region_set: string
+ :param sigv4a_signing_region_set: A set of AWS regions to apply the signature for
+ when using SigV4a for signing. Set to ``*`` to represent all regions.
+
+ Defaults to None.
+
:type client_context_params: dict
:param client_context_params: A dictionary of parameters specific to
individual services. If available, valid parameters can be found in
@@ -257,6 +263,7 @@ class Config:
('request_min_compression_size_bytes', None),
('disable_request_compression', None),
('client_context_params', None),
+ ('sigv4a_signing_region_set', None),
]
)
diff --git a/botocore/configprovider.py b/botocore/configprovider.py
index 5ed2dc63ce..b0dd09f09f 100644
--- a/botocore/configprovider.py
+++ b/botocore/configprovider.py
@@ -168,6 +168,12 @@
False,
utils.ensure_boolean,
),
+ 'sigv4a_signing_region_set': (
+ 'sigv4a_signing_region_set',
+ 'AWS_SIGV4A_SIGNING_REGION_SET',
+ None,
+ None,
+ ),
}
# A mapping for the s3 specific configuration vars. These are the configuration
# vars that typically go in the s3 section of the config file. This mapping
diff --git a/botocore/exceptions.py b/botocore/exceptions.py
index 1c480abbf8..9fa0dfaa84 100644
--- a/botocore/exceptions.py
+++ b/botocore/exceptions.py
@@ -514,7 +514,7 @@ class UnknownClientMethodError(BotoCoreError):
class UnsupportedSignatureVersionError(BotoCoreError):
"""Error when trying to use an unsupported Signature Version."""
- fmt = 'Signature version is not supported: {signature_version}'
+ fmt = 'Signature version(s) are not supported: {signature_version}'
class ClientError(Exception):
diff --git a/botocore/handlers.py b/botocore/handlers.py
index 211ed0477c..99eed3bfc5 100644
--- a/botocore/handlers.py
+++ b/botocore/handlers.py
@@ -203,6 +203,11 @@ def set_operation_specific_signer(context, signing_name, **kwargs):
if auth_type == 'bearer':
return 'bearer'
+ # If the operation needs an unsigned body, we set additional context
+ # allowing the signer to be aware of this.
+ if context.get('unsigned_payload') or auth_type == 'v4-unsigned-body':
+ context['payload_signing_enabled'] = False
+
if auth_type.startswith('v4'):
if auth_type == 'v4-s3express':
return auth_type
@@ -210,7 +215,8 @@ def set_operation_specific_signer(context, signing_name, **kwargs):
if auth_type == 'v4a':
# If sigv4a is chosen, we must add additional signing config for
# global signature.
- signing = {'region': '*', 'signing_name': signing_name}
+ region = _resolve_sigv4a_region(context)
+ signing = {'region': region, 'signing_name': signing_name}
if 'signing' in context:
context['signing'].update(signing)
else:
@@ -219,11 +225,6 @@ def set_operation_specific_signer(context, signing_name, **kwargs):
else:
signature_version = 'v4'
- # If the operation needs an unsigned body, we set additional context
- # allowing the signer to be aware of this.
- if auth_type == 'v4-unsigned-body':
- context['payload_signing_enabled'] = False
-
# Signing names used by s3 and s3-control use customized signers "s3v4"
# and "s3v4a".
if signing_name in S3_SIGNING_NAMES:
@@ -232,6 +233,15 @@ def set_operation_specific_signer(context, signing_name, **kwargs):
return signature_version
+def _resolve_sigv4a_region(context):
+ region = None
+ if 'client_config' in context:
+ region = context['client_config'].sigv4a_signing_region_set
+ if not region and context.get('signing', {}).get('region'):
+ region = context['signing']['region']
+ return region or '*'
+
+
def decode_console_output(parsed, **kwargs):
if 'Output' in parsed:
try:
diff --git a/botocore/model.py b/botocore/model.py
index df9159e36e..677266c8d2 100644
--- a/botocore/model.py
+++ b/botocore/model.py
@@ -15,6 +15,7 @@
from collections import defaultdict
from typing import NamedTuple, Union
+from botocore.auth import resolve_auth_type
from botocore.compat import OrderedDict
from botocore.exceptions import (
MissingServiceIdError,
@@ -623,10 +624,24 @@ def context_parameters(self):
def request_compression(self):
return self._operation_model.get('requestcompression')
+ @CachedProperty
+ def auth(self):
+ return self._operation_model.get('auth')
+
@CachedProperty
def auth_type(self):
return self._operation_model.get('authtype')
+ @CachedProperty
+ def resolved_auth_type(self):
+ if self.auth:
+ return resolve_auth_type(self.auth)
+ return self.auth_type
+
+ @CachedProperty
+ def unsigned_payload(self):
+ return self._operation_model.get('unsignedPayload')
+
@CachedProperty
def error_shapes(self):
shapes = self._operation_model.get("errors", [])
diff --git a/botocore/regions.py b/botocore/regions.py
index ab20130304..cfa3bde115 100644
--- a/botocore/regions.py
+++ b/botocore/regions.py
@@ -722,7 +722,9 @@ def auth_schemes_to_signing_ctx(self, auth_schemes):
signing_context['region'] = scheme['signingRegion']
elif 'signingRegionSet' in scheme:
if len(scheme['signingRegionSet']) > 0:
- signing_context['region'] = scheme['signingRegionSet'][0]
+ signing_context['region'] = ','.join(
+ scheme['signingRegionSet']
+ )
if 'signingName' in scheme:
signing_context.update(signing_name=scheme['signingName'])
if 'disableDoubleEncoding' in scheme:
| diff --git a/tests/functional/test_auth_config.py b/tests/functional/test_auth_config.py
new file mode 100644
index 0000000000..7fe096d338
--- /dev/null
+++ b/tests/functional/test_auth_config.py
@@ -0,0 +1,77 @@
+# Copyright 2024 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.
+import pytest
+
+from botocore.session import get_session
+
+# In the future, a service may have a list of credentials requirements where one
+# signature may fail and others may succeed. e.g. a service may want to use bearer
+# auth but fall back to sigv4 if a token isn't available. There's currently no way to do
+# this in botocore, so this test ensures we handle this gracefully when the need arises.
+
+
+# The dictionary's value here needs to be hashable to be added to the set below; any
+# new auth types with multiple requirements should be added in a comma-separated list
+AUTH_TYPE_REQUIREMENTS = {
+ 'aws.auth#sigv4': 'credentials',
+ 'aws.auth#sigv4a': 'credentials',
+ 'smithy.api#httpBearerAuth': 'bearer_token',
+ 'smithy.api#noAuth': 'none',
+}
+
+
+def _all_test_cases():
+ session = get_session()
+ loader = session.get_component('data_loader')
+
+ services = loader.list_available_services('service-2')
+ auth_services = []
+ auth_operations = []
+
+ for service in services:
+ service_model = session.get_service_model(service)
+ auth_config = service_model.metadata.get('auth', {})
+ if auth_config:
+ auth_services.append([service, auth_config])
+ for operation in service_model.operation_names:
+ operation_model = service_model.operation_model(operation)
+ if operation_model.auth:
+ auth_operations.append([service, operation_model])
+ return auth_services, auth_operations
+
+
+AUTH_SERVICES, AUTH_OPERATIONS = _all_test_cases()
+
+
+@pytest.mark.validates_models
+@pytest.mark.parametrize("auth_service, auth_config", AUTH_SERVICES)
+def test_all_requirements_match_for_service(auth_service, auth_config):
+ # Validates that all service-level signature types have the same requirements
+ message = f'Found mixed signer requirements for service: {auth_service}'
+ assert_all_requirements_match(auth_config, message)
+
+
+@pytest.mark.validates_models
+@pytest.mark.parametrize("auth_service, operation_model", AUTH_OPERATIONS)
+def test_all_requirements_match_for_operation(auth_service, operation_model):
+ # Validates that all operation-level signature types have the same requirements
+ message = f'Found mixed signer requirements for operation: {auth_service}.{operation_model.name}'
+ auth_config = operation_model.auth
+ assert_all_requirements_match(auth_config, message)
+
+
+def assert_all_requirements_match(auth_config, message):
+ auth_requirements = set(
+ AUTH_TYPE_REQUIREMENTS[auth_type] for auth_type in auth_config
+ )
+ assert len(auth_requirements) == 1
diff --git a/tests/unit/auth/test_auth_trait.py b/tests/unit/auth/test_auth_trait.py
new file mode 100644
index 0000000000..c1209a576c
--- /dev/null
+++ b/tests/unit/auth/test_auth_trait.py
@@ -0,0 +1,42 @@
+# Copyright 2024 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 botocore.auth import BaseSigner, resolve_auth_type
+from botocore.exceptions import (
+ UnknownSignatureVersionError,
+ UnsupportedSignatureVersionError,
+)
+from tests import mock, unittest
+
+
+class TestAuthTraitResolution(unittest.TestCase):
+ def test_auth_resolves_first_available(self):
+ auth = ['aws.auth#foo', 'aws.auth#bar']
+ # Don't declare a signer for "foo"
+ auth_types = {'bar': mock.Mock(spec=BaseSigner)}
+ auth_type_conversions = {'aws.auth#foo': 'foo', 'aws.auth#bar': 'bar'}
+
+ with mock.patch('botocore.auth.AUTH_TYPE_MAPS', auth_types):
+ with mock.patch(
+ 'botocore.auth.AUTH_TYPE_TO_SIGNATURE_VERSION',
+ auth_type_conversions,
+ ):
+ assert resolve_auth_type(auth) == 'bar'
+
+ def test_invalid_auth_type_error(self):
+ with self.assertRaises(UnknownSignatureVersionError):
+ resolve_auth_type(['aws.auth#invalidAuth'])
+
+ def test_no_known_auth_type(self):
+ with self.assertRaises(UnsupportedSignatureVersionError):
+ resolve_auth_type([])
diff --git a/tests/unit/test_handlers.py b/tests/unit/test_handlers.py
index 44ebbecc3f..fef4c43eab 100644
--- a/tests/unit/test_handlers.py
+++ b/tests/unit/test_handlers.py
@@ -1036,13 +1036,11 @@ def test_set_operation_specific_signer_v4a_existing_signing_context(self):
signing_name = 'myservice'
context = {
'auth_type': 'v4a',
- 'signing': {'foo': 'bar', 'region': 'abc'},
+ 'signing': {'foo': 'bar'},
}
handlers.set_operation_specific_signer(
context=context, signing_name=signing_name
)
- # region has been updated
- self.assertEqual(context['signing']['region'], '*')
# signing_name has been added
self.assertEqual(context['signing']['signing_name'], signing_name)
# foo remained untouched
@@ -1073,6 +1071,61 @@ def test_set_operation_specific_signer_s3v4_unsigned_payload(self):
self.assertEqual(response, 's3v4')
self.assertEqual(context.get('payload_signing_enabled'), False)
+ def test_set_operation_specific_signer_defaults_to_asterisk(self):
+ signing_name = 'myservice'
+ context = {
+ 'auth_type': 'v4a',
+ }
+ handlers.set_operation_specific_signer(
+ context=context, signing_name=signing_name
+ )
+ self.assertEqual(context['signing']['region'], '*')
+
+ def test_set_operation_specific_signer_prefers_client_config(self):
+ signing_name = 'myservice'
+ context = {
+ 'auth_type': 'v4a',
+ 'client_config': Config(
+ sigv4a_signing_region_set="region_1,region_2"
+ ),
+ 'signing': {
+ 'region': 'abc',
+ },
+ }
+ handlers.set_operation_specific_signer(
+ context=context, signing_name=signing_name
+ )
+ self.assertEqual(context['signing']['region'], 'region_1,region_2')
+
+ def test_payload_signing_disabled_sets_proper_key(self):
+ signing_name = 'myservice'
+ context = {
+ 'auth_type': 'v4',
+ 'signing': {
+ 'foo': 'bar',
+ 'region': 'abc',
+ },
+ 'unsigned_payload': True,
+ }
+ handlers.set_operation_specific_signer(
+ context=context, signing_name=signing_name
+ )
+ self.assertEqual(context.get('payload_signing_enabled'), False)
+
+ def test_no_payload_signing_disabled_does_not_set_key(self):
+ signing_name = 'myservice'
+ context = {
+ 'auth_type': 'v4',
+ 'signing': {
+ 'foo': 'bar',
+ 'region': 'abc',
+ },
+ }
+ handlers.set_operation_specific_signer(
+ context=context, signing_name=signing_name
+ )
+ self.assertNotIn('payload_signing_enabled', context)
+
@pytest.mark.parametrize(
'auth_type, expected_response', [('v4', 's3v4'), ('v4a', 's3v4a')]
diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py
index 303ed1a31a..da95a18bea 100644
--- a/tests/unit/test_model.py
+++ b/tests/unit/test_model.py
@@ -182,6 +182,7 @@ def setUp(self):
'errors': [{'shape': 'NoSuchResourceException'}],
'documentation': 'Docs for OperationName',
'authtype': 'v4',
+ 'auth': ['aws.auth#sigv4'],
},
'OperationTwo': {
'http': {
@@ -396,6 +397,22 @@ def test_error_shapes(self):
operation.error_shapes[0].name, 'NoSuchResourceException'
)
+ def test_has_auth(self):
+ operation = self.service_model.operation_model('OperationName')
+ self.assertEqual(operation.auth, ["aws.auth#sigv4"])
+
+ def test_auth_not_set(self):
+ operation = self.service_model.operation_model('OperationTwo')
+ self.assertIsNone(operation.auth)
+
+ def test_has_resolved_auth_type(self):
+ operation = self.service_model.operation_model('OperationName')
+ self.assertEqual(operation.resolved_auth_type, 'v4')
+
+ def test_resolved_auth_type_not_set(self):
+ operation = self.service_model.operation_model('OperationTwo')
+ self.assertIsNone(operation.resolved_auth_type)
+
def test_has_auth_type(self):
operation = self.service_model.operation_model('OperationName')
self.assertEqual(operation.auth_type, 'v4')
| diff --git a/.changes/next-release/enhancement-signing-83434.json b/.changes/next-release/enhancement-signing-83434.json
new file mode 100644
index 0000000000..a90654a772
--- /dev/null
+++ b/.changes/next-release/enhancement-signing-83434.json
@@ -0,0 +1,5 @@
+{
+ "type": "feature",
+ "category": "signing",
+ "description": "Adds internal support for the new 'auth' trait to allow a priority list of auth types for a service or operation."
+}
| [
{
"components": [
{
"doc": "",
"lines": [
1140,
1150
],
"name": "resolve_auth_type",
"signature": "def resolve_auth_type(auth_trait):",
"type": "function"
}
],
"file": "botocore/auth.py"
},
{
"components": [
{
... | [
"tests/functional/test_auth_config.py::test_all_requirements_match_for_service[acm-auth_config0]",
"tests/functional/test_auth_config.py::test_all_requirements_match_for_service[acm-pca-auth_config1]",
"tests/functional/test_auth_config.py::test_all_requirements_match_for_service[apigateway-auth_config2]",
"t... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Multi-auth trait support
Adds support for the new 'auth' trait on our models that will allow a priority list of auth types for a service or operation
----------
</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 botocore/auth.py]
(definition of resolve_auth_type:)
def resolve_auth_type(auth_trait):
[end of new definitions in botocore/auth.py]
[start of new definitions in botocore/handlers.py]
(definition of _resolve_sigv4a_region:)
def _resolve_sigv4a_region(context):
[end of new definitions in botocore/handlers.py]
[start of new definitions in botocore/model.py]
(definition of OperationModel.auth:)
def auth(self):
(definition of OperationModel.resolved_auth_type:)
def resolved_auth_type(self):
(definition of OperationModel.unsigned_payload:)
def unsigned_payload(self):
[end of new definitions in botocore/model.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>> | 5e4b564dd0f9aab16a404251ebd3e675c9681492 | |
boto__botocore-3232 | 3,232 | boto/botocore | null | 98899c002f9f5ee9238555a9461e1a252140462a | 2024-08-06T14:31:48Z | diff --git a/.changes/next-release/enhancement-s3-94466.json b/.changes/next-release/enhancement-s3-94466.json
new file mode 100644
index 0000000000..5fc2e636ec
--- /dev/null
+++ b/.changes/next-release/enhancement-s3-94466.json
@@ -0,0 +1,5 @@
+{
+ "type": "enhancement",
+ "category": "``s3``",
+ "description": "Adds logic to gracefully handle invalid timestamps returned in the Expires header."
+}
diff --git a/botocore/data/s3/2006-03-01/service-2.sdk-extras.json b/botocore/data/s3/2006-03-01/service-2.sdk-extras.json
new file mode 100644
index 0000000000..d04e9d0b45
--- /dev/null
+++ b/botocore/data/s3/2006-03-01/service-2.sdk-extras.json
@@ -0,0 +1,8 @@
+{
+ "version": 1.0,
+ "merge": {
+ "shapes": {
+ "Expires":{"type":"timestamp"}
+ }
+ }
+}
diff --git a/botocore/docs/bcdoc/restdoc.py b/botocore/docs/bcdoc/restdoc.py
index d23fcf2825..3868126cc9 100644
--- a/botocore/docs/bcdoc/restdoc.py
+++ b/botocore/docs/bcdoc/restdoc.py
@@ -214,6 +214,9 @@ def get_section(self, name):
"""Retrieve a section"""
return self._structure[name]
+ def has_section(self, name):
+ return name in self._structure
+
def delete_section(self, name):
"""Delete a section"""
del self._structure[name]
diff --git a/botocore/endpoint.py b/botocore/endpoint.py
index 59f3d86c8e..1c2cee068b 100644
--- a/botocore/endpoint.py
+++ b/botocore/endpoint.py
@@ -302,10 +302,18 @@ def _do_get_response(self, request, operation_model, context):
history_recorder.record('HTTP_RESPONSE', http_response_record_dict)
protocol = operation_model.metadata['protocol']
+ customized_response_dict = {}
+ self._event_emitter.emit(
+ f"before-parse.{service_id}.{operation_model.name}",
+ operation_model=operation_model,
+ response_dict=response_dict,
+ customized_response_dict=customized_response_dict,
+ )
parser = self._response_parser_factory.create_parser(protocol)
parsed_response = parser.parse(
response_dict, operation_model.output_shape
)
+ parsed_response.update(customized_response_dict)
# Do a second parsing pass to pick up on any modeled error fields
# NOTE: Ideally, we would push this down into the parser classes but
# they currently have no reference to the operation or service model
diff --git a/botocore/handlers.py b/botocore/handlers.py
index 99eed3bfc5..9cb1d052c0 100644
--- a/botocore/handlers.py
+++ b/botocore/handlers.py
@@ -1176,6 +1176,69 @@ def remove_content_type_header_for_presigning(request, **kwargs):
del request.headers['Content-Type']
+def handle_expires_header(
+ operation_model, response_dict, customized_response_dict, **kwargs
+):
+ if _has_expires_shape(operation_model.output_shape):
+ if expires_value := response_dict.get('headers', {}).get('Expires'):
+ customized_response_dict['ExpiresString'] = expires_value
+ try:
+ utils.parse_timestamp(expires_value)
+ except (ValueError, RuntimeError):
+ logger.warning(
+ f'Failed to parse the "Expires" member as a timestamp: {expires_value}. '
+ f'The unparsed value is available in the response under "ExpiresString".'
+ )
+ del response_dict['headers']['Expires']
+
+
+def _has_expires_shape(shape):
+ if not shape:
+ return False
+ return any(
+ member_shape.name == 'Expires'
+ and member_shape.serialization.get('name') == 'Expires'
+ for member_shape in shape.members.values()
+ )
+
+
+def document_expires_shape(section, event_name, **kwargs):
+ # Updates the documentation for S3 operations that include the 'Expires' member
+ # in their response structure. Documents a synthetic member 'ExpiresString' and
+ # includes a deprecation notice for 'Expires'.
+ if 'response-example' in event_name:
+ if not section.has_section('structure-value'):
+ return
+ parent = section.get_section('structure-value')
+ if not parent.has_section('Expires'):
+ return
+ param_line = parent.get_section('Expires')
+ param_line.add_new_section('ExpiresString')
+ new_param_line = param_line.get_section('ExpiresString')
+ new_param_line.write("'ExpiresString': 'string',")
+ new_param_line.style.new_line()
+ elif 'response-params' in event_name:
+ if not section.has_section('Expires'):
+ return
+ param_section = section.get_section('Expires')
+ # Add a deprecation notice for the "Expires" param
+ doc_section = param_section.get_section('param-documentation')
+ doc_section.style.start_note()
+ doc_section.write(
+ 'This member has been deprecated. Please use ``ExpiresString`` instead.'
+ )
+ doc_section.style.end_note()
+ # Document the "ExpiresString" param
+ new_param_section = param_section.add_new_section('ExpiresString')
+ new_param_section.style.new_paragraph()
+ new_param_section.write('- **ExpiresString** *(string) --*')
+ new_param_section.style.indent()
+ new_param_section.style.new_paragraph()
+ new_param_section.write(
+ 'The raw, unparsed value of the ``Expires`` field.'
+ )
+
+
# This is a list of (event_name, handler).
# When a Session is created, everything in this list will be
# automatically registered with that Session.
@@ -1205,6 +1268,7 @@ def remove_content_type_header_for_presigning(request, **kwargs):
('after-call.ec2.GetConsoleOutput', decode_console_output),
('after-call.cloudformation.GetTemplate', json_decode_template_body),
('after-call.s3.GetBucketLocation', parse_get_bucket_location),
+ ('before-parse.s3.*', handle_expires_header),
('before-parameter-build', generate_idempotent_uuid),
('before-parameter-build.s3', validate_bucket_name),
('before-parameter-build.s3', remove_bucket_from_url_paths_from_model),
@@ -1231,6 +1295,8 @@ def remove_content_type_header_for_presigning(request, **kwargs):
('before-parameter-build.s3-control', remove_accid_host_prefix_from_model),
('docs.*.s3.CopyObject.complete-section', document_copy_source_form),
('docs.*.s3.UploadPartCopy.complete-section', document_copy_source_form),
+ ('docs.response-example.s3.*.complete-section', document_expires_shape),
+ ('docs.response-params.s3.*.complete-section', document_expires_shape),
('before-endpoint-resolution.s3', customize_endpoint_resolver_builtins),
('before-call', add_recursion_detection_header),
('before-call.s3', add_expect_header),
| diff --git a/tests/functional/test_s3.py b/tests/functional/test_s3.py
index 0c04f858e0..f58488fc6e 100644
--- a/tests/functional/test_s3.py
+++ b/tests/functional/test_s3.py
@@ -15,6 +15,7 @@
import re
import pytest
+from dateutil.tz import tzutc
import botocore.session
from botocore import UNSIGNED
@@ -1340,6 +1341,41 @@ def test_500_error_with_non_xml_body(self):
self.assertEqual(len(http_stubber.requests), 2)
+class TestS3ExpiresHeaderResponse(BaseS3OperationTest):
+ def test_valid_expires_value_in_response(self):
+ expires_value = "Thu, 01 Jan 1970 00:00:00 GMT"
+ mock_headers = {'expires': expires_value}
+ s3 = self.session.create_client("s3")
+ with ClientHTTPStubber(s3) as http_stubber:
+ http_stubber.add_response(headers=mock_headers)
+ response = s3.get_object(Bucket='mybucket', Key='mykey')
+ self.assertEqual(
+ response.get('Expires'),
+ datetime.datetime(1970, 1, 1, tzinfo=tzutc()),
+ )
+ self.assertEqual(response.get('ExpiresString'), expires_value)
+
+ def test_invalid_expires_value_in_response(self):
+ expires_value = "Invalid Date"
+ mock_headers = {'expires': expires_value}
+ warning_msg = 'Failed to parse the "Expires" member as a timestamp'
+ s3 = self.session.create_client("s3")
+ with self.assertLogs('botocore.handlers', level='WARNING') as log:
+ with ClientHTTPStubber(s3) as http_stubber:
+ http_stubber.add_response(headers=mock_headers)
+ response = s3.get_object(Bucket='mybucket', Key='mykey')
+ self.assertNotIn(
+ 'expires',
+ response.get('ResponseMetadata').get('HTTPHeaders'),
+ )
+ self.assertNotIn('Expires', response)
+ self.assertEqual(response.get('ExpiresString'), expires_value)
+ self.assertTrue(
+ any(warning_msg in entry for entry in log.output),
+ f'Expected warning message not found in logs. Logs: {log.output}',
+ )
+
+
class TestWriteGetObjectResponse(BaseS3ClientConfigurationTest):
def create_stubbed_s3_client(self, **kwargs):
client = self.create_s3_client(**kwargs)
diff --git a/tests/unit/test_endpoint.py b/tests/unit/test_endpoint.py
index a2dc45755a..00790e4ecb 100644
--- a/tests/unit/test_endpoint.py
+++ b/tests/unit/test_endpoint.py
@@ -82,13 +82,16 @@ def setUp(self):
def tearDown(self):
self.factory_patch.stop()
- def get_emitter_responses(self, num_retries=0, sleep_time=0):
+ def get_emitter_responses(self, num_retries=0, sleep_time=0, num_events=4):
emitter_responses = []
+ # We emit the following events:
+ # 1. request-created
+ # 2. before-send
+ # 3. before-parse (may not be emitted if certain errors are thrown)
+ # 4. response-received
response_request_emitter_responses = [
- [(None, None)], # emit() response for request-created
- [(None, None)], # emit() response for before-send
- [(None, None)], # emit() response for response-received
- ]
+ [(None, None)] # emit() response for each emitted event
+ ] * num_events
for _ in range(num_retries):
emitter_responses.extend(response_request_emitter_responses)
# emit() response for retry for sleep time
@@ -239,6 +242,7 @@ def test_retry_events_can_alter_behavior(self):
expected_events=[
'request-created.ec2.DescribeInstances',
'before-send.ec2.DescribeInstances',
+ 'before-parse.ec2.DescribeInstances',
'response-received.ec2.DescribeInstances',
'needs-retry.ec2.DescribeInstances',
]
@@ -247,7 +251,7 @@ def test_retry_events_can_alter_behavior(self):
def test_retry_on_socket_errors(self):
self.event_emitter.emit.side_effect = self.get_emitter_responses(
- num_retries=1
+ num_retries=1, num_events=3
)
self.http_session.send.side_effect = HTTPClientError(error='wrapped')
with self.assertRaises(HTTPClientError):
diff --git a/tests/unit/test_handlers.py b/tests/unit/test_handlers.py
index fef4c43eab..7e28356442 100644
--- a/tests/unit/test_handlers.py
+++ b/tests/unit/test_handlers.py
@@ -15,6 +15,7 @@
import copy
import io
import json
+import logging
import os
import pytest
@@ -1780,3 +1781,166 @@ def test_remove_bucket_from_url_paths_from_model(
)
assert model.http['requestUri'] == request_uri_after
assert model.http['authPath'] == auth_path
+
+
+@pytest.fixture()
+def operation_model_mock():
+ operation_model = mock.Mock()
+ operation_model.output_shape = mock.Mock()
+ operation_model.output_shape.members = {'Expires': mock.Mock()}
+ operation_model.output_shape.members['Expires'].name = 'Expires'
+ operation_model.output_shape.members['Expires'].serialization = {
+ 'name': 'Expires'
+ }
+ return operation_model
+
+
+@pytest.mark.parametrize(
+ "expires, expect_expires_header",
+ [
+ # Valid expires values
+ ("Thu, 01 Jan 2015 00:00:00 GMT", True),
+ ("10/21/2018", True),
+ ("01 dec 2100", True),
+ ("2023-11-02 08:43:04 -0400", True),
+ ("Sun, 22 Oct 23 00:45:02 UTC", True),
+ # Invalid expires values
+ ("Invalid Date", False),
+ ("access plus 1 month", False),
+ ("Expires: Thu, 9 Sep 2013 14:19:41 GMT", False),
+ ("{ts '2023-10-10 09:27:14'}", False),
+ (-33702800404003370280040400, False),
+ ],
+)
+def test_handle_expires_header(
+ expires, expect_expires_header, operation_model_mock
+):
+ response_dict = {
+ 'headers': {
+ 'Expires': expires,
+ }
+ }
+ customized_response_dict = {}
+ handlers.handle_expires_header(
+ operation_model_mock, response_dict, customized_response_dict
+ )
+ assert customized_response_dict.get('ExpiresString') == expires
+ assert ('Expires' in response_dict['headers']) == expect_expires_header
+
+
+def test_handle_expires_header_logs_warning(operation_model_mock, caplog):
+ response_dict = {
+ 'headers': {
+ 'Expires': 'Invalid Date',
+ }
+ }
+ with caplog.at_level(logging.WARNING):
+ handlers.handle_expires_header(operation_model_mock, response_dict, {})
+ assert len(caplog.records) == 1
+ assert 'Failed to parse the "Expires" member as a timestamp' in caplog.text
+
+
+def test_handle_expires_header_does_not_log_warning(
+ operation_model_mock, caplog
+):
+ response_dict = {
+ 'headers': {
+ 'Expires': 'Thu, 01 Jan 2015 00:00:00 GMT',
+ }
+ }
+ with caplog.at_level(logging.WARNING):
+ handlers.handle_expires_header(operation_model_mock, response_dict, {})
+ assert len(caplog.records) == 0
+
+
+@pytest.fixture()
+def document_expires_mocks():
+ return {
+ 'section': mock.Mock(),
+ 'parent': mock.Mock(),
+ 'param_line': mock.Mock(),
+ 'param_section': mock.Mock(),
+ 'doc_section': mock.Mock(),
+ 'new_param_line': mock.Mock(),
+ 'new_param_section': mock.Mock(),
+ 'response_example_event': 'docs.response-example.s3.TestOperation.complete-section',
+ 'response_params_event': 'docs.response-params.s3.TestOperation.complete-section',
+ }
+
+
+def test_document_response_example_with_expires(document_expires_mocks):
+ mocks = document_expires_mocks
+ mocks['section'].has_section.return_value = True
+ mocks['section'].get_section.return_value = mocks['parent']
+ mocks['parent'].has_section.return_value = True
+ mocks['parent'].get_section.return_value = mocks['param_line']
+ mocks['param_line'].has_section.return_value = True
+ mocks['param_line'].get_section.return_value = mocks['new_param_line']
+ handlers.document_expires_shape(
+ mocks['section'], mocks['response_example_event']
+ )
+ mocks['param_line'].add_new_section.assert_called_once_with(
+ 'ExpiresString'
+ )
+ mocks['new_param_line'].write.assert_called_once_with(
+ "'ExpiresString': 'string',"
+ )
+ mocks['new_param_line'].style.new_line.assert_called_once()
+
+
+def test_document_response_example_without_expires(document_expires_mocks):
+ mocks = document_expires_mocks
+ mocks['section'].has_section.return_value = True
+ mocks['section'].get_section.return_value = mocks['parent']
+ mocks['parent'].has_section.return_value = False
+ handlers.document_expires_shape(
+ mocks['section'], mocks['response_example_event']
+ )
+ mocks['parent'].add_new_section.assert_not_called()
+ mocks['parent'].get_section.assert_not_called()
+ mocks['new_param_line'].write.assert_not_called()
+
+
+def test_document_response_params_with_expires(document_expires_mocks):
+ mocks = document_expires_mocks
+ mocks['section'].has_section.return_value = True
+ mocks['section'].get_section.return_value = mocks['param_section']
+ mocks['param_section'].get_section.side_effect = [
+ mocks['doc_section'],
+ ]
+ mocks['param_section'].add_new_section.side_effect = [
+ mocks['new_param_section'],
+ ]
+ mocks['doc_section'].style = mock.Mock()
+ mocks['new_param_section'].style = mock.Mock()
+ handlers.document_expires_shape(
+ mocks['section'], mocks['response_params_event']
+ )
+ mocks['param_section'].get_section.assert_any_call('param-documentation')
+ mocks['doc_section'].style.start_note.assert_called_once()
+ mocks['doc_section'].write.assert_called_once_with(
+ 'This member has been deprecated. Please use ``ExpiresString`` instead.'
+ )
+ mocks['doc_section'].style.end_note.assert_called_once()
+ mocks['param_section'].add_new_section.assert_called_once_with(
+ 'ExpiresString'
+ )
+ mocks['new_param_section'].style.new_paragraph.assert_any_call()
+ mocks['new_param_section'].write.assert_any_call(
+ '- **ExpiresString** *(string) --*'
+ )
+ mocks['new_param_section'].style.indent.assert_called_once()
+ mocks['new_param_section'].write.assert_any_call(
+ 'The raw, unparsed value of the ``Expires`` field.'
+ )
+
+
+def test_document_response_params_without_expires(document_expires_mocks):
+ mocks = document_expires_mocks
+ mocks['section'].has_section.return_value = False
+ handlers.document_expires_shape(
+ mocks['section'], mocks['response_params_event']
+ )
+ mocks['section'].get_section.assert_not_called()
+ mocks['param_section'].add_new_section.assert_not_called()
+ mocks['doc_section'].write.assert_not_called()
| diff --git a/.changes/next-release/enhancement-s3-94466.json b/.changes/next-release/enhancement-s3-94466.json
new file mode 100644
index 0000000000..5fc2e636ec
--- /dev/null
+++ b/.changes/next-release/enhancement-s3-94466.json
@@ -0,0 +1,5 @@
+{
+ "type": "enhancement",
+ "category": "``s3``",
+ "description": "Adds logic to gracefully handle invalid timestamps returned in the Expires header."
+}
diff --git a/botocore/data/s3/2006-03-01/service-2.sdk-extras.json b/botocore/data/s3/2006-03-01/service-2.sdk-extras.json
new file mode 100644
index 0000000000..d04e9d0b45
--- /dev/null
+++ b/botocore/data/s3/2006-03-01/service-2.sdk-extras.json
@@ -0,0 +1,8 @@
+{
+ "version": 1.0,
+ "merge": {
+ "shapes": {
+ "Expires":{"type":"timestamp"}
+ }
+ }
+}
| [
{
"components": [
{
"doc": "",
"lines": [
217,
218
],
"name": "DocumentStructure.has_section",
"signature": "def has_section(self, name):",
"type": "function"
}
],
"file": "botocore/docs/bcdoc/restdoc.py"
},
{
"compo... | [
"tests/functional/test_s3.py::TestS3ExpiresHeaderResponse::test_invalid_expires_value_in_response",
"tests/functional/test_s3.py::TestS3ExpiresHeaderResponse::test_valid_expires_value_in_response",
"tests/unit/test_endpoint.py::TestRetryInterface::test_retry_attempts_added_to_response_metadata",
"tests/unit/t... | [
"tests/functional/test_s3.py::TestS3BucketValidation::test_invalid_bucket_name_raises_error",
"tests/functional/test_s3.py::TestS3ClientConfigResolution::test_client_config_us_east_1_regional_overrides_config_var",
"tests/functional/test_s3.py::TestS3ClientConfigResolution::test_client_config_us_east_1_regional... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
s3 expires implementation
This PR customizes the S3 `Expires` shape in preparation for model changes. Instead of throwing an error, operations will now complete with fallback behavior and a warning.
* Ensures the `Expires` header remains a timestamp for backwards compatibility.
* Omits the `Expires` key in the response if parsing fails and logs a warning.
Operations with `Expires` in their output shapes will:
* Add a synthetic member called `ExpiresString` to retain the raw value of `Expires`.
* Deprecate `Expires` and encourage users to use the new field `ExpiresString` through documentation.
----------
</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 botocore/docs/bcdoc/restdoc.py]
(definition of DocumentStructure.has_section:)
def has_section(self, name):
[end of new definitions in botocore/docs/bcdoc/restdoc.py]
[start of new definitions in botocore/handlers.py]
(definition of handle_expires_header:)
def handle_expires_header( operation_model, response_dict, customized_response_dict, **kwargs ):
(definition of _has_expires_shape:)
def _has_expires_shape(shape):
(definition of document_expires_shape:)
def document_expires_shape(section, event_name, **kwargs):
[end of new definitions in botocore/handlers.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>> | 5e4b564dd0f9aab16a404251ebd3e675c9681492 | |
RDFLib__rdflib-2877 | 2,877 | RDFLib/rdflib | null | 0c11debb5178157baeac27b735e49a757916d2a6 | 2024-08-06T04:52:24Z | diff --git a/docs/plugin_serializers.rst b/docs/plugin_serializers.rst
index 39d00df7f..3721bb9f8 100644
--- a/docs/plugin_serializers.rst
+++ b/docs/plugin_serializers.rst
@@ -21,6 +21,7 @@ n3 :class:`~rdflib.plugins.serializers.n3.N3Serializer`
nquads :class:`~rdflib.plugins.serializers.nquads.NQuadsSerializer`
nt :class:`~rdflib.plugins.serializers.nt.NTSerializer`
hext :class:`~rdflib.plugins.serializers.hext.HextuplesSerializer`
+patch :class:`~rdflib.plugins.serializers.patch.PatchSerializer`
pretty-xml :class:`~rdflib.plugins.serializers.rdfxml.PrettyXMLSerializer`
trig :class:`~rdflib.plugins.serializers.trig.TrigSerializer`
trix :class:`~rdflib.plugins.serializers.trix.TriXSerializer`
@@ -34,6 +35,11 @@ JSON-LD
-------
JSON-LD - 'json-ld' - has been incorporated into RDFLib since v6.0.0.
+RDF Patch
+---------
+
+The RDF Patch Serializer - 'patch' - uses the RDF Patch format defined at https://afs.github.io/rdf-patch/. It supports serializing context aware stores as either addition or deletion patches; and also supports serializing the difference between two context aware stores as a Patch of additions and deletions.
+
HexTuples
---------
The HexTuples Serializer - 'hext' - uses the HexTuples format defined at https://github.com/ontola/hextuples.
diff --git a/examples/patch_serializer_example.py b/examples/patch_serializer_example.py
new file mode 100644
index 000000000..748124bc5
--- /dev/null
+++ b/examples/patch_serializer_example.py
@@ -0,0 +1,64 @@
+from rdflib import Dataset, Graph, Literal, URIRef
+
+
+def main():
+ # example for adding a quad
+ ds = Dataset()
+ g = Graph(identifier=URIRef("http://graph-a"))
+ ds.add_graph(g)
+ triple = (URIRef("http://subj-a"), URIRef("http://pred-a"), Literal("obj-a"))
+ ds.get_context(g.identifier).add(triple)
+ result = ds.serialize(format="patch", operation="add")
+ print("Add Quad Patch:")
+ print(result)
+
+ # alternate example for adding a quad
+ ds = Dataset()
+ quad = (
+ URIRef("http://subj-a"),
+ URIRef("http://pred-a"),
+ Literal("obj-a"),
+ Graph(identifier=URIRef("http://graph-a")),
+ )
+ ds.add(quad)
+ result = ds.serialize(format="patch", operation="add")
+ print("Add Quad Patch:")
+ print(result)
+
+ # example for adding a triple
+ ds = Dataset()
+ ds.add(triple)
+ result = ds.serialize(format="patch", operation="add")
+ print("\nAdd Triple Patch:")
+ print(result)
+
+ # Example for diff quads
+ quad_1 = (
+ URIRef("http://subj-a"),
+ URIRef("http://pred-a"),
+ Literal("obj-a"),
+ Graph(identifier=URIRef("http://graph-a")),
+ )
+ quad_2 = (
+ URIRef("http://subj-b"),
+ URIRef("http://pred-b"),
+ Literal("obj-b"),
+ Graph(identifier=URIRef("http://graph-b")),
+ )
+ quad_3 = (
+ URIRef("http://subj-c"),
+ URIRef("http://pred-c"),
+ Literal("obj-c"),
+ Graph(identifier=URIRef("http://graph-c")),
+ )
+ ds1 = Dataset()
+ ds2 = Dataset()
+ ds1.addN([quad_1, quad_2])
+ ds2.addN([quad_2, quad_3])
+ result = ds1.serialize(format="patch", target=ds2)
+ print("Diff Quad Patch:")
+ print(result)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/rdflib/plugin.py b/rdflib/plugin.py
index 921f218a7..7bf685ff2 100644
--- a/rdflib/plugin.py
+++ b/rdflib/plugin.py
@@ -363,6 +363,12 @@ def plugins(
"rdflib.plugins.serializers.hext",
"HextuplesSerializer",
)
+register(
+ "patch",
+ Serializer,
+ "rdflib.plugins.serializers.patch",
+ "PatchSerializer",
+)
# Register Triple Parsers
register(
diff --git a/rdflib/plugins/serializers/patch.py b/rdflib/plugins/serializers/patch.py
new file mode 100644
index 000000000..f548cbe3d
--- /dev/null
+++ b/rdflib/plugins/serializers/patch.py
@@ -0,0 +1,105 @@
+from __future__ import annotations
+
+import warnings
+from typing import IO, Optional
+from uuid import uuid4
+
+from rdflib import Dataset
+from rdflib.plugins.serializers.nquads import _nq_row
+from rdflib.plugins.serializers.nt import _nt_row
+from rdflib.serializer import Serializer
+
+add_remove_methods = {"add": "A", "remove": "D"}
+
+
+class PatchSerializer(Serializer):
+ """
+ Creates an RDF patch file to add and remove triples/quads.
+ Can either:
+ - Create an add or delete patch for a single Dataset.
+ - Create a patch to represent the difference between two Datasets.
+ """
+
+ def __init__(
+ self,
+ store: Dataset,
+ ):
+ self.store: Dataset = store
+ super().__init__(store)
+
+ def serialize(
+ self,
+ stream: IO[bytes],
+ base: Optional[str] = None,
+ encoding: Optional[str] = None,
+ **kwargs,
+ ):
+ """
+ Serialize the store to the given stream.
+ :param stream: The stream to serialize to.
+ :param base: The base URI to use for the serialization.
+ :param encoding: The encoding to use for the serialization.
+ :param kwargs: Additional keyword arguments.
+ Supported keyword arguments:
+ - operation: The operation to perform. Either 'add' or 'remove'.
+ - target: The target Dataset to compare against.
+ NB: Only one of 'operation' or 'target' should be provided.
+ - header_id: The header ID to use.
+ - header_prev: The previous header ID to use.
+ """
+ operation = kwargs.get("operation")
+ target = kwargs.get("target")
+ header_id = kwargs.get("header_id")
+ header_prev = kwargs.get("header_prev")
+ if not header_id:
+ header_id = f"uuid:{uuid4()}"
+ encoding = self.encoding
+ if base is not None:
+ warnings.warn("PatchSerializer does not support base.")
+ if encoding is not None and encoding.lower() != self.encoding.lower():
+ warnings.warn(
+ "PatchSerializer does not use custom encoding. "
+ f"Given encoding was: {encoding}"
+ )
+
+ def write_header():
+ stream.write(f"H id <{header_id}> .\n".encode(encoding, "replace"))
+ if header_prev:
+ stream.write(f"H prev <{header_prev}>\n".encode(encoding, "replace"))
+ stream.write("TX .\n".encode(encoding, "replace"))
+
+ def write_triples(contexts, op_code, use_passed_contexts=False):
+ for context in contexts:
+ if not use_passed_contexts:
+ context = self.store.get_context(context.identifier)
+ for triple in context:
+ stream.write(
+ self._patch_row(triple, context.identifier, op_code).encode(
+ encoding, "replace"
+ )
+ )
+
+ if operation:
+ assert operation in add_remove_methods, f"Invalid operation: {operation}"
+
+ write_header()
+ if operation:
+ operation_code = add_remove_methods.get(operation)
+ write_triples(self.store.contexts(), operation_code)
+ elif target:
+ to_add, to_remove = self._diff(target)
+ write_triples(to_add.contexts(), "A", use_passed_contexts=True)
+ write_triples(to_remove.contexts(), "D", use_passed_contexts=True)
+
+ stream.write("TC .\n".encode(encoding, "replace"))
+
+ def _diff(self, target):
+ rows_to_add = target - self.store
+ rows_to_remove = self.store - target
+ return rows_to_add, rows_to_remove
+
+ def _patch_row(self, triple, context_id, operation):
+ if context_id == self.store.default_context.identifier:
+ return f"{operation} {_nt_row(triple)}"
+ else:
+ return f"{operation} {_nq_row(triple, context_id)}"
| diff --git a/test/test_serializers/test_serializer_patch.py b/test/test_serializers/test_serializer_patch.py
new file mode 100644
index 000000000..6d8a05055
--- /dev/null
+++ b/test/test_serializers/test_serializer_patch.py
@@ -0,0 +1,178 @@
+from rdflib import Dataset, Graph, Literal, URIRef
+
+
+def test_add_quad():
+ ds = Dataset()
+ ds.add(
+ (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ Graph(identifier=URIRef("http://example.org/graph1")),
+ )
+ )
+ result = ds.serialize(format="patch", operation="add")
+ assert (
+ """A <http://example.org/subject1> <http://example.org/predicate2> "object2" <http://example.org/graph1> .
+"""
+ in result
+ )
+
+
+def test_delete_quad():
+ ds = Dataset()
+ ds.add(
+ (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ Graph(identifier=URIRef("http://example.org/graph1")),
+ )
+ )
+ result = ds.serialize(format="patch", operation="remove")
+ assert (
+ """D <http://example.org/subject1> <http://example.org/predicate2> "object2" <http://example.org/graph1> .
+"""
+ in result
+ )
+
+
+def test_diff_quad():
+ quad_1 = (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ Graph(identifier=URIRef("http://example.org/graph1")),
+ )
+ quad_2 = (
+ URIRef("http://example.org/subject2"),
+ URIRef("http://example.org/predicate3"),
+ Literal("object3"),
+ Graph(identifier=URIRef("http://example.org/graph2")),
+ )
+ ds1 = Dataset()
+ ds2 = Dataset()
+ ds1.add(quad_1)
+ ds2.addN([quad_1, quad_2])
+ result = ds1.serialize(format="patch", target=ds2)
+ assert (
+ """A <http://example.org/subject2> <http://example.org/predicate3> "object3" <http://example.org/graph2> ."""
+ in result
+ )
+
+
+def test_add_triple():
+ ds = Dataset()
+ ds.add(
+ (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ )
+ )
+ result = ds.serialize(format="patch", operation="add")
+ assert (
+ """A <http://example.org/subject1> <http://example.org/predicate2> "object2" ."""
+ in result
+ )
+
+
+def test_delete_triple():
+ ds = Dataset()
+ ds.add(
+ (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ )
+ )
+ result = ds.serialize(format="patch", operation="remove")
+ assert (
+ """D <http://example.org/subject1> <http://example.org/predicate2> "object2" ."""
+ in result
+ )
+
+
+def test_diff_triple():
+ triple_1 = (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ )
+ triple_2 = (
+ URIRef("http://example.org/subject2"),
+ URIRef("http://example.org/predicate3"),
+ Literal("object3"),
+ )
+ ds1 = Dataset()
+ ds2 = Dataset()
+ ds1.add(triple_1)
+ ds2.add(triple_1)
+ ds2.add(triple_2)
+ result = ds1.serialize(format="patch", target=ds2)
+ assert (
+ """A <http://example.org/subject2> <http://example.org/predicate3> "object3" ."""
+ in result
+ )
+
+
+def test_diff_quad_overlap():
+ quad_1 = (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate1"),
+ Literal("object1"),
+ Graph(identifier=URIRef("http://example.org/graph1")),
+ )
+ quad_2 = (
+ URIRef("http://example.org/subject2"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ Graph(identifier=URIRef("http://example.org/graph2")),
+ )
+ quad_3 = (
+ URIRef("http://example.org/subject3"),
+ URIRef("http://example.org/predicate3"),
+ Literal("object3"),
+ Graph(identifier=URIRef("http://example.org/graph3")),
+ )
+ ds1 = Dataset()
+ ds2 = Dataset()
+ ds1.addN([quad_1, quad_2])
+ ds2.addN([quad_2, quad_3])
+ result = ds1.serialize(format="patch", target=ds2)
+ # first quad needs to be removed
+ assert (
+ """D <http://example.org/subject1> <http://example.org/predicate1> "object1" <http://example.org/graph1> ."""
+ in result
+ )
+ # third quad needs to be added
+ assert (
+ """A <http://example.org/subject3> <http://example.org/predicate3> "object3" <http://example.org/graph3> ."""
+ in result
+ )
+
+
+def test_header_id():
+ ds = Dataset()
+ ds.add(
+ (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ )
+ )
+ result = ds.serialize(format="patch", operation="add", header_id="uuid:123")
+ assert """H id <uuid:123>""" in result
+
+
+def test_prev_header():
+ ds = Dataset()
+ ds.add(
+ (
+ URIRef("http://example.org/subject1"),
+ URIRef("http://example.org/predicate2"),
+ Literal("object2"),
+ )
+ )
+ result = ds.serialize(format="patch", operation="add", header_prev="uuid:123")
+ assert """H prev <uuid:123>""" in result
| diff --git a/docs/plugin_serializers.rst b/docs/plugin_serializers.rst
index 39d00df7f..3721bb9f8 100644
--- a/docs/plugin_serializers.rst
+++ b/docs/plugin_serializers.rst
@@ -21,6 +21,7 @@ n3 :class:`~rdflib.plugins.serializers.n3.N3Serializer`
nquads :class:`~rdflib.plugins.serializers.nquads.NQuadsSerializer`
nt :class:`~rdflib.plugins.serializers.nt.NTSerializer`
hext :class:`~rdflib.plugins.serializers.hext.HextuplesSerializer`
+patch :class:`~rdflib.plugins.serializers.patch.PatchSerializer`
pretty-xml :class:`~rdflib.plugins.serializers.rdfxml.PrettyXMLSerializer`
trig :class:`~rdflib.plugins.serializers.trig.TrigSerializer`
trix :class:`~rdflib.plugins.serializers.trix.TriXSerializer`
@@ -34,6 +35,11 @@ JSON-LD
-------
JSON-LD - 'json-ld' - has been incorporated into RDFLib since v6.0.0.
+RDF Patch
+---------
+
+The RDF Patch Serializer - 'patch' - uses the RDF Patch format defined at https://afs.github.io/rdf-patch/. It supports serializing context aware stores as either addition or deletion patches; and also supports serializing the difference between two context aware stores as a Patch of additions and deletions.
+
HexTuples
---------
The HexTuples Serializer - 'hext' - uses the HexTuples format defined at https://github.com/ontola/hextuples.
| [
{
"components": [
{
"doc": "",
"lines": [
4,
60
],
"name": "main",
"signature": "def main():",
"type": "function"
}
],
"file": "examples/patch_serializer_example.py"
},
{
"components": [
{
"doc": "Creat... | [
"test/test_serializers/test_serializer_patch.py::test_add_quad",
"test/test_serializers/test_serializer_patch.py::test_delete_quad",
"test/test_serializers/test_serializer_patch.py::test_diff_quad",
"test/test_serializers/test_serializer_patch.py::test_add_triple",
"test/test_serializers/test_serializer_pat... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Implement RDF Patch serializer
Supports serialization from Dataset instances only; triples and quads within a Dataset are supported.
# Summary of changes
Three methods to create RDF Patches from RDFLib Datasets:
1. Serialize a Dataset as an addition patch
2. Serialize a Dataset as a delete patch
3. Create a patch representing the difference between a Dataset instance and a target Dataset instance
Basic usage:
1. `ds.serialize(format="patch", operation="add")`
2. `ds.serialize(format="patch", operation="remove")`
3. `ds1.serialize(format="patch", target=ds2)`
Complete examples are provided in an example script.
# Checklist
- [x] Checked that there aren't other open pull requests for
the same change.
- [x] Checked that all tests and type checking passes.
- If the change adds new features or changes the RDFLib public API:
- [x] ~Created an issue to discuss the change and get in-principle agreement.~ Discussed w/ maintainers
- [x] Considered adding an example in `./examples`.
- If the change has a potential impact on users of this project:
- [x] Updated relevant documentation to avoid inaccuracies.
- [x] Considered adding additional documentation.
- [x] Considered granting [push permissions to the PR branch](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork),
so maintainers can fix minor issues and keep your PR up to date.
----------
</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 examples/patch_serializer_example.py]
(definition of main:)
def main():
[end of new definitions in examples/patch_serializer_example.py]
[start of new definitions in rdflib/plugins/serializers/patch.py]
(definition of PatchSerializer:)
class PatchSerializer(Serializer):
"""Creates an RDF patch file to add and remove triples/quads.
Can either:
- Create an add or delete patch for a single Dataset.
- Create a patch to represent the difference between two Datasets."""
(definition of PatchSerializer.__init__:)
def __init__( self, store: Dataset, ):
(definition of PatchSerializer.serialize:)
def serialize( self, stream: IO[bytes], base: Optional[str] = None, encoding: Optional[str] = None, **kwargs, ):
"""Serialize the store to the given stream.
:param stream: The stream to serialize to.
:param base: The base URI to use for the serialization.
:param encoding: The encoding to use for the serialization.
:param kwargs: Additional keyword arguments.
Supported keyword arguments:
- operation: The operation to perform. Either 'add' or 'remove'.
- target: The target Dataset to compare against.
NB: Only one of 'operation' or 'target' should be provided.
- header_id: The header ID to use.
- header_prev: The previous header ID to use."""
(definition of PatchSerializer.serialize.write_header:)
def write_header():
(definition of PatchSerializer.serialize.write_triples:)
def write_triples(contexts, op_code, use_passed_contexts=False):
(definition of PatchSerializer._diff:)
def _diff(self, target):
(definition of PatchSerializer._patch_row:)
def _patch_row(self, triple, context_id, operation):
[end of new definitions in rdflib/plugins/serializers/patch.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>> | 0c11debb5178157baeac27b735e49a757916d2a6 | |
conan-io__conan-16789 | 16,789 | conan-io/conan | null | 369a3d0751b20cdb19abf7547b8b98e8cbd6dec9 | 2024-08-05T11:17:38Z | diff --git a/conan/tools/gnu/pkgconfigdeps.py b/conan/tools/gnu/pkgconfigdeps.py
index 4e2160989cc..3e743678788 100644
--- a/conan/tools/gnu/pkgconfigdeps.py
+++ b/conan/tools/gnu/pkgconfigdeps.py
@@ -350,6 +350,7 @@ def __init__(self, conanfile):
# Issue: https://github.com/conan-io/conan/issues/14935
# FIXME: Conan 3.x: build_context_folder should be "build" by default
self.build_context_folder = None # Keeping backward-compatibility
+ self._properties = {}
def _validate_build_requires(self, host_req, build_req):
"""
@@ -397,6 +398,9 @@ def content(self):
# Filter the build_requires not activated with PkgConfigDeps.build_context_activated
if require.build and dep.ref.name not in self.build_context_activated:
continue
+ for prop, value in self._properties.get(dep.ref.name, {}).items():
+ dep.cpp_info.set_property(prop, value)
+
# Save all the *.pc files and their contents
pc_files.update(_PCGenerator(self, require, dep).pc_files)
return pc_files
@@ -410,3 +414,17 @@ def generate(self):
generator_files = self.content
for generator_file, content in generator_files.items():
save(generator_file, content)
+
+ def set_property(self, dep, prop, value):
+ """
+ Using this method you can overwrite the :ref:`property<PkgConfigDeps Properties>` values set by
+ the Conan recipes from the consumer. This can be done for `pkg_config_name`,
+ `pkg_config_aliases` and `pkg_config_custom_content` properties.
+
+ :param dep: Name of the dependency to set the :ref:`property<PkgConfigDeps Properties>`. For
+ components use the syntax: ``dep_name::component_name``.
+ :param prop: Name of the :ref:`property<PkgConfigDeps Properties>`.
+ :param value: Value of the property. Use ``None`` to invalidate any value set by the
+ upstream recipe.
+ """
+ self._properties.setdefault(dep, {}).update({prop: value})
| diff --git a/test/integration/toolchains/gnu/test_pkgconfigdeps.py b/test/integration/toolchains/gnu/test_pkgconfigdeps.py
index 467d4f1f48c..1ccc91d90f2 100644
--- a/test/integration/toolchains/gnu/test_pkgconfigdeps.py
+++ b/test/integration/toolchains/gnu/test_pkgconfigdeps.py
@@ -1023,6 +1023,59 @@ def package_info(self):
c.run("install app -s:h build_type=Debug --build=missing")
assert "Install finished successfully" in c.out # the asserts in build() didn't fail
+ @pytest.mark.parametrize("build_folder_name", ["build", ""])
+ def test_pkg_config_deps_set_in_build_context_folder(self, build_folder_name):
+ c = TestClient()
+ tool = textwrap.dedent("""
+ import os
+ from conan import ConanFile
+ from conan.tools.gnu import PkgConfigDeps
+
+ class Example(ConanFile):
+ name = "tool"
+ version = "1.0"
+ requires = "wayland/1.0"
+ tool_requires = "wayland/1.0"
+
+ def generate(self):
+ deps = PkgConfigDeps(self)
+ deps.set_property("wayland", "pkg_config_name", "waylandx264")
+ deps.build_context_activated = ["wayland", "dep"]
+ deps.build_context_folder = "{build_folder_name}"
+ deps.generate()
+
+ def build(self):
+ assert os.path.exists("waylandx264.pc")
+ assert not os.path.exists("wayland.pc")
+ if "{build_folder_name}":
+ assert os.path.exists("{build_folder_name}/waylandx264.pc")
+ assert not os.path.exists("{build_folder_name}/wayland.pc")
+ """.format(build_folder_name=build_folder_name))
+ wayland = textwrap.dedent("""
+ from conan import ConanFile
+
+ class Pkg(ConanFile):
+ name = "wayland"
+ version = "1.0"
+ requires = "dep/1.0"
+
+ def package_info(self):
+ self.cpp_info.components["client"].libs = []
+ self.cpp_info.components["server"].libs = []
+ """)
+ c.save({"dep/conanfile.py": GenConanfile("dep", "1.0").with_package_type("shared-library"),
+ "wayland/conanfile.py": wayland,
+ "tool/conanfile.py": tool,
+ "app/conanfile.py": GenConanfile().with_tool_requires("tool/1.0")})
+ c.run("create dep")
+ c.run("create wayland")
+ c.run("create tool")
+ c.run("install app --build=missing")
+ assert "Install finished successfully" in c.out # the asserts in build() didn't fail
+ # Now make sure we can actually build with build!=host context
+ c.run("install app -s:h build_type=Debug --build=missing")
+ assert "Install finished successfully" in c.out # the asserts in build() didn't fail
+
def test_tool_requires_error_if_folder_and_suffix(self):
client = TestClient()
conanfile = textwrap.dedent("""
@@ -1118,3 +1171,39 @@ def test_using_deployer_folder():
assert "libdir=${prefix}/lib" in content
assert "includedir=${prefix}/include" in content
assert "bindir=${prefix}/bin" in content
+
+
+def test_pkg_config_deps_set_property():
+ c = TestClient()
+ app = textwrap.dedent("""\
+ import os
+ from conan import ConanFile
+ from conan.tools.gnu import PkgConfigDeps
+ class Pkg(ConanFile):
+ settings = "build_type"
+ requires = "dep/0.1", "other/0.1"
+ def generate(self):
+ pc = PkgConfigDeps(self)
+ pc.set_property("dep", "pkg_config_name", "depx264")
+ pc.set_property("other::mycomp1", "nosoname", True)
+ pc.generate()
+ """)
+
+ pkg_info = {"components": {"mycomp1": {"libs": ["mylib"]}}}
+ c.save({"dep/conanfile.py": GenConanfile("dep", "0.1").with_package_type("shared-library"),
+ "other/conanfile.py": GenConanfile("other", "0.1").with_package_type("shared-library")
+ .with_package_info(pkg_info, {}),
+ "app/conanfile.py": app})
+ c.run("create dep")
+ c.run("create other")
+ c.run("install app")
+ assert not os.path.exists(os.path.join(c.current_folder, "app", "dep.pc"))
+
+ dep = c.load("app/depx264.pc")
+ assert 'Name: depx264' in dep
+ other = c.load("app/other.pc")
+ assert 'Name: other' in other
+ other_mycomp1 = c.load("app/other-mycomp1.pc")
+ assert 'Name: other-mycomp1' in other_mycomp1
+ assert other.split("\n")[0] == other_mycomp1.split("\n")[0]
+
| [
{
"components": [
{
"doc": "Using this method you can overwrite the :ref:`property<PkgConfigDeps Properties>` values set by\nthe Conan recipes from the consumer. This can be done for `pkg_config_name`,\n`pkg_config_aliases` and `pkg_config_custom_content` properties.\n\n:param dep: Name of the dep... | [
"test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_pkg_config_deps_set_property"
] | [
"test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_pkg_config_dirs",
"test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_empty_dirs",
"test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_system_libs",
"test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_multiple_include",
... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add `set_property` for PkgConfigDeps
Changelog: Feature: Add `set_property` for PkgConfigDeps to set properties for requirements from consumer recipes.
Docs: Omit
close: #13076
----------
</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 PkgConfigDeps.set_property:)
def set_property(self, dep, prop, value):
"""Using this method you can overwrite the :ref:`property<PkgConfigDeps Properties>` values set by
the Conan recipes from the consumer. This can be done for `pkg_config_name`,
`pkg_config_aliases` and `pkg_config_custom_content` properties.
:param dep: Name of the dependency to set the :ref:`property<PkgConfigDeps Properties>`. For
components use the syntax: ``dep_name::component_name``.
:param prop: Name of the :ref:`property<PkgConfigDeps Properties>`.
:param value: Value of the property. Use ``None`` to invalidate any value set by the
upstream recipe."""
[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 | ||
tobymao__sqlglot-3865 | 3,865 | tobymao/sqlglot | null | e53e7cc02a224563d0a61b0a39298d606b9bac80 | 2024-08-02T12:17:24Z | diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index ffc3cecf14..7fdc96c8fe 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -209,10 +209,11 @@ def _arrow_json_extract_sql(self: DuckDB.Generator, expression: JSON_EXTRACT_TYP
return arrow_sql
-def _date_diff_sql(self: DuckDB.Generator, expression: exp.DateDiff) -> str:
- def _implicit_date_cast(arg: exp.Expression):
- return exp.cast(arg, exp.DataType.Type.DATE) if isinstance(arg, exp.Literal) else arg
+def _implicit_date_cast(arg: t.Optional[exp.Expression]) -> t.Optional[exp.Expression]:
+ return exp.cast(arg, exp.DataType.Type.DATE) if isinstance(arg, exp.Literal) else arg
+
+def _date_diff_sql(self: DuckDB.Generator, expression: exp.DateDiff) -> str:
this = _implicit_date_cast(expression.this)
expr = _implicit_date_cast(expression.expression)
@@ -853,3 +854,15 @@ def objectinsert_sql(self, expression: exp.ObjectInsert) -> str:
return self.func("STRUCT_PACK", kv_sql)
return self.func("STRUCT_INSERT", this, kv_sql)
+
+ def generatedatearray_sql(self, expression: exp.GenerateDateArray) -> str:
+ start = _implicit_date_cast(expression.args.get("start"))
+ end = _implicit_date_cast(expression.args.get("end"))
+
+ # BQ's GENERATE_DATE_ARRAY is transformed to DuckDB'S GENERATE_SERIES
+ gen_series = exp.GenerateSeries(
+ start=start, end=end, step=expression.args.get("interval")
+ )
+
+ # The result is TIMESTAMP array, so to match BQ's semantics we must cast it back to DATE array
+ return self.sql(exp.cast(gen_series, exp.DataType.build("ARRAY<DATE>")))
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index d19c774313..7d73c1c3b5 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -170,6 +170,12 @@ class Parser(metaclass=_Parser):
this=seq_get(args, 0),
to=exp.DataType(this=exp.DataType.Type.TEXT),
),
+ "GENERATE_DATE_ARRAY": lambda args: exp.GenerateDateArray(
+ start=seq_get(args, 0),
+ end=seq_get(args, 1),
+ interval=seq_get(args, 2)
+ or exp.Interval(this=exp.Literal.number(1), unit=exp.var("DAY")),
+ ),
"GLOB": lambda args: exp.Glob(this=seq_get(args, 1), expression=seq_get(args, 0)),
"HEX": build_hex,
"JSON_EXTRACT": build_extract_json_with_path(exp.JSONExtract),
| diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py
index 2e0b6a8e09..c3fc9ff873 100644
--- a/tests/dialects/test_bigquery.py
+++ b/tests/dialects/test_bigquery.py
@@ -1431,6 +1431,20 @@ def test_bigquery(self):
"trino": "CONCAT(ARRAY[1, 2], ARRAY[3, 4], ARRAY[5, 6])",
},
)
+ self.validate_all(
+ "SELECT GENERATE_DATE_ARRAY('2016-10-05', '2016-10-08')",
+ write={
+ "duckdb": "SELECT CAST(GENERATE_SERIES(CAST('2016-10-05' AS DATE), CAST('2016-10-08' AS DATE), INTERVAL 1 DAY) AS DATE[])",
+ "bigquery": "SELECT GENERATE_DATE_ARRAY('2016-10-05', '2016-10-08', INTERVAL 1 DAY)",
+ },
+ )
+ self.validate_all(
+ "SELECT GENERATE_DATE_ARRAY('2016-10-05', '2016-10-08', INTERVAL '1' MONTH)",
+ write={
+ "duckdb": "SELECT CAST(GENERATE_SERIES(CAST('2016-10-05' AS DATE), CAST('2016-10-08' AS DATE), INTERVAL '1' MONTH) AS DATE[])",
+ "bigquery": "SELECT GENERATE_DATE_ARRAY('2016-10-05', '2016-10-08', INTERVAL '1' MONTH)",
+ },
+ )
def test_errors(self):
with self.assertRaises(TokenError):
| [] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery"
] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_errors",
"tests/dialects/test_bigquery.py::TestBigQuery::test_gap_fill",
"tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat",
"tests/dialects/test_bigquery.py::TestBigQuery::test_inline_constructor",
"tests/dialects/test_bigquery.py::TestBi... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(duckdb)!: Support for BQ's exp.GenerateDateArray generation
Generate BigQuery's `GENERATE_DATE_ARRAY(start, stop, interval)` to DuckDB's `GENERATE_SERIES(start, stop, interval)`
Docs
--------
[BigQuery GENERATE_DATE_ARRAY](https://cloud.google.com/bigquery/docs/reference/standard-sql/array_functions#generate_date_array) | [DuckDB GENERATE_SERIES](https://duckdb.org/docs/sql/functions/nested.html#generate_series)
----------
</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>
</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 | ||
conan-io__conan-16762 | 16,762 | conan-io/conan | null | e1063a152b8a969383f35c122a8b26eca58a0820 | 2024-08-01T14:08:04Z | diff --git a/conan/tools/cmake/presets.py b/conan/tools/cmake/presets.py
index b7e616150e2..43739a955ca 100644
--- a/conan/tools/cmake/presets.py
+++ b/conan/tools/cmake/presets.py
@@ -5,7 +5,7 @@
from conan.api.output import ConanOutput, Color
from conan.tools.cmake.layout import get_build_folder_custom_vars
-from conan.tools.cmake.toolchain.blocks import GenericSystemBlock
+from conan.tools.cmake.toolchain.blocks import GenericSystemBlock, CompilersBlock
from conan.tools.cmake.utils import is_multi_configuration
from conan.tools.build import build_jobs
from conan.tools.microsoft import is_msvc
@@ -158,6 +158,13 @@ def _configure_preset(conanfile, generator, cache_variables, toolchain_file, mul
"strategy": "external"
}
+ # Set the compiler like in the toolchain. Some IDEs like VS or VSCode require the compiler
+ # being set to cl.exe in order to activate the environment using vcvarsall.bat according to
+ # the toolset and architecture settings.
+ compilers = CompilersBlock.get_compilers(conanfile)
+ for lang, compiler in compilers.items():
+ ret["cacheVariables"][f"CMAKE_{lang}_COMPILER"] = compiler.replace("\\", "/")
+
ret["toolchainFile"] = toolchain_file
if conanfile.build_folder:
# If we are installing a ref: "conan install <ref>", we don't have build_folder, because
diff --git a/conan/tools/cmake/toolchain/blocks.py b/conan/tools/cmake/toolchain/blocks.py
index 425e62b2af3..1343865c906 100644
--- a/conan/tools/cmake/toolchain/blocks.py
+++ b/conan/tools/cmake/toolchain/blocks.py
@@ -852,9 +852,13 @@ class CompilersBlock(Block):
""")
def context(self):
+ return {"compilers": self.get_compilers(self._conanfile)}
+
+ @staticmethod
+ def get_compilers(conanfile):
# Reading configuration from "tools.build:compiler_executables" -> {"C": "/usr/bin/gcc"}
- compilers_by_conf = self._conanfile.conf.get("tools.build:compiler_executables", default={},
- check_type=dict)
+ compilers_by_conf = conanfile.conf.get("tools.build:compiler_executables", default={},
+ check_type=dict)
# Map the possible languages
compilers = {}
# Allowed <LANG> variables (and <LANG>_LAUNCHER)
@@ -865,7 +869,7 @@ def context(self):
# To set CMAKE_<LANG>_COMPILER
if comp in compilers_by_conf:
compilers[lang] = compilers_by_conf[comp]
- return {"compilers": compilers}
+ return compilers
class GenericSystemBlock(Block):
| diff --git a/test/integration/toolchains/cmake/test_cmaketoolchain.py b/test/integration/toolchains/cmake/test_cmaketoolchain.py
index 38ac9049b82..c174193ece6 100644
--- a/test/integration/toolchains/cmake/test_cmaketoolchain.py
+++ b/test/integration/toolchains/cmake/test_cmaketoolchain.py
@@ -1046,6 +1046,30 @@ def test_set_cmake_lang_compilers_and_launchers():
assert 'set(CMAKE_RC_COMPILER "C:/local/rc.exe")' in toolchain
+def test_cmake_presets_compiler():
+ profile = textwrap.dedent(r"""
+ [settings]
+ os=Windows
+ arch=x86_64
+ compiler=msvc
+ compiler.version=193
+ compiler.runtime=dynamic
+ [conf]
+ tools.build:compiler_executables={"c": "cl", "cpp": "cl.exe", "rc": "C:\\local\\rc.exe"}
+ """)
+ client = TestClient()
+ conanfile = GenConanfile().with_settings("os", "arch", "compiler")\
+ .with_generator("CMakeToolchain")
+ client.save({"conanfile.py": conanfile,
+ "profile": profile})
+ client.run("install . -pr:b profile -pr:h profile")
+ presets = json.loads(client.load("CMakePresets.json"))
+ cache_variables = presets["configurePresets"][0]["cacheVariables"]
+ assert cache_variables["CMAKE_C_COMPILER"] == "cl"
+ assert cache_variables["CMAKE_CXX_COMPILER"] == "cl.exe"
+ assert cache_variables["CMAKE_RC_COMPILER"] == "C:/local/rc.exe"
+
+
def test_cmake_layout_toolchain_folder():
""" in single-config generators, the toolchain is a different file per configuration
https://github.com/conan-io/conan/issues/12827
| [
{
"components": [
{
"doc": "",
"lines": [
858,
872
],
"name": "CompilersBlock.get_compilers",
"signature": "def get_compilers(conanfile):",
"type": "function"
}
],
"file": "conan/tools/cmake/toolchain/blocks.py"
}
] | [
"test/integration/toolchains/cmake/test_cmaketoolchain.py::test_cmake_presets_compiler"
] | [
"test/integration/toolchains/cmake/test_cmaketoolchain.py::test_cross_build",
"test/integration/toolchains/cmake/test_cmaketoolchain.py::test_cross_build_linux_to_macos",
"test/integration/toolchains/cmake/test_cmaketoolchain.py::test_cross_build_user_toolchain",
"test/integration/toolchains/cmake/test_cmaket... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Define compiler variables in CMakePresets.json
Changelog: Feature: Define `CMAKE_<LANG>_COMPILER` variables in CMakePresets.json.
Docs: Omit
Fixes #13136
The compiler variables are set to the same values as in the `cmake_toolchain.cmake`, and only when defining `tools.build:compiler_executables`.
I've tested it with both VS an VS Code, which successfully initialize the correct vcvars environment and select the correct compiler as specified by the toolset version, host and target architecture. From a non-IDE perspective, this does influence the CMake configuration in any way, as the compiler variables would be set in the toolchain to the same value anyway.
<details><summary>profile</summary>
```ini
[settings]
os=Windows
arch=x86
compiler=msvc
compiler.version=193
compiler.runtime=dynamic
compiler.runtime_type=Release
compiler.cppstd=17
[conf]
tools.cmake.cmaketoolchain:toolset_arch=x64
tools.build:compiler_executables={"c": "cl.exe", "cpp": "cl.exe"}
```
</details>
<details><summary>conanfile.txt</summary>
```ini
[generators]
CMakeToolchain
[layout]
cmake_layout
```
</details>
<details><summary>CMakePresets.json after <code>conan install -pr profile -s build_type=Debug .</code></summary>
```json
{
"version": 3,
"vendor": {
"conan": {}
},
"cmakeMinimumRequired": {
"major": 3,
"minor": 15,
"patch": 0
},
"configurePresets": [
{
"name": "conan-debug",
"displayName": "'conan-debug' config",
"description": "'conan-debug' configure using 'Ninja' generator",
"generator": "Ninja",
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_C_COMPILER": "cl.exe",
"CMAKE_CXX_COMPILER": "cl.exe"
},
"toolset": {
"value": "v143,host=x64",
"strategy": "external"
},
"architecture": {
"value": "x86",
"strategy": "external"
},
"toolchainFile": "generators\\conan_toolchain.cmake",
"binaryDir": "C:\\TMP\\conan-feat-presets-with-compiler\\build\\Debug"
}
],
"buildPresets": [
{
"name": "conan-debug",
"configurePreset": "conan-debug",
"jobs": 24
}
],
"testPresets": [
{
"name": "conan-debug",
"configurePreset": "conan-debug"
}
]
}
```
</details>
- [x] Refer to the issue that supports this Pull Request.
- [ ] 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.
- [ ] 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/toolchain/blocks.py]
(definition of CompilersBlock.get_compilers:)
def get_compilers(conanfile):
[end of new definitions in conan/tools/cmake/toolchain/blocks.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>
[feature] CMakePresets support for msvc toolset version
### What is your suggestion?
## Suggestion
Would it be possible for the Conan generated CMakePresets.json to include `msvc.toolset` version details (i.e. `v143`, `v142`, etc.) when populating the `toolset.value` field?
This would allow IDEs to know which `vcvarsall.bat` environment to use when building the project.
## Expected Behavior
For example, when cross-compiling with VS2022 x64 to x86, I'd expect to see the conan generated CMakePresets.json look something like:
```diff
"generator": "Ninja",
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
"CMAKE_BUILD_TYPE": "RelWithDebInfo"
},
"architecture": {
"value": "x86",
"strategy": "external"
},
+"toolset": {
+ "value": "v143,host=x64",
+ "strategy": "external"
+},
"toolchainFile": "C:\\projects\\build\\foo\\RelWithDebInfo\\generators\\conan_toolchain.cmake",
"binaryDir": "C:\\projects\\build\\foo\\RelWithDebInfo
```
_I can use `tools.cmake.cmaketoolchain:toolset_arch=x64` to add the "host=x64" portion, but I don't have anyway to get `v143` added._
VSCode recognizes this `toolset` / `architecture` combination and correctly chooses VS2022 and calls `vcvarsall.bat amd64_x86` prior to calling CMake.
## Current Behavior
Conan *doesn't* include `toolset` details in the generated CMakePresets.json file, so in order to get IDEs like VSCode to find the right environment, we need to adjust CMakePresets.json (as described above) or worse adjust the CMakeUserPresets.json file as follows:
```diff
{
"version": 4,
"vendor": {
"conan": {}
},
"include": [
"C:\\path\\to\\conan\\CMakePresets.json"
- ]
+ ],
+ "configurePresets": [
+ {
+ "name": "RelWithDebInfo",
+ "displayName": "RelWithDebInfo",
+ "inherits": "relwithdebinfo",
+ "toolset": {
+ "value": "v143,host=x64",
+ "strategy": "external"
+ }
+ ],
+ "buildPresets": [
+ {
+ "name": "RelWithDebInfo",
+ "displayName": "RelWithDebInfo",
+ "configurePreset": "RelWithDebInfo",
+ "configuration": "RelWithDebInfo"
+ }
+ ]
}
```
Conan already knows *which* vcvarsall to call, and and ensures the correct one gets called in the generated `conanvcvars.bat`.
Conan also appears to know about `msvc.toolset` version information:
https://github.com/conan-io/conan/blob/e33b55a486fd208223524dda49cce02dbe70c214/conans/client/conf/__init__.py#L117
_At least for the legacy toolsets_
And seems to know about the mapping:
https://github.com/conan-io/conan/blob/e0a8ee058bc8dc2d9811b8aeb6999f69aeb78d85/conan/tools/microsoft/visual.py#L53-L60
It seems like Conan could should be able to use the `msvc.toolset` information from the build profile and populate the version field correctly.
## Context
Follow up to https://github.com/conan-io/conan/issues/11623
Some IDEs are capable of targeting multiple toolsets (e.g. VS2015, VS2019, VS2022), and `toolset.value` is the way for the IDE to know which `vcvarsall.bat` to load and use internally while compiling.
> It's the same step that Visual Studio takes for you when the IDE invokes CMake. **Visual Studio parses the active Configure Preset for the host and target architecture specified by toolset and architecture. Visual Studio then sources the specified environment from vcvarsall.bat.** When you build from the Windows command line with Ninja, you'll need to take this step yourself.
_Excerpt from MSDN [Sourcing the environment when building with command-line generators on Windows](https://learn.microsoft.com/en-us/cpp/build/cmake-presets-vs?view=msvc-170#sourcing-the-environment-when-building-with-command-line-generators-on-windows)_
IDE | Support
----|----------
VSCode | [Already Supported](https://github.com/microsoft/vscode-cmake-tools/search?q=varsForVSInstallation) <br> https://github.com/microsoft/vscode-cmake-tools/pull/2524
QtCreator | [In Progress](https://codereview.qt-project.org/c/qt-creator/qt-creator/+/457588/8/src/plugins/cmakeprojectmanager/cmakeprojectimporter.cpp)<br> [QTCREATOR-BUG 28693](https://bugreports.qt.io/browse/QTCREATORBUG-28693)
CLion | [Feature Request](https://youtrack.jetbrains.com/issue/CPP-31353/Support-external-strategy-of-toolset-and-architecture-fields-in-CMakePresets.json-for-MSVC-compilers.)
Thanks for your support!
### Have you read the CONTRIBUTING guide?
- [X] I've read the CONTRIBUTING guide
----------
Hi @thorntonryan
thanks for your detailed report.
Quick question, isn't Conan generating the right toolset inside the ``conan_toolchain.cmake``? Because it is there:
```cmake
{% if generator_platform %}
set(CMAKE_GENERATOR_PLATFORM "{{ generator_platform }}" CACHE STRING "" FORCE)
{% endif %}
{% if toolset %}
set(CMAKE_GENERATOR_TOOLSET "{{ toolset }}" CACHE STRING "" FORCE)
{% endif %}
```
The reason why things are by default if possible in the toolchain file is because conan needs to be compatible down to CMake 3.15, so no presets. The more things we put in the presets, the more complicated is for developers with CMake < 3.20 to issue a command line that will work for them.
Hrmm. Doesn't look like it.
If I run the following:
```sh
$ conan new hello/0.1 --template cmake_lib
```
And then install that project:
```sh
$ conan install conanfile.py -pr:b x86_64-windows-msvc143 -pr:h x86-windows-msvc143
```
<details>
<summary>$ conan profile show x86-windows-msvc143</summary>
```
Configuration for profile x86-windows-msvc143:
[settings]
os=Windows
os_build=Windows
arch_build=x86_64
compiler=Visual Studio
compiler.version=17
build_type=RelWithDebInfo
arch=x86
```
</details>
<details>
<summary>$ conan profile show x86_64-windows-msvc143</summary>
```
Configuration for profile x86_64-windows-msvc143:
[settings]
os=Windows
os_build=Windows
arch_build=x86_64
compiler=Visual Studio
compiler.version=17
build_type=RelWithDebInfo
arch=x86_64
```
</details>
Conan generates the following:
<details>
<summary>CMakePresets.json</summary>
```json
{
"version": 3,
"vendor": {
"conan": {}
},
"cmakeMinimumRequired": {
"major": 3,
"minor": 15,
"patch": 0
},
"configurePresets": [
{
"name": "relwithdebinfo",
"displayName": "'relwithdebinfo' config",
"description": "'relwithdebinfo' configure using 'Ninja' generator",
"generator": "Ninja",
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
"CMAKE_BUILD_TYPE": "RelWithDebInfo"
},
"architecture": {
"value": "x86",
"strategy": "external"
},
"toolchainFile": "C:\\projects\\build\\conan\\build\\RelWithDebInfo\\generators\\conan_toolchain.cmake",
"binaryDir": "C:\\projects\\build\\conan\\build\\RelWithDebInfo"
}
],
"buildPresets": [
{
"name": "relwithdebinfo",
"configurePreset": "relwithdebinfo"
}
],
"testPresets": [
{
"name": "relwithdebinfo",
"configurePreset": "relwithdebinfo"
}
]
}
```
</details>
<details>
<summary>CMakeUserPresets.json</summary>
```json
{
"version": 4,
"vendor": {
"conan": {}
},
"include": [
"C:\\projects\\build\\conan\\build\\RelWithDebInfo\\generators\\CMakePresets.json"
]
}
```
</details>
<details>
<summary>conan_toolchain.cmake</summary>
```cmake
# Conan automatically generated toolchain file
# DO NOT EDIT MANUALLY, it will be overwritten
# Avoid including toolchain file several times (bad if appending to variables like
# CMAKE_CXX_FLAGS. See https://github.com/android/ndk/issues/323
include_guard()
message(STATUS "Using Conan toolchain: ${CMAKE_CURRENT_LIST_FILE}")
if(${CMAKE_VERSION} VERSION_LESS "3.15")
message(FATAL_ERROR "The 'CMakeToolchain' generator only works with CMake >= 3.15")
endif()
# Definition of VS runtime, defined from build_type, compiler.runtime, compiler.runtime_type
cmake_policy(GET CMP0091 POLICY_CMP0091)
if(NOT "${POLICY_CMP0091}" STREQUAL NEW)
message(FATAL_ERROR "The CMake policy CMP0091 must be NEW, but is '${POLICY_CMP0091}'")
endif()
set(CMAKE_MSVC_RUNTIME_LIBRARY "$<$<CONFIG:RelWithDebInfo>:MultiThreadedDLL>")
# Extra c, cxx, linkflags and defines
if(DEFINED CONAN_CXX_FLAGS)
string(APPEND CMAKE_CXX_FLAGS_INIT " ${CONAN_CXX_FLAGS}")
endif()
if(DEFINED CONAN_C_FLAGS)
string(APPEND CMAKE_C_FLAGS_INIT " ${CONAN_C_FLAGS}")
endif()
if(DEFINED CONAN_SHARED_LINKER_FLAGS)
string(APPEND CMAKE_SHARED_LINKER_FLAGS_INIT " ${CONAN_SHARED_LINKER_FLAGS}")
endif()
if(DEFINED CONAN_EXE_LINKER_FLAGS)
string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " ${CONAN_EXE_LINKER_FLAGS}")
endif()
get_property( _CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE )
if(_CMAKE_IN_TRY_COMPILE)
message(STATUS "Running toolchain IN_TRY_COMPILE")
return()
endif()
set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON)
# Definition of CMAKE_MODULE_PATH
# Explicitly defined "buildirs" of "build" context dependencies
# the generators folder (where conan generates files, like this toolchain)
list(PREPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
# Definition of CMAKE_PREFIX_PATH, CMAKE_XXXXX_PATH
# The Conan local "generators" folder, where this toolchain is saved.
list(PREPEND CMAKE_PREFIX_PATH ${CMAKE_CURRENT_LIST_DIR} )
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_PACKAGE OR CMAKE_FIND_ROOT_PATH_MODE_PACKAGE STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE "BOTH")
endif()
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_PROGRAM OR CMAKE_FIND_ROOT_PATH_MODE_PROGRAM STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM "BOTH")
endif()
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_LIBRARY OR CMAKE_FIND_ROOT_PATH_MODE_LIBRARY STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY "BOTH")
endif()
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_INCLUDE OR CMAKE_FIND_ROOT_PATH_MODE_INCLUDE STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE "BOTH")
endif()
if (DEFINED ENV{PKG_CONFIG_PATH})
set(ENV{PKG_CONFIG_PATH} "C:/projects/build/conan/build/RelWithDebInfo/generators;$ENV{PKG_CONFIG_PATH}")
else()
set(ENV{PKG_CONFIG_PATH} "C:/projects/build/conan/build/RelWithDebInfo/generators;")
endif()
message(STATUS "Conan toolchain: Setting BUILD_SHARED_LIBS = OFF")
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared libraries")
# Variables
# Variables per configuration
# Preprocessor definitions
# Preprocessor definitions per configuration
```
</details>
Unfortunately, I'm not seeing `CMAKE_GENERATOR_PLATFORM` or `CMAKE_GENERATOR_TOOLSET` there.
If I try the same thing with the `msvc` compiler:
```sh
$ conan install conanfile.py -pr:b x86_64-windows-msvc-143 -pr:h x86-windows-msvc-143
```
<details>
<summary>$ conan profile show x86-windows-msvc-143</summary>
```
Configuration for profile x86-windows-msvc-143:
[settings]
os=Windows
os_build=Windows
arch_build=x86_64
compiler=msvc
compiler.version=193
build_type=RelWithDebInfo
arch=x86
compiler.cppstd=20
compiler.runtime=dynamic
```
</details>
<details>
<summary>$ conan profile show x86_64-windows-msvc-143</summary>
```
Configuration for profile x86_64-windows-msvc-143:
[settings]
os=Windows
os_build=Windows
arch_build=x86_64
compiler=msvc
compiler.version=193
build_type=RelWithDebInfo
arch=x86_64
compiler.cppstd=20
compiler.runtime=dynamic
```
</details>
Conan generates the following:
<details>
<summary>CmakePresets.json</summary>
```
{
"version": 3,
"vendor": {
"conan": {}
},
"cmakeMinimumRequired": {
"major": 3,
"minor": 15,
"patch": 0
},
"configurePresets": [
{
"name": "relwithdebinfo",
"displayName": "'relwithdebinfo' config",
"description": "'relwithdebinfo' configure using 'Ninja' generator",
"generator": "Ninja",
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
"CMAKE_BUILD_TYPE": "RelWithDebInfo"
},
"architecture": {
"value": "x86",
"strategy": "external"
},
"toolchainFile": "C:\\projects\\build\\conan\\build\\RelWithDebInfo\\generators\\conan_toolchain.cmake",
"binaryDir": "C:\\projects\\build\\conan\\build\\RelWithDebInfo"
}
],
"buildPresets": [
{
"name": "relwithdebinfo",
"configurePreset": "relwithdebinfo"
}
],
"testPresets": [
{
"name": "relwithdebinfo",
"configurePreset": "relwithdebinfo"
}
]
}
```
</details>
<details>
<summary>CMakeUserPresets.json</summary>
```
{
"version": 4,
"vendor": {
"conan": {}
},
"include": [
"C:\\projects\\build\\conan\\build\\RelWithDebInfo\\generators\\CMakePresets.json"
]
}
```
</details>
<details>
<summary>conan_toolchain.cmake</summary>
```
# Conan automatically generated toolchain file
# DO NOT EDIT MANUALLY, it will be overwritten
# Avoid including toolchain file several times (bad if appending to variables like
# CMAKE_CXX_FLAGS. See https://github.com/android/ndk/issues/323
include_guard()
message(STATUS "Using Conan toolchain: ${CMAKE_CURRENT_LIST_FILE}")
if(${CMAKE_VERSION} VERSION_LESS "3.15")
message(FATAL_ERROR "The 'CMakeToolchain' generator only works with CMake >= 3.15")
endif()
# Definition of VS runtime, defined from build_type, compiler.runtime, compiler.runtime_type
cmake_policy(GET CMP0091 POLICY_CMP0091)
if(NOT "${POLICY_CMP0091}" STREQUAL NEW)
message(FATAL_ERROR "The CMake policy CMP0091 must be NEW, but is '${POLICY_CMP0091}'")
endif()
set(CMAKE_MSVC_RUNTIME_LIBRARY "$<$<CONFIG:RelWithDebInfo>:MultiThreadedDLL>")
message(STATUS "Conan toolchain: C++ Standard 20 with extensions OFF")
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Extra c, cxx, linkflags and defines
if(DEFINED CONAN_CXX_FLAGS)
string(APPEND CMAKE_CXX_FLAGS_INIT " ${CONAN_CXX_FLAGS}")
endif()
if(DEFINED CONAN_C_FLAGS)
string(APPEND CMAKE_C_FLAGS_INIT " ${CONAN_C_FLAGS}")
endif()
if(DEFINED CONAN_SHARED_LINKER_FLAGS)
string(APPEND CMAKE_SHARED_LINKER_FLAGS_INIT " ${CONAN_SHARED_LINKER_FLAGS}")
endif()
if(DEFINED CONAN_EXE_LINKER_FLAGS)
string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " ${CONAN_EXE_LINKER_FLAGS}")
endif()
get_property( _CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE )
if(_CMAKE_IN_TRY_COMPILE)
message(STATUS "Running toolchain IN_TRY_COMPILE")
return()
endif()
set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON)
# Definition of CMAKE_MODULE_PATH
# the generators folder (where conan generates files, like this toolchain)
list(PREPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
# Definition of CMAKE_PREFIX_PATH, CMAKE_XXXXX_PATH
# The Conan local "generators" folder, where this toolchain is saved.
list(PREPEND CMAKE_PREFIX_PATH ${CMAKE_CURRENT_LIST_DIR} )
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_PACKAGE OR CMAKE_FIND_ROOT_PATH_MODE_PACKAGE STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE "BOTH")
endif()
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_PROGRAM OR CMAKE_FIND_ROOT_PATH_MODE_PROGRAM STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM "BOTH")
endif()
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_LIBRARY OR CMAKE_FIND_ROOT_PATH_MODE_LIBRARY STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY "BOTH")
endif()
if(NOT DEFINED CMAKE_FIND_ROOT_PATH_MODE_INCLUDE OR CMAKE_FIND_ROOT_PATH_MODE_INCLUDE STREQUAL "ONLY")
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE "BOTH")
endif()
if (DEFINED ENV{PKG_CONFIG_PATH})
set(ENV{PKG_CONFIG_PATH} "C:/projects/build/conan/build/RelWithDebInfo/generators;$ENV{PKG_CONFIG_PATH}")
else()
set(ENV{PKG_CONFIG_PATH} "C:/projects/build/conan/build/RelWithDebInfo/generators;")
endif()
message(STATUS "Conan toolchain: Setting BUILD_SHARED_LIBS = OFF")
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build shared libraries")
# Variables
# Variables per configuration
# Preprocessor definitions
# Preprocessor definitions per configuration
```
</details>
If I then add `toolset_arch` to my `global.conf`:
```diff
tools.cmake.cmaketoolchain:generator=Ninja
+tools.cmake.cmaketoolchain:toolset_arch=x64
```
Then I see toolset partially added to the generated CMakePresets.json:
```diff
"generator": "Ninja",
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
"CMAKE_BUILD_TYPE": "RelWithDebInfo"
},
+"toolset": {
+ "value": "host=x64",
+ "strategy": "external"
+},
"architecture": {
"value": "x86",
"strategy": "external"
},
```
But, in order to get VSCode (and hopefully Qt Creator soon) to detect / pick the right toolset, it needs to be:
```diff
"toolset": {
- "value": "host=x64",
+ "value": "v193,host=x64",
"strategy": "external"
},
```
And like the "Visual Studio" compiler, I'm not seeing `CMAKE_GENERATOR_PLATFORM` or `CMAKE_GENERATOR_TOOLSET` there either.
> The reason why things are by default if possible in the toolchain file is because conan needs to be compatible down to CMake 3.15, so no presets. The more things we put in the presets, the more complicated is for developers with CMake < 3.20 to issue a command line that will work for them.
Completely understandable. I appreciate your commitment to maintaining support/stability for folks on older versions of CMake.
I guess I was under the impression that when `external` was used, CMake ignored those values...so I'd be surprised if it complicated command line usage in any way.
That's certainly what the CMake 3.20 [cmake-presets doc](https://cmake.org/cmake/help/v3.20/manual/cmake-presets.7.html) seems to suggest:
>"external"
> Do not set the value, even if the generator supports it. This is useful if, for example, a preset uses the Ninja generator, and an IDE knows how to set up the Visual C++ environment from the architecture and toolset fields. **In that case, CMake will ignore the field, but the IDE can use them to set up the environment before invoking CMake.**
Same for the MSDN doc according to [Select your target and host architecture when building with the Visual C++ toolset](
https://learn.microsoft.com/en-us/cpp/build/cmake-presets-vs?view=msvc-170#select-your-target-and-host-architecture-when-building-with-the-visual-c-toolset):
> The `architecture.strategy` and `toolset.strategy` values tell CMake how to handle the architecture and toolset fields. `set` means CMake sets the respective value, **and `external` means CMake won't set the respective value.**
---
As best I can tell, these `toolset` / `architecture` fields appear to be the way to tell the IDE what env to load. And since https://github.com/conan-io/conan/pull/11666, Conan already has limited support for this with Visual Studio, so I was hoping it may be possible to extend what we write slightly that way we can support more IDEs like VSCode (and soon Qt Creator and maybe eventually CLion). At least I struggle to see how it could be worse than the status quo.
Conan just needs to prefix the `toolset.value` with the toolset version somehow.
https://github.com/conan-io/conan/blob/aef2eea04fa5c457ae28950b836264d969ec1322/conan/tools/cmake/presets.py#L70
Really bad psuedo code:
```diff
+toolset_version = msvc_version_to_toolset_version(conanfile.settings.get_safe("compiler.version"))
+toolset_value = toolset_version
+if toolset_arch:
+ toolset_value = toolset_value + "," + toolset_arch
ret["toolset"] = {
- "value": toolset_arch,
+ "value": toolset_value
"strategy": "external"
}
```
Anyways, I can always work around the issue if needed. I think it'd be consistent and an improvement with what Conan is already doing, and improved CMakePresets support seems like the direction a lot of IDEs are going, but I totally understand the compatibility concerns. If the request is not in alignment with where Conan is going at present, feel free to close the issue :)
Thanks again for considering the request. Conan is a tremendous product and you, your team, and this community do a tremendous job. Keep up the good work!
CMAKE_GENERATOR_TOOLSET only affects the Visual Studio generators (well, and also Xcode and Green Hills MULTI, for non-MSVC usage). And it doesn't set the environment directly even then - it just puts the toolset into the .vcxproj files, leaving the ultimate resolution for MSBuild. It doesn't have any effect at all when you are using Ninja/Make/etc - those rely on you having already called vcvarsall. conan handle that for itself, by putting the vcvars call into conanbuild.bat (and thus into anything launched by the conanfile.py's `self.run`. But IDEs mostly don't have any way to make use of a .bat file that would launch a new shell with the environment altered, since the process is already running.
These `"strategy": "external"` toolset entries seem to be what the major IDE vendors are coalescing on, so it would be nice if conan would include that information (even though it is semi-redundant to conanvcvars.bat).
@thorntonryan, does this workaround still work for you with Conan 2.0? I am getting "No CMAKE_CXX_COMPILER could be found." which means that the VSCode does not load `vcvars`.
@mpusz ,
Using Conan 1.58 and a project using `cmake_layout`, looks like I needed to tweak the generated CMakeUserPresets.json in the following way:
```diff
```diff
{
"version": 4,
"vendor": {
"conan": {}
},
"include": [
"C:\\path\\to\\build\\Debug\\generators\\CMakePresets.json",
"C:\\path\\to\\buid\\RelWithDebInfo\\generators\\CMakePresets.json"
- ]
+ ],
+ "configurePresets": [
+ {
+ "name": "Debug",
+ "displayName": "Debug",
+ "inherits": "debug",
+ "toolset": {
+ "value": "v143,host=x64",
+ "strategy": "external"
+ },
+ "cacheVariables": {
+ "CMAKE_CXX_COMPILER": "cl.exe",
+ "CMAKE_MAKE_PROGRAM": "ninja.exe"
+ }
+ },
+ {
+ "name": "RelWithDebInfo",
+ "displayName": "RelWithDebInfo",
+ "inherits": "relwithdebinfo",
+ "toolset": {
+ "value": "v143,host=x64",
+ "strategy": "external"
+ },
+ "cacheVariables": {
+ "CMAKE_CXX_COMPILER": "cl.exe",
+ "CMAKE_MAKE_PROGRAM": "ninja.exe"
+ }
+ }
+ ],
+ "buildPresets": [
+ {
+ "name": "Debug",
+ "displayName": "Debug",
+ "configurePreset": "Debug",
+ "configuration": "Debug"
+ },
+ {
+ "name": "RelWithDebInfo",
+ "displayName": "RelWithDebInfo",
+ "configurePreset": "RelWithDebInfo",
+ "configuration": "RelWithDebInfo"
+ }
+ ]
}
```
Honestly not sure why these need to be defined. I thought I've called `cmake` from a VS Dev prompt before and it finds `cl.exe` automatically , so I'm not sure why VSCode seems to need it.
But at least it finds the _right_ `cl.exe`.
Maybe try that?
Thanks! By adding the following:
```diff
{
"version": 3,
"vendor": {
"conan": {}
},
"cmakeMinimumRequired": {
"major": 3,
"minor": 15,
"patch": 0
},
"configurePresets": [
{
"name": "conan-msvc-193",
"displayName": "'conan-msvc-193' config",
"description": "'conan-msvc-193' configure using 'Ninja Multi-Config' generator",
"generator": "Ninja Multi-Config",
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
+ "CMAKE_CXX_COMPILER": "cl.exe"
},
"architecture": {
"value": "x64",
"strategy": "external"
},
+ "toolset": {
+ "value": "v143,host=x64",
+ "strategy": "external"
+ },
"toolchainFile": "D:\\repos\\units\\build\\msvc-193\\generators\\conan_toolchain.cmake",
"binaryDir": "D:\\repos\\units\\build\\msvc-193"
}
],
"buildPresets": [
{
"name": "conan-msvc-193-release",
"configurePreset": "conan-msvc-193",
"configuration": "Release"
}
],
"testPresets": [
{
"name": "conan-msvc-193-release",
"configurePreset": "conan-msvc-193",
"configuration": "Release"
}
]
}
```
I was able to make MSVC 193 work somehow. The only problem compared to running from VS Dev prompt is that I get the following warning:
```text
warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
```
However, when I tried to do the same for MSVC 192 installed under VS2022 it didn't work. I also tried with `-c tools.microsoft.msbuild:vs_version=17` provided to conan install command line with no luck.
Wonder if [this ](https://github.com/conan-io/conan/issues/13136#issuecomment-1433407307) could be accomplished using the new `msvs_toolset` helper:
https://github.com/conan-io/conan/pull/13041
There is already `conf::tools.cmake.cmaketoolchain:toolset_arch` in place which controls the generation of the `toolset` section / injects `host=` into the `toolset.value`.
Except this is *not* correctly prefixed with `settings::compiler.toolset`, respectively is missing entirely when the config entry for `toolset_arch` wasn't overwritten.
Hi all,
I am checking this, but need some guidance, it would be necessary to update the reproduction, it seems that latest Conan 2.0.17 is adding ``toolset`` to the presets, still, it doesn't automatically work for me in VSCode, which seems the ultimate goal.
Steps:
- ``conan new cmake_exe -d name=app -d version=0.1``
- ``conan install . -c tools.cmake.cmaketoolchain:generator=Ninja``
The resulting presets will have:
```
"toolset": {
"value": "v143",
"strategy": "external"
},
"architecture": {
"value": "x64",
"strategy": "external"
},
```
- I open ``code .`` the current folder
- I have the cmake tools from Microsoft, version v1.16.32
- When configuring and trying to build, it will still not find the compiler
- Even if I edit the CMakePresets.json adding the above CXX as env-vars or cache vars, still not work
- Even if I edit and add ``v143,host=x64`` manually to the presets, still doesn't work
Can anyone please provide with detailed updated repro? Thanks!
Without `host=x64`, `"value": "v143"` is under-specified and defaults to the old x86 host toolchain.
I expect you got the warning
> [preset] Configure preset ...: No toolset architecture specified for cl.exe, using "host=x86" by default
Did you have the x86 host toolchain installed? Just guessing, but Microsoft may finally have switched to x64 as the default (and only) installed host toolset for v143.
> Without host=x64, "value": "v143" is under-specified and defaults to the old x86 host toolchain.
But even if I add it manually to my presets, still same error. (I will clarify in my above steps). Not really a x86 toolchain issue, it seems that even with the ``host=x64`` it is not working.

You clicked here?
When you do that, what messages do you get in the "Output" panel?
```
[driver] Removing C:/Users/Diego/conanws/kk/build/Release/CMakeCache.txt
[driver] Removing C:\Users\Diego\conanws\kk\build\Release\CMakeFiles
[proc] Executing command: C:\ws\cmake\cmake-3.25.3-windows-x86_64\bin\cmake.EXE -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=C:/Users/memsharded/conanws/kk/build/Release/generators/conan_toolchain.cmake -SC:/Users/memsharded/conanws/kk -BC:/Users/memsharded/conanws/kk/build/Release -G Ninja
[cmake] -- Using Conan toolchain: C:/Users/memsharded/conanws/kk/build/Release/generators/conan_toolchain.cmake
[cmake] -- Conan toolchain: C++ Standard 14 with extensions OFF
[cmake] -- The CXX compiler identification is unknown
[cmake] CMake Error at CMakeLists.txt:2 (project):
[cmake] No CMAKE_CXX_COMPILER could be found.
[cmake]
[cmake] Tell CMake where to find the compiler by setting either the environment
[cmake] variable "CXX" or the CMake cache entry CMAKE_CXX_COMPILER to the full path
[cmake] to the compiler, or to the compiler name if it is in the PATH.
```
`CMAKE_C_COMPILER` and `CMAKE_CXX_COMPILER` are both required as cache variables for Ninja. Set both to `"cl.exe"`.
No warnings prefixed with `[preset]`, so that should have been sane.
The invocation of vswhere is silent in that output
Yes, that is right, adding both
```
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
"CMAKE_BUILD_TYPE": "Release",
"CMAKE_CXX_COMPILER": "cl.exe",
"CMAKE_C_COMPILER": "cl.exe"
}
```
Seems to make it work. The output was sometimes confusing, because it runs automatically before adding it, so it is not clear if it is running with your latest changes or running the previous state.
Maybe making
```
conan install . -c tools.cmake.cmaketoolchain:generator=Ninja
-c tools.build:compiler_executables="{'c': 'cl.exe', 'cpp': 'cl.exe'}"
-c tools.cmake.cmaketoolchain:toolset_arch=x64
```
to add cl.exe to Presets (at the moment it only adds it to ``conan_toolchain.cmake``.
By the way, the way to define the x64 toolset is:
```
conan install . -c tools.cmake.cmaketoolchain:generator=Ninja -c tools.cmake.cmaketoolchain:toolset_arch=x64
```
and that will make
```
"toolset": {
"value": "v143,host=x64",
"strategy": "extern
```
automatically
> CMAKE_C_COMPILER and CMAKE_CXX_COMPILER are both required as cache variables for ~Ninja~ ~VSCode~ **VSCodes' cmake-tools integration**.
Minor correction, but this requirement is a subtle wrinkle of ~VSCode's~ VSCode's cmake-tools implementation:
https://github.com/microsoft/vscode-cmake-tools/blob/main/src/preset.ts#L753-L754
Yeah, my understanding is that the integration of cmake-tools for VSCode checks the CMAKE_XX_COMPILER to decide to call vcvars automatically.
One other thing that seems missing here is a way to have the toolset be something like `"v143,version=14.29"` when trying to use an installation that contains [Side-by-side minor version MSVC toolsets](https://devblogs.microsoft.com/cppblog/side-by-side-minor-version-msvc-toolsets-in-visual-studio-2017/). That's the syntax adopted by [`cmake -T`](https://cmake.org/cmake/help/latest/variable/CMAKE_GENERATOR_TOOLSET.html#visual-studio-toolset-selection) in [CMake 3.12 and greater]( https://gitlab.kitware.com/cmake/cmake/-/merge_requests/2093) and also copied for [VScode's handlling of toolset { . strategy: "external" }`](https://github.com/microsoft/vscode-cmake-tools/blob/main/src/installs/visualStudio.ts#L467-L469), specifically [in varsForVSInstallation](https://github.com/microsoft/vscode-cmake-tools/blob/main/src/installs/visualStudio.ts#L467-L469))
So maybe `[conf]tools.cmake.cmaketoolchain:toolset_version`, translated to `,version=...` and appended similarly to `toolset_arch`?
Hmm, actually this seems to be partially in place already:
[GenericSystemBlock.get_toolset](https://github.com/conan-io/conan/blob/8f86d38b92c22f82ad674ed69a1bf684fe056b32/conan/tools/cmake/toolchain/blocks.py#L696-L700) already has code to use settings.compiler.version and settings.compiler.update such that compiler.version=193 and compiler.update=7 would result in toolset=...,version=14.37. Which I think is good enough - Visual Studio doesn't support side-by-side patch versions, just side-by-side minors, so there's little reason to what to specify a 3- or 4-digit version anyway. And if you care, you probably care enough that putting it in settings (and thus getting distinct package_id) is appropriate.
But [conan.tools.microsoft.visual._vcvars_vers](https://github.com/conan-io/conan/blob/8f86d38b92c22f82ad674ed69a1bf684fe056b32/conan/tools/microsoft/visual.py#L290) does not seem to have similar code to consider settings.compiler.update, so it will only do 14.1, 14.2, or 14.3, but never distinguish `-vcvars_ver=14.37` vs `-vcvars_ver=14.38`. Which means conanbuild.bat wouldn't get the same minor version that CMakePresets does....
Split off the VCvars issue as #15522, since that's not actually about CMakePresets
https://github.com/conan-io/conan/issues/15522 has been merged it will be in Conan 2.3.
I was having another look, this is the current state:
- The Coan integrations already generate the right Presets ``toolset`` information
- I cannot manage to make it work the previous workaround of adding
```python
"cacheVariables": {
"CMAKE_POLICY_DEFAULT_CMP0091": "NEW",
"CMAKE_BUILD_TYPE": "Release",
"CMAKE_CXX_COMPILER": "cl.exe",
"CMAKE_C_COMPILER": "cl.exe"
}
```
for VSCode automatically launching vcvars, this is not happening anymore.
Can anyone please confirm this? The only missing gap would be the ``CMAKE_<LANG>_COMPILER`` definitions? Can you make it work with such workaround?
--------------------
</issues> | 4a5b19a75db9225316c8cb022a2dfb9705a2af34 | |
aws-cloudformation__cfn-lint-3546 | 3,546 | aws-cloudformation/cfn-lint | null | 4d2355dda2ecb981e70f117c7d597a51ac443715 | 2024-07-30T22:47:28Z | diff --git a/src/cfnlint/rules/resources/ecs/ServiceFargate.py b/src/cfnlint/rules/resources/ecs/ServiceFargate.py
new file mode 100644
index 0000000000..1d03742e68
--- /dev/null
+++ b/src/cfnlint/rules/resources/ecs/ServiceFargate.py
@@ -0,0 +1,138 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any, Iterator
+
+from cfnlint.helpers import ensure_list, is_function
+from cfnlint.jsonschema import ValidationError, ValidationResult
+from cfnlint.jsonschema.protocols import Validator
+from cfnlint.rules.helpers import get_resource_by_name, get_value_from_path
+from cfnlint.rules.jsonschema.CfnLintKeyword import CfnLintKeyword
+
+
+class ServiceFargate(CfnLintKeyword):
+ id = "E3054"
+ shortdesc = (
+ "Validate ECS service using Fargate uses TaskDefinition that allows Fargate"
+ )
+ description = (
+ "When using an ECS service with 'LaunchType' of 'FARGATE' "
+ "the associated task definition must have 'RequiresCompatibilities' "
+ "specified with 'FARGATE' listed"
+ )
+ tags = ["resources", "ecs"]
+
+ def __init__(self) -> None:
+ super().__init__(
+ keywords=["Resources/AWS::ECS::Service/Properties"],
+ )
+
+ def _filter_resource_name(self, instance: Any) -> str | None:
+ fn_k, fn_v = is_function(instance)
+ if fn_k is None:
+ return None
+ if fn_k == "Ref":
+ if isinstance(fn_v, str):
+ return fn_v
+ elif fn_k == "Fn::GetAtt":
+ name = ensure_list(fn_v)[0].split(".")[0]
+ if isinstance(name, str):
+ return name
+ return None
+
+ def _get_service_properties(
+ self, validator: Validator, instance: Any
+ ) -> Iterator[tuple[str, str, Validator]]:
+ for task_definition_id, task_definition_validator in get_value_from_path(
+ validator, instance, deque(["TaskDefinition"])
+ ):
+ task_definition_resource_name = self._filter_resource_name(
+ task_definition_id
+ )
+ if task_definition_resource_name is None:
+ continue
+
+ for (
+ launch_type,
+ launch_type_validator,
+ ) in get_value_from_path(
+ task_definition_validator, instance, deque(["LaunchType"])
+ ):
+ yield (
+ task_definition_resource_name,
+ launch_type,
+ launch_type_validator,
+ )
+
+ def _get_task_definition_properties(
+ self, validator: Validator, resource_name: Any
+ ) -> Iterator[tuple[list[Any] | None, Validator]]:
+ task_definition, task_definition_validator = get_resource_by_name(
+ validator, resource_name, ["AWS::ECS::TaskDefinition"]
+ )
+ if not task_definition:
+ return
+
+ for capabilities, capabilities_validator in get_value_from_path(
+ task_definition_validator,
+ task_definition,
+ path=deque(["Properties", "RequiresCompatibilities"]),
+ ):
+ if capabilities is None:
+ yield capabilities, capabilities_validator
+ continue
+ if not isinstance(capabilities, list):
+ continue
+ for capibility, _ in get_value_from_path(
+ capabilities_validator,
+ capabilities,
+ path=deque(["*"]),
+ ):
+ if isinstance(capibility, dict) or capibility == "FARGATE":
+ break
+ else:
+ yield capabilities, capabilities_validator
+
+ def validate(
+ self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+
+ for (
+ task_definition_resource_name,
+ launch_type,
+ service_validator,
+ ) in self._get_service_properties(
+ validator,
+ instance,
+ ):
+ if launch_type != "FARGATE":
+ continue
+ for (
+ capabilities,
+ capabilities_validator,
+ ) in self._get_task_definition_properties(
+ service_validator,
+ task_definition_resource_name,
+ ):
+ if capabilities is None:
+ yield ValidationError(
+ "'RequiresCompatibilities' is a required property",
+ validator="required",
+ rule=self,
+ path_override=deque(
+ list(capabilities_validator.context.path.path)[:-1]
+ ),
+ )
+ continue
+
+ yield ValidationError(
+ f"{capabilities!r} does not contain items matching 'FARGATE'",
+ validator="contains",
+ rule=self,
+ path_override=capabilities_validator.context.path.path,
+ )
diff --git a/src/cfnlint/rules/resources/ecs/ServiceNetworkConfiguration.py b/src/cfnlint/rules/resources/ecs/ServiceNetworkConfiguration.py
new file mode 100644
index 0000000000..0a2d19e45c
--- /dev/null
+++ b/src/cfnlint/rules/resources/ecs/ServiceNetworkConfiguration.py
@@ -0,0 +1,107 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any, Iterator
+
+from cfnlint.helpers import ensure_list, is_function
+from cfnlint.jsonschema import ValidationError, ValidationResult
+from cfnlint.jsonschema.protocols import Validator
+from cfnlint.rules.helpers import get_resource_by_name, get_value_from_path
+from cfnlint.rules.jsonschema.CfnLintKeyword import CfnLintKeyword
+
+
+class ServiceNetworkConfiguration(CfnLintKeyword):
+ id = "E3052"
+ shortdesc = "Validate ECS service requires NetworkConfiguration"
+ description = (
+ "When using an ECS task definition has NetworkMode set to "
+ "'awsvpc' then 'NetworkConfiguration' is required"
+ )
+ tags = ["resources", "ecs"]
+
+ def __init__(self) -> None:
+ super().__init__(
+ keywords=["Resources/AWS::ECS::Service/Properties"],
+ )
+
+ def _filter_resource_name(self, instance: Any) -> str | None:
+ fn_k, fn_v = is_function(instance)
+ if fn_k is None:
+ return None
+ if fn_k == "Ref":
+ if isinstance(fn_v, str):
+ return fn_v
+ elif fn_k == "Fn::GetAtt":
+ name = ensure_list(fn_v)[0].split(".")[0]
+ if isinstance(name, str):
+ return name
+ return None
+
+ def _get_service_properties(
+ self, validator: Validator, instance: Any
+ ) -> Iterator[tuple[str, str, Validator]]:
+ for task_definition_id, task_definition_validator in get_value_from_path(
+ validator, instance, deque(["TaskDefinition"])
+ ):
+ task_definition_resource_name = self._filter_resource_name(
+ task_definition_id
+ )
+ if task_definition_resource_name is None:
+ continue
+
+ for (
+ network_configuration,
+ network_configuration_validator,
+ ) in get_value_from_path(
+ task_definition_validator, instance, deque(["NetworkConfiguration"])
+ ):
+ yield (
+ task_definition_resource_name,
+ network_configuration,
+ network_configuration_validator,
+ )
+
+ def _get_task_definition_properties(
+ self, validator: Validator, resource_name: Any
+ ) -> Iterator[tuple[str | int | None, Validator]]:
+ target_group, target_group_validator = get_resource_by_name(
+ validator, resource_name, ["AWS::ECS::TaskDefinition"]
+ )
+ if not target_group:
+ return
+
+ for network_mode, network_mode_validator in get_value_from_path(
+ target_group_validator,
+ target_group,
+ path=deque(["Properties", "NetworkMode"]),
+ ):
+ if network_mode == "awsvpc":
+ yield network_mode, network_mode_validator
+
+ def validate(
+ self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+
+ for (
+ task_definition_resource_name,
+ network_configuration,
+ task_definition_validator,
+ ) in self._get_service_properties(
+ validator,
+ instance,
+ ):
+ for _, _ in self._get_task_definition_properties(
+ task_definition_validator,
+ task_definition_resource_name,
+ ):
+ if network_configuration is None:
+ yield ValidationError(
+ "'NetworkConfiguration' is a required property",
+ validator="required",
+ rule=self,
+ )
diff --git a/src/cfnlint/rules/resources/ecs/TaskDefinitionAwsVpc.py b/src/cfnlint/rules/resources/ecs/TaskDefinitionAwsVpc.py
new file mode 100644
index 0000000000..603088ff56
--- /dev/null
+++ b/src/cfnlint/rules/resources/ecs/TaskDefinitionAwsVpc.py
@@ -0,0 +1,81 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any, Iterator
+
+from cfnlint.jsonschema import ValidationError, ValidationResult
+from cfnlint.jsonschema.protocols import Validator
+from cfnlint.rules.helpers import get_value_from_path
+from cfnlint.rules.jsonschema.CfnLintKeyword import CfnLintKeyword
+
+
+class TaskDefinitionAwsVpc(CfnLintKeyword):
+ id = "E3053"
+ shortdesc = "Validate ECS task definition is has correct values for 'HostPort'"
+ description = (
+ "The 'HostPort' must either be undefined or equal to "
+ "the 'ContainerPort' value"
+ )
+ tags = ["resources", "ecs"]
+
+ def __init__(self) -> None:
+ super().__init__(
+ keywords=["Resources/AWS::ECS::TaskDefinition/Properties"],
+ )
+
+ def _get_port_mappings(
+ self, validator: Validator, instance: Any
+ ) -> Iterator[tuple[str | int | None, str | int | None, Validator]]:
+
+ for container_definition, container_definition_validator in get_value_from_path(
+ validator,
+ instance,
+ path=deque(["ContainerDefinitions", "*", "PortMappings", "*"]),
+ ):
+ for host_port, host_port_validator in get_value_from_path(
+ container_definition_validator,
+ container_definition,
+ path=deque(["HostPort"]),
+ ):
+ if not isinstance(host_port, (str, int)):
+ continue
+ for container_port, _ in get_value_from_path(
+ host_port_validator,
+ container_definition,
+ path=deque(["ContainerPort"]),
+ ):
+ if not isinstance(container_port, (str, int)):
+ continue
+ if str(host_port) != str(container_port):
+ yield host_port, container_port, host_port_validator
+
+ def validate(
+ self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+
+ for network_mode, _ in get_value_from_path(
+ validator,
+ instance,
+ path=deque(["NetworkMode"]),
+ ):
+ if network_mode != "awsvpc":
+ continue
+ for (
+ host_port,
+ container_port,
+ port_mapping_validator,
+ ) in self._get_port_mappings(
+ validator,
+ instance,
+ ):
+ yield ValidationError(
+ f"{host_port!r} does not equal {container_port!r}",
+ validator="const",
+ rule=self,
+ path_override=port_mapping_validator.context.path.path,
+ )
| diff --git a/test/unit/rules/resources/ecs/test_service_fargate.py b/test/unit/rules/resources/ecs/test_service_fargate.py
new file mode 100644
index 0000000000..5ea578ccde
--- /dev/null
+++ b/test/unit/rules/resources/ecs/test_service_fargate.py
@@ -0,0 +1,326 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+
+import jsonpatch
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.helpers import get_value_from_path
+from cfnlint.rules.resources.ecs.ServiceFargate import ServiceFargate
+
+
+@pytest.fixture
+def rule():
+ rule = ServiceFargate()
+ yield rule
+
+
+_task_definition = {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "RequiresCompatibilities": ["FARGATE"],
+ },
+}
+
+_service = {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "TaskDefinition": {"Ref": "TaskDefinition"},
+ "LaunchType": "FARGATE",
+ },
+}
+
+
+@pytest.mark.parametrize(
+ "template,start_path,expected",
+ [
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/RequiresCompatibilities",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Fn::Sub": "${TaskDefinition.Arn}"},
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/RequiresCompatibilities",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Fn::GetAtt": "TaskDefinition.Arn"},
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ ("'RequiresCompatibilities' is a required property"),
+ validator="required",
+ rule=ServiceFargate(),
+ path_override=deque(["Resources", "TaskDefinition", "Properties"]),
+ )
+ ],
+ ),
+ (
+ {
+ "Parameters": {"MyTask": {"Type": "String"}},
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/RequiresCompatibilities",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Ref": "MyTask"},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/RequiresCompatibilities",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": "MyTask",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/RequiresCompatibilities",
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ ("'RequiresCompatibilities' is a required property"),
+ validator="required",
+ rule=ServiceFargate(),
+ path_override=deque(["Resources", "TaskDefinition", "Properties"]),
+ )
+ ],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/RequiresCompatibilities",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/LaunchType",
+ "value": "EC2",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/RequiresCompatibilities",
+ "value": [
+ "EC2",
+ "FARGATE",
+ ],
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/RequiresCompatibilities",
+ "value": [
+ "EC2",
+ "EXTERNAL",
+ ],
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ ("['EC2', 'EXTERNAL'] does not contain items matching 'FARGATE'"),
+ validator="contains",
+ rule=ServiceFargate(),
+ path_override=deque(
+ [
+ "Resources",
+ "TaskDefinition",
+ "Properties",
+ "RequiresCompatibilities",
+ ]
+ ),
+ )
+ ],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/RequiresCompatibilities",
+ "value": {"Fn::FindInMap": ["A", "B", "C"]},
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {"MyLaunchType": {"Type": "String"}},
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/RequiresCompatibilities",
+ "value": ["EC2", {"Ref": "MyLaunchType"}],
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ ],
+ indirect=["template"],
+)
+def test_validate(template, start_path, expected, rule, validator):
+ for instance, instance_validator in get_value_from_path(
+ validator, template, start_path
+ ):
+ errs = list(rule.validate(instance_validator, "", instance, {}))
+ assert errs == expected, f"Expected {expected} got {errs}"
diff --git a/test/unit/rules/resources/ecs/test_service_network_configuration.py b/test/unit/rules/resources/ecs/test_service_network_configuration.py
new file mode 100644
index 0000000000..08215e8bda
--- /dev/null
+++ b/test/unit/rules/resources/ecs/test_service_network_configuration.py
@@ -0,0 +1,268 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+
+import jsonpatch
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.helpers import get_value_from_path
+from cfnlint.rules.resources.ecs.ServiceNetworkConfiguration import (
+ ServiceNetworkConfiguration,
+)
+
+
+@pytest.fixture
+def rule():
+ rule = ServiceNetworkConfiguration()
+ yield rule
+
+
+_task_definition = {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "NetworkMode": "awsvpc",
+ "ContainerDefinitions": [],
+ },
+}
+
+_service = {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "TaskDefinition": {"Ref": "TaskDefinition"},
+ "NetworkConfiguration": {},
+ },
+}
+
+
+@pytest.mark.parametrize(
+ "template,start_path,expected",
+ [
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkMode",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/NetworkMode",
+ "value": "bridge",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {"MyNetworkMode": {"Type": "String"}},
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/NetworkMode",
+ "value": {"Ref": "MyNetworkMode"},
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ ("'NetworkConfiguration' is a required property"),
+ validator="required",
+ rule=ServiceNetworkConfiguration(),
+ )
+ ],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Fn::GetAtt": "TaskDefinition.Arn"},
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ ("'NetworkConfiguration' is a required property"),
+ validator="required",
+ rule=ServiceNetworkConfiguration(),
+ )
+ ],
+ ),
+ (
+ {
+ "Parameters": {"MyTargetGroup": {"Type": "String"}},
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Ref": "MyTargetGroup"},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Foo": "Bar"},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/NetworkConfiguration",
+ },
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Fn::Sub": "${TaskDefinition.Arn}"},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ ],
+ indirect=["template"],
+)
+def test_validate(template, start_path, expected, rule, validator):
+ for instance, instance_validator in get_value_from_path(
+ validator, template, start_path
+ ):
+ errs = list(rule.validate(instance_validator, "", instance, {}))
+ assert errs == expected, f"Expected {expected} got {errs}"
diff --git a/test/unit/rules/resources/ecs/test_task_definition_aws_vpc.py b/test/unit/rules/resources/ecs/test_task_definition_aws_vpc.py
new file mode 100644
index 0000000000..3db1ac38f4
--- /dev/null
+++ b/test/unit/rules/resources/ecs/test_task_definition_aws_vpc.py
@@ -0,0 +1,212 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+
+import jsonpatch
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.helpers import get_value_from_path
+from cfnlint.rules.resources.ecs.TaskDefinitionAwsVpc import TaskDefinitionAwsVpc
+
+
+@pytest.fixture
+def rule():
+ rule = TaskDefinitionAwsVpc()
+ yield rule
+
+
+_task_definition = {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "NetworkMode": "awsvpc",
+ "ContainerDefinitions": [
+ {
+ "Name": "my-container",
+ "Image": "my-image",
+ "PortMappings": [
+ {
+ "ContainerPort": 8080,
+ }
+ ],
+ }
+ ],
+ },
+}
+
+
+@pytest.mark.parametrize(
+ "template,start_path,expected",
+ [
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ }
+ },
+ deque(["Resources", "TaskDefinition", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "add",
+ "path": (
+ "/Properties/ContainerDefinitions/"
+ "0/PortMappings/0/HostPort"
+ ),
+ "value": "8080",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "TaskDefinition", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "add",
+ "path": (
+ "/Properties/ContainerDefinitions/"
+ "0/PortMappings/0/HostPort"
+ ),
+ "value": "8080",
+ },
+ {
+ "op": "replace",
+ "path": (
+ "/Properties/ContainerDefinitions/"
+ "0/PortMappings/0/ContainerPort"
+ ),
+ "value": {"Fn::Sub": "8080"},
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "TaskDefinition", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {
+ "MyPort": {"Type": "String"},
+ "MySecondPort": {"Type": "String"},
+ },
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "add",
+ "path": (
+ "/Properties/ContainerDefinitions/0"
+ "/PortMappings/0/ContainerPort"
+ ),
+ "value": {"Ref": "MyPort"},
+ },
+ {
+ "op": "add",
+ "path": (
+ "/Properties/ContainerDefinitions/0"
+ "/PortMappings/0/HostPort"
+ ),
+ "value": {"Ref": "MySecondPort"},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "TaskDefinition", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "add",
+ "path": (
+ "/Properties/ContainerDefinitions/0"
+ "/PortMappings/0/HostPort"
+ ),
+ "value": "80",
+ },
+ {
+ "op": "replace",
+ "path": ("/Properties/NetworkMode"),
+ "value": "bridge",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "TaskDefinition", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "add",
+ "path": (
+ "/Properties/ContainerDefinitions/0"
+ "/PortMappings/0/HostPort"
+ ),
+ "value": "80",
+ }
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "TaskDefinition", "Properties"]),
+ [
+ ValidationError(
+ ("'80' does not equal 8080"),
+ validator="const",
+ rule=TaskDefinitionAwsVpc(),
+ path_override=deque(
+ [
+ "Resources",
+ "TaskDefinition",
+ "Properties",
+ "ContainerDefinitions",
+ 0,
+ "PortMappings",
+ 0,
+ "HostPort",
+ ]
+ ),
+ )
+ ],
+ ),
+ ],
+ indirect=["template"],
+)
+def test_validate(template, start_path, expected, rule, validator):
+ for instance, instance_validator in get_value_from_path(
+ validator, template, start_path
+ ):
+ errs = list(rule.validate(instance_validator, "", instance, {}))
+
+ assert errs == expected, f"Expected {expected} got {errs}"
| [
{
"components": [
{
"doc": "",
"lines": [
18,
137
],
"name": "ServiceFargate",
"signature": "class ServiceFargate(CfnLintKeyword):",
"type": "class"
},
{
"doc": "",
"lines": [
30,
32
... | [
"test/unit/rules/resources/ecs/test_service_fargate.py::test_validate[template0-start_path0-expected0]",
"test/unit/rules/resources/ecs/test_service_fargate.py::test_validate[template1-start_path1-expected1]",
"test/unit/rules/resources/ecs/test_service_fargate.py::test_validate[template2-start_path2-expected2]... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add 3 new rules to validate ECS configs
*Issue #, if available:*
fix #1547
*Description of changes:*
- Add 3 new rules to validate ECS configs
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
----------
</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/cfnlint/rules/resources/ecs/ServiceFargate.py]
(definition of ServiceFargate:)
class ServiceFargate(CfnLintKeyword):
(definition of ServiceFargate.__init__:)
def __init__(self) -> None:
(definition of ServiceFargate._filter_resource_name:)
def _filter_resource_name(self, instance: Any) -> str | None:
(definition of ServiceFargate._get_service_properties:)
def _get_service_properties( self, validator: Validator, instance: Any ) -> Iterator[tuple[str, str, Validator]]:
(definition of ServiceFargate._get_task_definition_properties:)
def _get_task_definition_properties( self, validator: Validator, resource_name: Any ) -> Iterator[tuple[list[Any] | None, Validator]]:
(definition of ServiceFargate.validate:)
def validate( self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/ecs/ServiceFargate.py]
[start of new definitions in src/cfnlint/rules/resources/ecs/ServiceNetworkConfiguration.py]
(definition of ServiceNetworkConfiguration:)
class ServiceNetworkConfiguration(CfnLintKeyword):
(definition of ServiceNetworkConfiguration.__init__:)
def __init__(self) -> None:
(definition of ServiceNetworkConfiguration._filter_resource_name:)
def _filter_resource_name(self, instance: Any) -> str | None:
(definition of ServiceNetworkConfiguration._get_service_properties:)
def _get_service_properties( self, validator: Validator, instance: Any ) -> Iterator[tuple[str, str, Validator]]:
(definition of ServiceNetworkConfiguration._get_task_definition_properties:)
def _get_task_definition_properties( self, validator: Validator, resource_name: Any ) -> Iterator[tuple[str | int | None, Validator]]:
(definition of ServiceNetworkConfiguration.validate:)
def validate( self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/ecs/ServiceNetworkConfiguration.py]
[start of new definitions in src/cfnlint/rules/resources/ecs/TaskDefinitionAwsVpc.py]
(definition of TaskDefinitionAwsVpc:)
class TaskDefinitionAwsVpc(CfnLintKeyword):
(definition of TaskDefinitionAwsVpc.__init__:)
def __init__(self) -> None:
(definition of TaskDefinitionAwsVpc._get_port_mappings:)
def _get_port_mappings( self, validator: Validator, instance: Any ) -> Iterator[tuple[str | int | None, str | int | None, Validator]]:
(definition of TaskDefinitionAwsVpc.validate:)
def validate( self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/ecs/TaskDefinitionAwsVpc.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>
New Fargate Rules
*cfn-lint version: (`cfn-lint --version`)*: 0.32.1
*Description of issue.* New Rule Suggestions for ECS Fargate
Having just tried to deploy a new task alongside some existing tasks in Fargate, I ran across quite a few deployment failures that cfn-lint didn't warn me against, so this issue is simply a proposal for new rules to cover these cases.
- [x] ~~[Error] When an `AWS::ECS::Service` has its `LaunchType` set to `FARGATE`, it cannot have `SchedulingStrategy` set to `DAEMON`. Currently the only supported `SchedulingStrategy` is `REPLICA`. Reference: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html#service_scheduler.~~ https://github.com/aws-cloudformation/cfn-lint/pull/2559
- [ ] [Error] When an `AWS::ECS::TaskDefinition` has its `NetworkMode` set to `awsvpc`, then any `AWS::ECS::TaskDefinition ContainerDefinition` subresources should either not specify any `HostPort` within each `PortMappings` entry, or should set it to equal the corresponding `ContainerPort`. Reference: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-portmappings.
- [ ] [Error] When an `AWS::ECS::TaskDefinition` has its `NetworkMode` set to `awsvpc`, its parent `AWS::ECS::Service` resource must specify a `NetworkConfiguration` (which should be of type `AWS::ECS::Service AwsVpcConfiguration`. Reference: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-networkconfiguration.
- [x] ~~[Error] Every `AWS::ECS::TaskDefinition` must contain at least one `AWS::ECS::TaskDefinition ContainerDefinition` that has `Essential` set to `true`. Reference: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-essential.~~ https://github.com/aws-cloudformation/cfn-python-lint/pull/1548
----------
Adding another suggestion to fargate rules:
- [ ] [Error] When `AWS::ECS::Service` has `LauchType` set to `FARGATE`, but the `TaskDefinition` it references does not specify `"RequiresCapabilities": ["FARGATE"]` (causes "Task definition does not support launch_type FARGATE.")
--------------------
</issues> | 4b214774e419d871b7b498fb5256e2ed09393795 | |
deepset-ai__haystack-8122 | 8,122 | deepset-ai/haystack | null | 3d1ad10385e5545abef14b811d72a405c2f5c967 | 2024-07-30T09:49:23Z | diff --git a/docs/pydoc/config/joiners_api.yml b/docs/pydoc/config/joiners_api.yml
index ad6e89a52a..6b7d422166 100644
--- a/docs/pydoc/config/joiners_api.yml
+++ b/docs/pydoc/config/joiners_api.yml
@@ -1,7 +1,7 @@
loaders:
- type: haystack_pydoc_tools.loaders.CustomPythonLoader
search_path: [../../../haystack/components/joiners]
- modules: ["document_joiner", "branch"]
+ modules: ["document_joiner", "branch", "answer_joiner"]
ignore_when_discovered: ["__init__"]
processors:
- type: filter
diff --git a/haystack/components/joiners/__init__.py b/haystack/components/joiners/__init__.py
index a72f73c134..57878c209c 100644
--- a/haystack/components/joiners/__init__.py
+++ b/haystack/components/joiners/__init__.py
@@ -2,7 +2,8 @@
#
# SPDX-License-Identifier: Apache-2.0
+from .answer_joiner import AnswerJoiner
from .branch import BranchJoiner
from .document_joiner import DocumentJoiner
-__all__ = ["DocumentJoiner", "BranchJoiner"]
+__all__ = ["DocumentJoiner", "BranchJoiner", "AnswerJoiner"]
diff --git a/haystack/components/joiners/answer_joiner.py b/haystack/components/joiners/answer_joiner.py
new file mode 100644
index 0000000000..3a6a8b8246
--- /dev/null
+++ b/haystack/components/joiners/answer_joiner.py
@@ -0,0 +1,172 @@
+# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
+#
+# SPDX-License-Identifier: Apache-2.0
+
+import itertools
+from enum import Enum
+from math import inf
+from typing import Any, Callable, Dict, List, Optional, Union
+
+from haystack import component, default_from_dict, default_to_dict, logging
+from haystack.core.component.types import Variadic
+from haystack.dataclasses.answer import ExtractedAnswer, ExtractedTableAnswer, GeneratedAnswer
+
+AnswerType = Union[GeneratedAnswer, ExtractedTableAnswer, ExtractedAnswer]
+
+logger = logging.getLogger(__name__)
+
+
+class JoinMode(Enum):
+ """
+ Enum for AnswerJoiner join modes.
+ """
+
+ CONCATENATE = "concatenate"
+
+ def __str__(self):
+ return self.value
+
+ @staticmethod
+ def from_str(string: str) -> "JoinMode":
+ """
+ Convert a string to a JoinMode enum.
+ """
+ enum_map = {e.value: e for e in JoinMode}
+ mode = enum_map.get(string)
+ if mode is None:
+ msg = f"Unknown join mode '{string}'. Supported modes in AnswerJoiner are: {list(enum_map.keys())}"
+ raise ValueError(msg)
+ return mode
+
+
+@component
+class AnswerJoiner:
+ """
+ Merges multiple lists of `Answer` objects into a single list.
+
+ Use this component to combine answers from different Generators into a single list.
+ Currently, the component supports only one join mode: `CONCATENATE`.
+ This mode concatenates multiple lists of answers into a single list.
+
+ ### Usage example
+
+ In this example, AnswerJoiner merges answers from two different Generators:
+
+ ```python
+ from haystack.components.builders import AnswerBuilder
+ from haystack.components.joiners import AnswerJoiner
+
+ from haystack.core.pipeline import Pipeline
+
+ from haystack.components.generators.chat import OpenAIChatGenerator
+ from haystack.dataclasses import ChatMessage
+
+
+ query = "What's Natural Language Processing?"
+ messages = [ChatMessage.from_system("You are a helpful, respectful and honest assistant. Be super concise."),
+ ChatMessage.from_user(query)]
+
+ pipe = Pipeline()
+ pipe.add_component("gpt-4o", OpenAIChatGenerator(model="gpt-4o"))
+ pipe.add_component("llama", OpenAIChatGenerator(model="gpt-3.5-turbo"))
+ pipe.add_component("aba", AnswerBuilder())
+ pipe.add_component("abb", AnswerBuilder())
+ pipe.add_component("joiner", AnswerJoiner())
+
+ pipe.connect("gpt-4o.replies", "aba")
+ pipe.connect("llama.replies", "abb")
+ pipe.connect("aba.answers", "joiner")
+ pipe.connect("abb.answers", "joiner")
+
+ results = pipe.run(data={"gpt-4o": {"messages": messages},
+ "llama": {"messages": messages},
+ "aba": {"query": query},
+ "abb": {"query": query}})
+ ```
+ """
+
+ def __init__(
+ self,
+ join_mode: Union[str, JoinMode] = JoinMode.CONCATENATE,
+ top_k: Optional[int] = None,
+ sort_by_score: bool = False,
+ ):
+ """
+ Creates an AnswerJoiner component.
+
+ :param join_mode:
+ Specifies the join mode to use. Available modes:
+ - `concatenate`: Concatenates multiple lists of Answers into a single list.
+ :param top_k:
+ The maximum number of Answers to return.
+ :param sort_by_score:
+ If `True`, sorts the documents by score in descending order.
+ If a document has no score, it is handled as if its score is -infinity.
+ """
+ if isinstance(join_mode, str):
+ join_mode = JoinMode.from_str(join_mode)
+ join_mode_functions: Dict[JoinMode, Callable[[List[List[AnswerType]]], List[AnswerType]]] = {
+ JoinMode.CONCATENATE: self._concatenate
+ }
+ self.join_mode_function: Callable[[List[List[AnswerType]]], List[AnswerType]] = join_mode_functions[join_mode]
+ self.join_mode = join_mode
+ self.top_k = top_k
+ self.sort_by_score = sort_by_score
+
+ @component.output_types(answers=List[AnswerType])
+ def run(self, answers: Variadic[List[AnswerType]], top_k: Optional[int] = None):
+ """
+ Joins multiple lists of Answers into a single list depending on the `join_mode` parameter.
+
+ :param answers:
+ Nested list of Answers to be merged.
+
+ :param top_k:
+ The maximum number of Answers to return. Overrides the instance's `top_k` if provided.
+
+ :returns:
+ A dictionary with the following keys:
+ - `answers`: Merged list of Answers
+ """
+ answers_list = list(answers)
+ join_function = self.join_mode_function
+ output_answers: List[AnswerType] = join_function(answers_list)
+
+ if self.sort_by_score:
+ output_answers = sorted(
+ output_answers, key=lambda answer: answer.score if hasattr(answer, "score") else -inf, reverse=True
+ )
+
+ top_k = top_k or self.top_k
+ if top_k:
+ output_answers = output_answers[:top_k]
+ return {"answers": output_answers}
+
+ def _concatenate(self, answer_lists: List[List[AnswerType]]) -> List[AnswerType]:
+ """
+ Concatenate multiple lists of Answers, flattening them into a single list and sorting by score.
+
+ :param answer_lists: List of lists of Answers to be flattened.
+ """
+ return list(itertools.chain.from_iterable(answer_lists))
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Serializes the component to a dictionary.
+
+ :returns:
+ Dictionary with serialized data.
+ """
+ return default_to_dict(self, join_mode=str(self.join_mode), top_k=self.top_k, sort_by_score=self.sort_by_score)
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "AnswerJoiner":
+ """
+ Deserializes the component from a dictionary.
+
+ :param data:
+ The dictionary to deserialize from.
+ :returns:
+ The deserialized component.
+ """
+ return default_from_dict(cls, data)
diff --git a/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml b/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml
new file mode 100644
index 0000000000..e1773183d3
--- /dev/null
+++ b/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml
@@ -0,0 +1,5 @@
+---
+features:
+ - |
+ Introduced a new AnswerJoiner component that allows joining multiple lists of Answers into a single list using
+ the Concatenate join mode.
| diff --git a/test/components/joiners/test_answer_joiner.py b/test/components/joiners/test_answer_joiner.py
new file mode 100644
index 0000000000..b7ba764ec2
--- /dev/null
+++ b/test/components/joiners/test_answer_joiner.py
@@ -0,0 +1,141 @@
+# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
+#
+# SPDX-License-Identifier: Apache-2.0
+import os
+
+import pytest
+
+from haystack.components.builders import AnswerBuilder
+
+from haystack import Document, Pipeline
+from haystack.dataclasses.answer import ExtractedAnswer, GeneratedAnswer, ExtractedTableAnswer
+from haystack.components.generators.chat import OpenAIChatGenerator
+from haystack.components.joiners.answer_joiner import AnswerJoiner, JoinMode
+from haystack.dataclasses import ChatMessage
+
+
+class TestAnswerJoiner:
+ def test_init(self):
+ joiner = AnswerJoiner()
+ assert joiner.join_mode == JoinMode.CONCATENATE
+ assert joiner.top_k is None
+ assert joiner.sort_by_score is False
+
+ def test_init_with_custom_parameters(self):
+ joiner = AnswerJoiner(join_mode="concatenate", top_k=5, sort_by_score=True)
+ assert joiner.join_mode == JoinMode.CONCATENATE
+ assert joiner.top_k == 5
+ assert joiner.sort_by_score is True
+
+ def test_to_dict(self):
+ joiner = AnswerJoiner()
+ data = joiner.to_dict()
+ assert data == {
+ "type": "haystack.components.joiners.answer_joiner.AnswerJoiner",
+ "init_parameters": {"join_mode": "concatenate", "top_k": None, "sort_by_score": False},
+ }
+
+ def test_to_from_dict_custom_parameters(self):
+ joiner = AnswerJoiner("concatenate", top_k=5, sort_by_score=True)
+ data = joiner.to_dict()
+ assert data == {
+ "type": "haystack.components.joiners.answer_joiner.AnswerJoiner",
+ "init_parameters": {"join_mode": "concatenate", "top_k": 5, "sort_by_score": True},
+ }
+
+ deserialized_joiner = AnswerJoiner.from_dict(data)
+ assert deserialized_joiner.join_mode == JoinMode.CONCATENATE
+ assert deserialized_joiner.top_k == 5
+ assert deserialized_joiner.sort_by_score is True
+
+ def test_from_dict(self):
+ data = {"type": "haystack.components.joiners.answer_joiner.AnswerJoiner", "init_parameters": {}}
+ answer_joiner = AnswerJoiner.from_dict(data)
+ assert answer_joiner.join_mode == JoinMode.CONCATENATE
+ assert answer_joiner.top_k is None
+ assert answer_joiner.sort_by_score is False
+
+ def test_from_dict_customs_parameters(self):
+ data = {
+ "type": "haystack.components.joiners.answer_joiner.AnswerJoiner",
+ "init_parameters": {"join_mode": "concatenate", "top_k": 5, "sort_by_score": True},
+ }
+ answer_joiner = AnswerJoiner.from_dict(data)
+ assert answer_joiner.join_mode == JoinMode.CONCATENATE
+ assert answer_joiner.top_k == 5
+ assert answer_joiner.sort_by_score is True
+
+ def test_empty_list(self):
+ joiner = AnswerJoiner()
+ result = joiner.run([])
+ assert result == {"answers": []}
+
+ def test_list_of_empty_lists(self):
+ joiner = AnswerJoiner()
+ result = joiner.run([[], []])
+ assert result == {"answers": []}
+
+ def test_list_of_single_answer(self):
+ joiner = AnswerJoiner()
+ answers = [
+ GeneratedAnswer(query="a", data="a", meta={}, documents=[Document(content="a")]),
+ GeneratedAnswer(query="b", data="b", meta={}, documents=[Document(content="b")]),
+ GeneratedAnswer(query="c", data="c", meta={}, documents=[Document(content="c")]),
+ ]
+ result = joiner.run([answers])
+ assert result == {"answers": answers}
+
+ def test_two_lists_of_generated_answers(self):
+ joiner = AnswerJoiner()
+ answers1 = [GeneratedAnswer(query="a", data="a", meta={}, documents=[Document(content="a")])]
+ answers2 = [GeneratedAnswer(query="d", data="d", meta={}, documents=[Document(content="d")])]
+ result = joiner.run([answers1, answers2])
+ assert result == {"answers": answers1 + answers2}
+
+ def test_multiple_lists_of_mixed_answers(self):
+ joiner = AnswerJoiner()
+ answers1 = [GeneratedAnswer(query="a", data="a", meta={}, documents=[Document(content="a")])]
+ answers2 = [ExtractedAnswer(query="d", score=0.9, meta={}, document=Document(content="d"))]
+ answers3 = [ExtractedTableAnswer(query="e", score=0.7, meta={}, document=Document(content="e"))]
+ answers4 = [GeneratedAnswer(query="f", data="f", meta={}, documents=[Document(content="f")])]
+ all_answers = answers1 + answers2 + answers3 + answers4 # type: ignore
+ result = joiner.run([answers1, answers2, answers3, answers4])
+ assert result == {"answers": all_answers}
+
+ def test_unsupported_join_mode(self):
+ unsupported_mode = "unsupported_mode"
+ with pytest.raises(ValueError):
+ AnswerJoiner(join_mode=unsupported_mode)
+
+ @pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY", ""), reason="Needs OPENAI_API_KEY to run this test.")
+ @pytest.mark.integration
+ def test_with_pipeline(self):
+ query = "What's Natural Language Processing?"
+ messages = [
+ ChatMessage.from_system("You are a helpful, respectful and honest assistant. Be super concise."),
+ ChatMessage.from_user(query),
+ ]
+
+ pipe = Pipeline()
+ pipe.add_component("gpt-4o", OpenAIChatGenerator(model="gpt-4o"))
+ pipe.add_component("llama", OpenAIChatGenerator(model="gpt-3.5-turbo"))
+ pipe.add_component("aba", AnswerBuilder())
+ pipe.add_component("abb", AnswerBuilder())
+ pipe.add_component("joiner", AnswerJoiner())
+
+ pipe.connect("gpt-4o.replies", "aba")
+ pipe.connect("llama.replies", "abb")
+ pipe.connect("aba.answers", "joiner")
+ pipe.connect("abb.answers", "joiner")
+
+ results = pipe.run(
+ data={
+ "gpt-4o": {"messages": messages},
+ "llama": {"messages": messages},
+ "aba": {"query": query},
+ "abb": {"query": query},
+ }
+ )
+
+ assert "joiner" in results
+ assert len(results["joiner"]["answers"]) == 2
| diff --git a/docs/pydoc/config/joiners_api.yml b/docs/pydoc/config/joiners_api.yml
index ad6e89a52a..6b7d422166 100644
--- a/docs/pydoc/config/joiners_api.yml
+++ b/docs/pydoc/config/joiners_api.yml
@@ -1,7 +1,7 @@
loaders:
- type: haystack_pydoc_tools.loaders.CustomPythonLoader
search_path: [../../../haystack/components/joiners]
- modules: ["document_joiner", "branch"]
+ modules: ["document_joiner", "branch", "answer_joiner"]
ignore_when_discovered: ["__init__"]
processors:
- type: filter
diff --git a/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml b/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml
new file mode 100644
index 0000000000..e1773183d3
--- /dev/null
+++ b/releasenotes/notes/introduce-answer-joiner-component-885dd7846776f5cb.yaml
@@ -0,0 +1,5 @@
+---
+features:
+ - |
+ Introduced a new AnswerJoiner component that allows joining multiple lists of Answers into a single list using
+ the Concatenate join mode.
| [
{
"components": [
{
"doc": "Enum for AnswerJoiner join modes.",
"lines": [
19,
39
],
"name": "JoinMode",
"signature": "class JoinMode(Enum):",
"type": "class"
},
{
"doc": "",
"lines": [
26,
... | [
"test/components/joiners/test_answer_joiner.py::TestAnswerJoiner::test_init",
"test/components/joiners/test_answer_joiner.py::TestAnswerJoiner::test_init_with_custom_parameters",
"test/components/joiners/test_answer_joiner.py::TestAnswerJoiner::test_to_dict",
"test/components/joiners/test_answer_joiner.py::Te... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Add `AnswerJoiner` new component
### Why:
Adds an `AnswerJoiner` to merge multiple lists of answers using various join modes, addressing the need for simplified answer aggregation.
### What:
1. Added an `AnswerJoiner` class in `haystack/components/joiners/answer_joiner.py` for merging lists of answers.
2. Modified `haystack/components/joiners/__init__.py` to include `AnswerJoiner` in the module exports.
3. Added unit tests in `test/components/joiners/test_answer_joiner.py` to validate the functionality of `AnswerJoiner`.
### How can it be used:
- Similar to DocumentJoiner
### How did you test it:
- Conducted unit tests including initialization tests, to/from dictionary serialization, empty list handling, and checking for correct answer merging.
- Verified custom join functions and error handling for unsupported join modes using pytest.
### Notes for the reviewer:
- Review the `JoinMode` enumeration in `answer_joiner.py` to ensure future proofing for additional join modes.
- Check the logic within `_concatenate` method for performance implications with large lists.
- Validate the custom join function handling to ensure robustness against edge cases.
----------
</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/joiners/answer_joiner.py]
(definition of JoinMode:)
class JoinMode(Enum):
"""Enum for AnswerJoiner join modes."""
(definition of JoinMode.__str__:)
def __str__(self):
(definition of JoinMode.from_str:)
def from_str(string: str) -> "JoinMode":
"""Convert a string to a JoinMode enum."""
(definition of AnswerJoiner:)
class AnswerJoiner:
"""Merges multiple lists of `Answer` objects into a single list.
Use this component to combine answers from different Generators into a single list.
Currently, the component supports only one join mode: `CONCATENATE`.
This mode concatenates multiple lists of answers into a single list.
### Usage example
In this example, AnswerJoiner merges answers from two different Generators:
```python
from haystack.components.builders import AnswerBuilder
from haystack.components.joiners import AnswerJoiner
from haystack.core.pipeline import Pipeline
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
query = "What's Natural Language Processing?"
messages = [ChatMessage.from_system("You are a helpful, respectful and honest assistant. Be super concise."),
ChatMessage.from_user(query)]
pipe = Pipeline()
pipe.add_component("gpt-4o", OpenAIChatGenerator(model="gpt-4o"))
pipe.add_component("llama", OpenAIChatGenerator(model="gpt-3.5-turbo"))
pipe.add_component("aba", AnswerBuilder())
pipe.add_component("abb", AnswerBuilder())
pipe.add_component("joiner", AnswerJoiner())
pipe.connect("gpt-4o.replies", "aba")
pipe.connect("llama.replies", "abb")
pipe.connect("aba.answers", "joiner")
pipe.connect("abb.answers", "joiner")
results = pipe.run(data={"gpt-4o": {"messages": messages},
"llama": {"messages": messages},
"aba": {"query": query},
"abb": {"query": query}})
```"""
(definition of AnswerJoiner.__init__:)
def __init__( self, join_mode: Union[str, JoinMode] = JoinMode.CONCATENATE, top_k: Optional[int] = None, sort_by_score: bool = False, ):
"""Creates an AnswerJoiner component.
:param join_mode:
Specifies the join mode to use. Available modes:
- `concatenate`: Concatenates multiple lists of Answers into a single list.
:param top_k:
The maximum number of Answers to return.
:param sort_by_score:
If `True`, sorts the documents by score in descending order.
If a document has no score, it is handled as if its score is -infinity."""
(definition of AnswerJoiner.run:)
def run(self, answers: Variadic[List[AnswerType]], top_k: Optional[int] = None):
"""Joins multiple lists of Answers into a single list depending on the `join_mode` parameter.
:param answers:
Nested list of Answers to be merged.
:param top_k:
The maximum number of Answers to return. Overrides the instance's `top_k` if provided.
:returns:
A dictionary with the following keys:
- `answers`: Merged list of Answers"""
(definition of AnswerJoiner._concatenate:)
def _concatenate(self, answer_lists: List[List[AnswerType]]) -> List[AnswerType]:
"""Concatenate multiple lists of Answers, flattening them into a single list and sorting by score.
:param answer_lists: List of lists of Answers to be flattened."""
(definition of AnswerJoiner.to_dict:)
def to_dict(self) -> Dict[str, Any]:
"""Serializes the component to a dictionary.
:returns:
Dictionary with serialized data."""
(definition of AnswerJoiner.from_dict:)
def from_dict(cls, data: Dict[str, Any]) -> "AnswerJoiner":
"""Deserializes the component from a dictionary.
:param data:
The dictionary to deserialize from.
:returns:
The deserialized component."""
[end of new definitions in haystack/components/joiners/answer_joiner.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-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": "DocumentCl... | [
"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/com... | 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 | |
conan-io__conan-16742 | 16,742 | conan-io/conan | null | e1063a152b8a969383f35c122a8b26eca58a0820 | 2024-07-28T14:42:58Z | diff --git a/conan/internal/api/install/generators.py b/conan/internal/api/install/generators.py
index fb7322ca651..c385820a770 100644
--- a/conan/internal/api/install/generators.py
+++ b/conan/internal/api/install/generators.py
@@ -30,7 +30,8 @@
"PremakeDeps": "conan.tools.premake",
"MakeDeps": "conan.tools.gnu",
"SConsDeps": "conan.tools.scons",
- "QbsDeps": "conan.tools.qbs"
+ "QbsDeps": "conan.tools.qbs",
+ "QbsProfile": "conan.tools.qbs"
}
diff --git a/conan/tools/microsoft/visual.py b/conan/tools/microsoft/visual.py
index ab4a7129379..7aad2edf995 100644
--- a/conan/tools/microsoft/visual.py
+++ b/conan/tools/microsoft/visual.py
@@ -127,36 +127,9 @@ def generate(self, scope="build"):
if vs_install_path == "": # Empty string means "disable"
return
- msvc_update = conanfile.conf.get("tools.microsoft:msvc_update")
- if compiler == "clang":
- # The vcvars only needed for LLVM/Clang and VS ClangCL, who define runtime
- if not conanfile.settings.get_safe("compiler.runtime"):
- # NMake Makefiles will need vcvars activated, for VS target, defined with runtime
- return
- toolset_version = conanfile.settings.get_safe("compiler.runtime_version")
- vs_version = {"v140": "14",
- "v141": "15",
- "v142": "16",
- "v143": "17",
- "v144": "17"}.get(toolset_version)
- if vs_version is None:
- raise ConanException("Visual Studio Runtime version (v140-v144) not defined")
- vcvars_ver = {"v140": "14.0",
- "v141": "14.1",
- "v142": "14.2",
- "v143": "14.3",
- "v144": "14.4"}.get(toolset_version)
- if vcvars_ver and msvc_update is not None:
- vcvars_ver += f"{msvc_update}"
- else:
- vs_version = vs_ide_version(conanfile)
- if int(vs_version) <= 14:
- vcvars_ver = None
- else:
- compiler_version = str(conanfile.settings.compiler.version)
- compiler_update = msvc_update or conanfile.settings.get_safe("compiler.update", "")
- # The equivalent of compiler 19.26 is toolset 14.26
- vcvars_ver = "14.{}{}".format(compiler_version[-1], compiler_update)
+ vs_version, vcvars_ver = _vcvars_versions(conanfile)
+ if vs_version is None:
+ return
vcvarsarch = _vcvars_arch(conanfile)
@@ -305,6 +278,41 @@ def _vcvars_path(version, vs_install_path):
return vcpath
+def _vcvars_versions(conanfile):
+ compiler = conanfile.settings.get_safe("compiler")
+ msvc_update = conanfile.conf.get("tools.microsoft:msvc_update")
+ if compiler == "clang":
+ # The vcvars only needed for LLVM/Clang and VS ClangCL, who define runtime
+ if not conanfile.settings.get_safe("compiler.runtime"):
+ # NMake Makefiles will need vcvars activated, for VS target, defined with runtime
+ return None, None
+ toolset_version = conanfile.settings.get_safe("compiler.runtime_version")
+ vs_version = {"v140": "14",
+ "v141": "15",
+ "v142": "16",
+ "v143": "17",
+ "v144": "17"}.get(toolset_version)
+ if vs_version is None:
+ raise ConanException("Visual Studio Runtime version (v140-v144) not defined")
+ vcvars_ver = {"v140": "14.0",
+ "v141": "14.1",
+ "v142": "14.2",
+ "v143": "14.3",
+ "v144": "14.4"}.get(toolset_version)
+ if vcvars_ver and msvc_update is not None:
+ vcvars_ver += f"{msvc_update}"
+ else:
+ vs_version = vs_ide_version(conanfile)
+ if int(vs_version) <= 14:
+ vcvars_ver = None
+ else:
+ compiler_version = str(conanfile.settings.compiler.version)
+ compiler_update = msvc_update or conanfile.settings.get_safe("compiler.update", "")
+ # The equivalent of compiler 19.26 is toolset 14.26
+ vcvars_ver = "14.{}{}".format(compiler_version[-1], compiler_update)
+ return vs_version, vcvars_ver
+
+
def _vcvars_arch(conanfile):
"""
Computes the vcvars command line architecture based on conanfile settings (host) and
diff --git a/conan/tools/qbs/__init__.py b/conan/tools/qbs/__init__.py
index 8567cdbf796..3100e450aa2 100644
--- a/conan/tools/qbs/__init__.py
+++ b/conan/tools/qbs/__init__.py
@@ -1,2 +1,3 @@
from conan.tools.qbs.qbs import Qbs
from conan.tools.qbs.qbsdeps import QbsDeps
+from conan.tools.qbs.qbsprofile import QbsProfile
diff --git a/conan/tools/qbs/common.py b/conan/tools/qbs/common.py
new file mode 100644
index 00000000000..dd45f434e8d
--- /dev/null
+++ b/conan/tools/qbs/common.py
@@ -0,0 +1,87 @@
+architecture_map = {
+ 'x86': 'x86',
+ 'x86_64': 'x86_64',
+ 'ppc32be': 'ppc',
+ 'ppc32': 'ppc',
+ 'ppc64le': 'ppc64',
+ 'ppc64': 'ppc64',
+ 'armv4': 'arm',
+ 'armv4i': 'arm',
+ 'armv5el': 'arm',
+ 'armv5hf': 'arm',
+ 'armv6': 'arm',
+ 'armv7': 'arm',
+ 'armv7hf': 'arm',
+ 'armv7s': 'arm',
+ 'armv7k': 'arm',
+ 'armv8': 'arm64',
+ 'armv8_32': 'arm64',
+ 'armv8.3': 'arm64',
+ 'sparc': 'sparc',
+ 'sparcv9': 'sparc64',
+ 'mips': 'mips',
+ 'mips64': 'mips64',
+ 'avr': 'avr',
+ 's390': 's390x',
+ 's390x': 's390x',
+ 'asm.js': None,
+ 'wasm': None,
+ 'sh4le': 'sh'
+}
+
+
+build_variant_map = {
+ 'Debug': 'debug',
+ 'Release': 'release',
+ 'RelWithDebInfo': 'profiling',
+ 'MinSizeRel': 'release'
+}
+
+
+optimization_map = {
+ 'MinSizeRel': 'small'
+}
+
+
+cxx_language_version_map = {
+ '98': 'c++98',
+ 'gnu98': 'c++98',
+ '11': 'c++11',
+ 'gnu11': 'c++11',
+ '14': 'c++14',
+ 'gnu14': 'c++14',
+ '17': 'c++17',
+ 'gnu17': 'c++17',
+ '20': 'c++20',
+ 'gnu20': 'c++20'
+}
+
+
+target_platform_map = {
+ 'Windows': 'windows',
+ 'WindowsStore': 'windows',
+ 'WindowsCE': 'windows',
+ 'Linux': 'linux',
+ 'Macos': 'macos',
+ 'Android': 'android',
+ 'iOS': 'ios',
+ 'watchOS': 'watchos',
+ 'tvOS': 'tvos',
+ 'visionOS': 'xros',
+ 'FreeBSD': 'freebsd',
+ 'SunOS': 'solaris',
+ 'AIX': 'aix',
+ 'Emscripten': None,
+ 'Arduino': 'none',
+ 'Neutrino': 'qnx',
+}
+
+
+runtime_library_map = {
+ 'static': 'static',
+ 'dynamic': 'dynamic',
+ 'MD': 'dynamic',
+ 'MT': 'static',
+ 'MDd': 'dynamic',
+ 'MTd': 'static',
+}
\ No newline at end of file
diff --git a/conan/tools/qbs/qbs.py b/conan/tools/qbs/qbs.py
index 8590e90a015..1673d8b6d22 100644
--- a/conan/tools/qbs/qbs.py
+++ b/conan/tools/qbs/qbs.py
@@ -1,9 +1,9 @@
import os
+import shutil
from conan.tools.build import build_jobs, cmd_args_to_string
from conan.errors import ConanException
-
def _configuration_dict_to_commandlist(name, config_dict):
command_list = ['config:%s' % name]
for key, value in config_dict.items():
@@ -57,11 +57,23 @@ def add_configuration(self, name, values):
"""
self._configuration[name] = values
+ def _qbs_settings_paths(self):
+ generators_folder = self._conanfile.generators_folder
+ qbs_settings_path = os.path.join(generators_folder, 'qbs_settings.txt')
+ if not os.path.exists(qbs_settings_path):
+ return None, None
+ return os.path.join(generators_folder, 'conan-qbs-settings-dir'), qbs_settings_path
+
def _get_common_arguments(self):
- return [
+ args = []
+ settings_dir, _ = self._qbs_settings_paths()
+ if settings_dir is not None:
+ args.extend(['--settings-dir', settings_dir])
+ args.extend([
'--build-directory', self._conanfile.build_folder,
'--file', self._project_file,
- ]
+ ])
+ return args
def resolve(self, parallel=True):
"""
@@ -70,6 +82,14 @@ def resolve(self, parallel=True):
"conan" module provider automatically adding dependencies to the project.
:param parallel: Whether to use multi-threaded resolving. Defaults to ``True``.
"""
+ generators_folder = self._conanfile.generators_folder
+ settings_dir, settings_path = self._qbs_settings_paths()
+ if settings_dir is not None:
+ shutil.rmtree(settings_dir, ignore_errors=True)
+ import_args = ['--settings-dir', settings_dir, '--import', settings_path]
+ import_cmd = 'qbs config %s' % cmd_args_to_string(import_args)
+ self._conanfile.run(import_cmd)
+
args = self._get_common_arguments()
if parallel:
@@ -80,7 +100,6 @@ def resolve(self, parallel=True):
if self.profile:
args.append('profile:%s' % self.profile)
- generators_folder = self._conanfile.generators_folder
if os.path.exists(os.path.join(generators_folder, 'conan-qbs-deps')):
args.append('moduleProviders.conan.installDirectory:' + generators_folder)
diff --git a/conan/tools/qbs/qbsprofile.py b/conan/tools/qbs/qbsprofile.py
new file mode 100644
index 00000000000..4cf619efdbd
--- /dev/null
+++ b/conan/tools/qbs/qbsprofile.py
@@ -0,0 +1,315 @@
+import os
+import shlex
+import shutil
+import platform
+import textwrap
+
+from jinja2 import Template
+from conan.internal import check_duplicated_generator
+from conan.errors import ConanException
+from conan.tools.env import VirtualBuildEnv
+from conan.tools.microsoft import msvs_toolset
+from conan.tools.microsoft.visual import vs_installation_path, _vcvars_path, _vcvars_versions
+from conan.tools.qbs import common
+from conans.util.files import save
+
+
+def _find_msvc(conanfile):
+ vs_install_path = conanfile.conf.get("tools.microsoft.msbuild:installation_path")
+ vs_version, vcvars_ver = _vcvars_versions(conanfile)
+ vs_path = vs_install_path or vs_installation_path(vs_version)
+ if vs_path is None or vs_version is None:
+ return None
+
+ vc_install_dir = os.path.join(vs_path, 'VC', 'Tools', 'MSVC')
+ if not os.path.exists(vc_install_dir):
+ return None
+ compiler_versions = [v for v in os.listdir(vc_install_dir) if v.startswith(vcvars_ver)]
+ compiler_versions.sort(reverse=True)
+
+ build_arch_map = {
+ 'x86': 'Hostx86',
+ 'x86_64': 'Hostx64',
+ 'armv6': 'arm',
+ 'armv7': 'arm',
+ 'armv8': 'arm64',
+ }
+ host_arch_map = {
+ 'x86': 'x86',
+ 'x86_64': 'x64',
+ 'armv6': 'arm',
+ 'armv7': 'arm',
+ 'armv8': 'arm64',
+ }
+ build_arch = build_arch_map.get(str(conanfile.settings_build.arch))
+
+ host_arch = host_arch_map.get(str(conanfile.settings.arch))
+
+ if not host_arch or not build_arch:
+ return None
+
+ def cl_path(version):
+ return os.path.join(vc_install_dir, version, 'bin', build_arch, host_arch, 'cl.exe')
+
+ compiler_paths = [cl_path(version) for version in compiler_versions]
+ compiler_paths = [p for p in compiler_paths if os.path.exists(p)]
+
+ if len(compiler_paths) == 0:
+ return None
+
+ return compiler_paths[0]
+
+
+def _find_clangcl(conanfile):
+ vs_install_path = conanfile.conf.get("tools.microsoft.msbuild:installation_path")
+ vs_version, _ = _vcvars_versions(conanfile)
+ vs_path = vs_install_path or vs_installation_path(vs_version)
+
+ compiler_path = os.path.join(vs_path, 'VC', 'Tools', 'Llvm', 'bin', 'clang-cl.exe')
+ vcvars_path = _vcvars_path(vs_version, vs_install_path)
+ if not os.path.exists(compiler_path):
+ return None
+ return compiler_path, vcvars_path
+
+
+class _LinkerFlagsParser:
+ def __init__(self, ld_flags):
+ self.driver_linker_flags = []
+ self.linker_flags = []
+
+ for item in ld_flags:
+ if item.startswith('-Wl'):
+ self.linker_flags.extend(item.split(',')[1:])
+ else:
+ self.driver_linker_flags.append(item)
+
+
+class QbsProfile:
+ """
+ Qbs profiles generator.
+
+ This class generates file with the toolchain information that can be imported by Qbs.
+ """
+
+ def __init__(self, conanfile, profile='conan', default_profile='conan'):
+ """
+ :param conanfile: The current recipe object. Always use ``self``.
+ :param profile: The name of the profile in settings. Defaults to ``"conan"``.
+ :param default_profile: The name of the default profile. Defaults to ``"conan"``.
+
+ """
+ self._conanfile = conanfile
+ self._profile = profile
+ self._default_profile = default_profile
+
+ self.extra_cflags = []
+ self.extra_cxxflags = []
+ self.extra_defines = []
+ self.extra_sharedlinkflags = []
+ self.extra_exelinkflags = []
+
+ self._build_env = VirtualBuildEnv(self._conanfile, auto_generate=True).vars()
+
+ @property
+ def filename(self):
+ """
+ The name of the generated file. Returns ``qbs_settings.txt``.
+ """
+ return 'qbs_settings.txt'
+
+ @property
+ def content(self):
+ """
+ Returns the content of the settings file as dict of Qbs properties.
+ """
+ result = self._toolchain_properties()
+ result.update(self._properties_from_settings())
+ result.update(self._properties_from_conf())
+ result.update(self._properties_from_options())
+ # result.update(self._properties_from_env(self._build_env))
+ return result
+
+ def render(self):
+ """
+ Returns the content of the settings file as string.
+ """
+ template = textwrap.dedent('''\
+ {%- for key, value in profile_values.items() %}
+ profiles.{{profile}}.{{ key }}:{{ value }}
+ {%- endfor %}
+ defaultProfile: {{default_profile}}
+ ''')
+ t = Template(template)
+ context = {
+ 'profile_values': self.content,
+ 'profile': self._profile,
+ 'default_profile': self._default_profile,
+ }
+ result = t.render(**context)
+ return result
+
+ def generate(self):
+ """
+ This method will save the generated files to the conanfile.generators_folder.
+
+ Generates the "qbs_settings.txt" file. This file contains Qbs settings such as toolchain
+ properties and can be imported using ``qbs config --import``.
+ """
+ check_duplicated_generator(self, self._conanfile)
+ self._check_for_compiler()
+ save(self.filename, self.render())
+
+ def _check_for_compiler(self):
+ compiler = self._conanfile.settings.get_safe('compiler')
+ if not compiler:
+ raise ConanException('Qbs: need compiler to be set in settings')
+
+ if compiler not in ['msvc', 'gcc', 'clang', 'apple-clang']:
+ raise ConanException(f'Qbs: compiler {compiler} not supported')
+
+ def _get_qbs_toolchain(self):
+ compiler = self._conanfile.settings.get_safe('compiler')
+ the_os = self._conanfile.settings.get_safe('os')
+ if the_os == 'Windows':
+ if compiler == 'msvc':
+ if msvs_toolset(self._conanfile) == 'ClangCL':
+ return 'clang-cl'
+ return 'msvc'
+ if compiler == 'gcc':
+ return 'mingw'
+ if compiler == 'clang':
+ return 'clang-cl'
+ raise ConanException('unknown windows compiler')
+ if compiler == 'apple-clang':
+ return 'xcode'
+ # todo: other compilers?
+ return compiler
+
+ def _default_compiler_names(self, toolchain):
+ if toolchain == 'msvc':
+ return 'cl', 'cl'
+ if toolchain == 'clang-cl':
+ return 'clang-cl', 'clang-cl'
+ if toolchain in ('gcc', 'mingw'):
+ return 'gcc', 'g++'
+ if toolchain in ('clang', 'xcode'):
+ return 'clang', 'clang++'
+
+ # what about other toolchains? IAR, Cosmic have a bunch of compilers based on arch
+ return toolchain, toolchain
+
+ def _find_exe(self, exe):
+ if platform.system() == 'Windows':
+ exe = exe + '.exe'
+ if os.path.isabs(exe):
+ return exe
+ paths = self._build_env.get("PATH", "")
+ for p in paths.split(os.pathsep):
+ path = os.path.join(p, exe)
+ if os.path.exists(path):
+ return path
+ return shutil.which(exe)
+
+ def _toolchain_properties(self):
+ toolchain = self._get_qbs_toolchain()
+ the_os = self._conanfile.settings.get_safe('os')
+ vcvars_path = None
+ compiler = None
+ if the_os == 'Windows' and toolchain == 'msvc':
+ compiler = _find_msvc(self._conanfile)
+ elif the_os == 'Windows' and toolchain == 'clang-cl':
+ compiler, vcvars_path = _find_clangcl(self._conanfile)
+ else:
+ # TODO: use CC also for msvc?
+ c_compiler_default, cxx_compiler_default = self._default_compiler_names(toolchain)
+ compilers_by_conf = self._conanfile.conf.get("tools.build:compiler_executables",
+ default={}, check_type=dict)
+ c_compiler = (
+ compilers_by_conf.get("c") or self._build_env.get("CC") or c_compiler_default)
+ c_compiler = self._find_exe(c_compiler)
+
+ cxx_compiler = (
+ compilers_by_conf.get("cpp") or self._build_env.get("CXX") or cxx_compiler_default)
+ cxx_compiler = self._find_exe(cxx_compiler)
+ compiler = cxx_compiler or c_compiler
+ if compiler is None:
+ raise ConanException('cannot find compiler')
+
+ result = {
+ 'qbs.toolchainType': toolchain,
+ 'cpp.compilerName': os.path.basename(compiler),
+ 'cpp.toolchainInstallPath': os.path.dirname(compiler).replace('\\', '/')
+ }
+ # GCC and friends also have separate props for compilers
+ gcc_toolchains = ['clang', 'gcc', 'llvm', 'mingw', 'qcc', 'xcode']
+ if toolchain in gcc_toolchains:
+ result['cpp.cCompilerName'] = os.path.basename(c_compiler)
+ result['cpp.cxxCompilerName'] = os.path.basename(cxx_compiler)
+ if vcvars_path:
+ result["cpp.vcvarsallPath"] = vcvars_path
+ return result
+
+ def _properties_from_settings(self):
+ result = {}
+
+ def map_qbs_property(key, qbs_property, value_map, fallback=None):
+ value = value_map.get(self._conanfile.settings.get_safe(key)) or fallback
+ if value is not None:
+ result[qbs_property] = value
+
+ map_qbs_property('arch', 'qbs.architecture', common.architecture_map)
+ map_qbs_property('os', 'qbs.targetPlatform', common.target_platform_map, "undefined")
+ map_qbs_property('build_type', 'qbs.buildVariant', common.build_variant_map)
+ map_qbs_property(
+ 'compiler.cppstd', 'cpp.cxxLanguageVersion', common.cxx_language_version_map)
+ map_qbs_property('compiler.runtime', 'cpp.runtimeLibrary', common.runtime_library_map)
+
+ return result
+
+ def _properties_from_options(self):
+ result = {}
+
+ def maybe_bool_str(b):
+ return None if b is None else str(b).lower()
+
+ fpic = maybe_bool_str(self._conanfile.options.get_safe('fPIC'))
+ if fpic:
+ result["cpp.positionIndependentCode"] = fpic
+
+ return result
+
+ def _properties_from_conf(self):
+ result = {}
+
+ def map_list_property(key, qbs_property, extra):
+ value = self._conanfile.conf.get(key, default=[], check_type=list)
+ value.extend(extra)
+ if len(value) > 0:
+ result[qbs_property] = value
+
+ map_list_property("tools.build:cflags", "cpp.cFlags", self.extra_cflags)
+ map_list_property("tools.build:cxxflags", "cpp.cxxFlags", self.extra_cxxflags)
+ map_list_property("tools.build:defines", "cpp.defines", self.extra_defines)
+
+ def ldflags():
+ conf = self._conanfile.conf
+ result = conf.get("tools.build:sharedlinkflags", default=[], check_type=list)
+ result.extend(self.extra_sharedlinkflags)
+ result.extend(conf.get("tools.build:exelinkflags", default=[], check_type=list))
+ result.extend(self.extra_exelinkflags)
+ linker_scripts = conf.get("tools.build:linker_scripts", default=[], check_type=list)
+ result.extend(["-T'" + linker_script + "'" for linker_script in linker_scripts])
+ return result
+
+ ld_flags = ldflags()
+ if len(ld_flags) > 0:
+ parser = _LinkerFlagsParser(ld_flags)
+ result['cpp.linkerFlags'] = parser.linker_flags
+ result['cpp.driverLinkerFlags'] = parser.driver_linker_flags
+
+ sysroot = self._conanfile.conf.get("tools.build:sysroot")
+ if sysroot is not None:
+ sysroot = sysroot.replace("\\", "/")
+ result['qbs.sysroot'] = sysroot
+
+ return result
| diff --git a/test/functional/toolchains/qbs/test_qbsprofile.py b/test/functional/toolchains/qbs/test_qbsprofile.py
new file mode 100644
index 00000000000..93841cafc37
--- /dev/null
+++ b/test/functional/toolchains/qbs/test_qbsprofile.py
@@ -0,0 +1,51 @@
+import textwrap
+import pytest
+
+from conan.test.utils.tools import TestClient
+from conan.test.assets.sources import gen_function_cpp
+
+
+@pytest.mark.tool("qbs")
+def test_qbsprofile():
+ client = TestClient()
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ from conan.tools.qbs import Qbs
+
+ class Recipe(ConanFile):
+ name = "app"
+ version = "1.2"
+ exports_sources = "*.cpp", "*.h", "*.qbs"
+ settings = "os", "compiler", "build_type", "arch"
+ generators = "QbsProfile"
+
+ def layout(self):
+ self.folders.generators = "generators"
+
+ def build(self):
+ qbs = Qbs(self)
+ qbs.resolve()
+ qbs.build()
+
+ def package(self):
+ qbs = Qbs(self)
+ qbs.install()
+ ''')
+
+ qbsfile = textwrap.dedent('''
+ CppApplication {
+ files: ["main.cpp"]
+ }
+ ''')
+
+ client.save({
+ "conanfile.py": conanfile,
+ "main.cpp": gen_function_cpp(name="main"),
+ "app.qbs": qbsfile,
+ }, clean_first=True)
+ client.run("create .")
+
+ assert "qbs resolve --settings-dir" in client.out
+ assert "qbs build --settings-dir" in client.out
+ assert "qbs install --settings-dir" in client.out
diff --git a/test/integration/toolchains/qbs/test_qbsprofile.py b/test/integration/toolchains/qbs/test_qbsprofile.py
new file mode 100644
index 00000000000..c3b9016962b
--- /dev/null
+++ b/test/integration/toolchains/qbs/test_qbsprofile.py
@@ -0,0 +1,318 @@
+import os
+import platform
+import textwrap
+import pytest
+
+from conan.test.utils.tools import TestClient
+from conans.util.files import load
+
+
+def exe_suffix():
+ return '.exe' if platform.system() == 'Windows' else ''
+
+
+COMPILER_MAP = {
+ 'gcc': ('gcc', 'g++'),
+ 'clang': ('clang', 'clang++')
+}
+
+
+@pytest.mark.parametrize('compiler, version, system', [
+ ('gcc', '13', 'Linux'),
+ ('clang', '15', 'Linux'),
+])
+def test_toolchain_from_path(compiler, version, system):
+ client = TestClient()
+ path = client.current_folder
+
+ profile = textwrap.dedent(f'''
+ [settings]
+ compiler={compiler}
+ compiler.version={version}
+ compiler.libcxx=libstdc++
+ os={system}
+ [buildenv]
+ PATH={path}
+ ''')
+
+ cc, cxx = COMPILER_MAP[compiler]
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ class Recipe(ConanFile):
+ settings = "compiler", "os"
+ name = "mylib"
+ version = "0.1"
+ ''')
+
+ client.save({cc + exe_suffix(): ''})
+ client.save({cxx + exe_suffix(): ''})
+ client.save({'profile': profile})
+ client.save({'conanfile.py': conanfile})
+ client.run('install . -pr:a=profile -g QbsProfile')
+
+ settings_path = os.path.join(client.current_folder, 'qbs_settings.txt')
+ assert os.path.exists(settings_path)
+
+ settings_content = load(settings_path)
+ assert f'qbs.toolchainType:{compiler}' in settings_content
+ toolchain_path = client.current_folder.replace('\\', '/')
+ assert f'cpp.toolchainInstallPath:{toolchain_path}' in settings_content
+ assert f'cpp.compilerName:{cxx}' in settings_content
+ assert f'cpp.cCompilerName:{cc}' in settings_content
+ assert f'cpp.cxxCompilerName:{cxx}' in settings_content
+
+
+@pytest.mark.parametrize('compiler, version, system, cc, cxx', [
+ ('gcc', '13', 'Linux', 'gcc', 'g++'),
+ ('clang', '15', 'Linux', 'clang', 'clang++'),
+])
+def test_toolchain_from_conf(compiler, version, system, cc, cxx):
+ profile = textwrap.dedent(f'''
+ [settings]
+ compiler={compiler}
+ compiler.version={version}
+ compiler.libcxx=libstdc++
+ os={system}
+ [conf]
+ tools.build:compiler_executables ={{"c": "/opt/bin/{cc}", "cpp": "/opt/bin/{cxx}"}}
+ ''')
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ class Recipe(ConanFile):
+ settings = "compiler", "os"
+ name = "mylib"
+ version = "0.1"
+ ''')
+
+ client = TestClient()
+ client.save({'profile': profile})
+ client.save({'conanfile.py': conanfile})
+ client.run('install . -pr:a=profile -g QbsProfile')
+
+ settings_path = os.path.join(client.current_folder, 'qbs_settings.txt')
+ assert os.path.exists(settings_path)
+
+ settings_content = load(settings_path)
+ assert f'qbs.toolchainType:{compiler}' in settings_content
+ assert 'cpp.toolchainInstallPath:/opt/bin' in settings_content
+ assert f'cpp.compilerName:{cxx}' in settings_content
+ assert f'cpp.cCompilerName:{cc}' in settings_content
+ assert f'cpp.cxxCompilerName:{cxx}' in settings_content
+
+
+@pytest.mark.parametrize('compiler, version, system, cc, cxx', [
+ ('gcc', '13', 'Linux', 'gcc', 'g++'),
+ ('clang', '15', 'Linux', 'clang', 'clang++'),
+])
+def test_toolchain_from_env(compiler, version, system, cc, cxx):
+ profile = textwrap.dedent(f'''
+ [settings]
+ compiler={compiler}
+ compiler.version={version}
+ compiler.libcxx=libstdc++
+ os={system}
+ [buildenv]
+ CC=/opt/bin/{cc}
+ CXX=/opt/bin/{cxx}
+ ''')
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ class Recipe(ConanFile):
+ settings = "compiler", "os"
+ name = "mylib"
+ version = "0.1"
+ ''')
+
+ client = TestClient()
+ client.save({'profile': profile})
+ client.save({'conanfile.py': conanfile})
+ client.run('install . -pr:a=profile -g QbsProfile')
+
+ settings_path = os.path.join(client.current_folder, 'qbs_settings.txt')
+ assert os.path.exists(settings_path)
+
+ settings_content = load(settings_path)
+ assert f'qbs.toolchainType:{compiler}' in settings_content
+ assert 'cpp.toolchainInstallPath:/opt/bin' in settings_content
+ assert f'cpp.compilerName:{cxx}' in settings_content
+ assert f'cpp.cCompilerName:{cc}' in settings_content
+ assert f'cpp.cxxCompilerName:{cxx}' in settings_content
+
+
+@pytest.mark.parametrize('system, compiler, version, build_type, arch, cppstd', [
+ ('Linux', 'gcc', '13', 'Release', 'x86_64', '17'),
+ ('Linux', 'gcc', '13', 'Debug', 'x86_64', '14'),
+ ('Linux', 'gcc', '13', 'Debug', 'x86', '20'),
+ ('Linux', 'gcc', '13', 'Release', 'avr', '11'),
+])
+def test_options_from_settings(system, compiler, version, build_type, arch, cppstd):
+ client = TestClient()
+
+ cc, cxx = COMPILER_MAP[compiler]
+
+ profile = textwrap.dedent(f'''
+ [settings]
+ arch={arch}
+ build_type={build_type}
+ compiler={compiler}
+ compiler.version={version}
+ compiler.libcxx=libstdc++
+ compiler.cppstd={cppstd}
+ os={system}
+ [conf]
+ tools.build:compiler_executables ={{"c": "/opt/bin/{cc}", "cpp": "/opt/bin/{cxx}"}}
+ ''')
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ class Recipe(ConanFile):
+ settings = "os", "compiler", "build_type", "arch"
+ name = "mylib"
+ version = "0.1"
+ ''')
+
+ client.save({'profile': profile})
+ client.save({'conanfile.py': conanfile})
+ client.run('install . -pr:a=profile -g QbsProfile')
+
+ settings_path = os.path.join(client.current_folder, 'qbs_settings.txt')
+ assert os.path.exists(settings_path)
+ settings_content = load(settings_path)
+
+ assert f'qbs.architecture:{arch}' in settings_content
+ build_variant = build_type.lower()
+ assert f'qbs.buildVariant:{build_variant}' in settings_content
+ target_platform = system.lower()
+ assert f'qbs.targetPlatform:{target_platform}' in settings_content
+ assert 'cpp.cxxLanguageVersion:c++' + cppstd in settings_content
+ # TODO: cpp.runtimeLibrary (MSVC only)
+
+
+def test_options_from_conf():
+ client = TestClient()
+
+ profile = textwrap.dedent('''
+ [settings]
+ arch=x86_64
+ build_type=Release
+ compiler=gcc
+ compiler.version=13
+ compiler.libcxx=libstdc++
+ compiler.cppstd=17
+ os=Linux
+ [conf]
+ tools.build:compiler_executables ={"c": "/opt/bin/gcc", "cpp": "/opt/bin/g++"}
+ tools.build:cflags=['-Dfoo', '-Dbar']
+ tools.build:cxxflags=['-Dfoo', '-Dbaz']
+ tools.build:sharedlinkflags=['-s']
+ tools.build:exelinkflags=['-Wl,-s']
+ ''')
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ class Recipe(ConanFile):
+ settings = "os", "compiler", "build_type", "arch"
+ name = "mylib"
+ version = "0.1"
+ ''')
+
+ client.save({'profile': profile})
+ client.save({'conanfile.py': conanfile})
+ client.run('install . -pr:a=profile -g QbsProfile')
+
+ settings_path = os.path.join(client.current_folder, 'qbs_settings.txt')
+ assert os.path.exists(settings_path)
+ settings_content = load(settings_path)
+
+ assert "cpp.cFlags:['-Dfoo', '-Dbar']" in settings_content
+ assert "cpp.cxxFlags:['-Dfoo', '-Dbaz']" in settings_content
+ assert "cpp.linkerFlags:['-s']" in settings_content
+ assert "cpp.driverLinkerFlags:['-s']" in settings_content
+
+
+def test_options_extra():
+ client = TestClient()
+
+ profile = textwrap.dedent('''
+ [settings]
+ arch=x86_64
+ build_type=Release
+ compiler=gcc
+ compiler.version=13
+ compiler.libcxx=libstdc++
+ compiler.cppstd=17
+ os=Linux
+ [conf]
+ tools.build:compiler_executables ={"c": "/opt/bin/gcc", "cpp": "/opt/bin/g++"}
+ ''')
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ from conan.tools.qbs import QbsProfile
+ class Recipe(ConanFile):
+ settings = "os", "compiler", "build_type", "arch"
+ name = "mylib"
+ version = "0.1"
+
+ def generate(self):
+ profile = QbsProfile(self)
+ profile.extra_cflags=['-Dfoo', '-Dbar']
+ profile.extra_cxxflags=['-Dfoo', '-Dbaz']
+ profile.extra_defines=['FOO', 'QUX']
+ profile.extra_sharedlinkflags=['-s']
+ profile.extra_exelinkflags=['-Wl,-s']
+ profile.generate()
+ ''')
+
+ client.save({'profile': profile})
+ client.save({'conanfile.py': conanfile})
+ client.run('install . -pr:a=profile')
+
+ settings_path = os.path.join(client.current_folder, 'qbs_settings.txt')
+ assert os.path.exists(settings_path)
+ settings_content = load(settings_path)
+
+ assert "cpp.cFlags:['-Dfoo', '-Dbar']" in settings_content
+ assert "cpp.cxxFlags:['-Dfoo', '-Dbaz']" in settings_content
+ assert "cpp.defines:['FOO', 'QUX']" in settings_content
+ assert "cpp.linkerFlags:['-s']" in settings_content
+ assert "cpp.driverLinkerFlags:['-s']" in settings_content
+
+
+def test_sysroot():
+ client = TestClient()
+
+ profile = textwrap.dedent('''
+ [settings]
+ arch=x86_64
+ build_type=Release
+ compiler=gcc
+ compiler.version=13
+ compiler.libcxx=libstdc++
+ compiler.cppstd=17
+ os=Linux
+ [conf]
+ tools.build:compiler_executables ={"c": "/opt/bin/gcc", "cpp": "/opt/bin/g++"}
+ tools.build:sysroot=\\opt\\usr\\local
+ ''')
+
+ conanfile = textwrap.dedent('''
+ from conan import ConanFile
+ class Recipe(ConanFile):
+ settings = "os", "compiler", "build_type", "arch"
+ name = "mylib"
+ version = "0.1"
+ ''')
+
+ client.save({'profile': profile})
+ client.save({'conanfile.py': conanfile})
+ client.run('install . -pr:a=profile -g QbsProfile')
+
+ settings_path = os.path.join(client.current_folder, 'qbs_settings.txt')
+ assert os.path.exists(settings_path)
+ settings_content = load(settings_path)
+
+ assert "qbs.sysroot:/opt/usr/local" in settings_content
| [
{
"components": [
{
"doc": "",
"lines": [
281,
313
],
"name": "_vcvars_versions",
"signature": "def _vcvars_versions(conanfile):",
"type": "function"
}
],
"file": "conan/tools/microsoft/visual.py"
},
{
"components": ... | [
"test/integration/toolchains/qbs/test_qbsprofile.py::test_toolchain_from_path[gcc-13-Linux]",
"test/integration/toolchains/qbs/test_qbsprofile.py::test_toolchain_from_path[clang-15-Linux]",
"test/integration/toolchains/qbs/test_qbsprofile.py::test_toolchain_from_conf[gcc-13-Linux-gcc-g++]",
"test/integration/... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Rework QbsProfile
The original QbsProfile class created a Qbs project file that should be imported in the project's source code. This was done that way for better compatibility with the QtCreator IDE in order for it to properly get compiler flags. This approach however, requires changes to the user project (namely, to include the generated profile file) which makes it harder to change package managers.
The new approach is to generate a qbs_settings.txt file that contains toolchain properties such as its type, install path and compiler flags and import using "qbs config --import" to the custom settings directory during resolve() stage.
Also, the old class used "qbs setup-toolchains" which main purpose is to search all toolchains in the system. This is an overkill when toolchain is known in advance since most toolchains only require 2 properties - toolchain type and its location. Thus, reimplement the required "qbs setup-toolchains" in python.
The new approach allows to test QbsProfile using integration tests which was not really possible earlier due to the dependency to the call to Qbs.
Fixes #10033
Changelog: Feature: Rework QbsProfile to support Conan 2.
Docs: https://github.com/conan-io/docs/pull/3825
- [x] Refer to the issue that supports this Pull Request.
- [ ] 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.
- [ ] 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/microsoft/visual.py]
(definition of _vcvars_versions:)
def _vcvars_versions(conanfile):
[end of new definitions in conan/tools/microsoft/visual.py]
[start of new definitions in conan/tools/qbs/qbs.py]
(definition of Qbs._qbs_settings_paths:)
def _qbs_settings_paths(self):
[end of new definitions in conan/tools/qbs/qbs.py]
[start of new definitions in conan/tools/qbs/qbsprofile.py]
(definition of _find_msvc:)
def _find_msvc(conanfile):
(definition of _find_msvc.cl_path:)
def cl_path(version):
(definition of _find_clangcl:)
def _find_clangcl(conanfile):
(definition of _LinkerFlagsParser:)
class _LinkerFlagsParser:
(definition of _LinkerFlagsParser.__init__:)
def __init__(self, ld_flags):
(definition of QbsProfile:)
class QbsProfile:
"""Qbs profiles generator.
This class generates file with the toolchain information that can be imported by Qbs."""
(definition of QbsProfile.__init__:)
def __init__(self, conanfile, profile='conan', default_profile='conan'):
""":param conanfile: The current recipe object. Always use ``self``.
:param profile: The name of the profile in settings. Defaults to ``"conan"``.
:param default_profile: The name of the default profile. Defaults to ``"conan"``."""
(definition of QbsProfile.filename:)
def filename(self):
"""The name of the generated file. Returns ``qbs_settings.txt``."""
(definition of QbsProfile.content:)
def content(self):
"""Returns the content of the settings file as dict of Qbs properties."""
(definition of QbsProfile.render:)
def render(self):
"""Returns the content of the settings file as string."""
(definition of QbsProfile.generate:)
def generate(self):
"""This method will save the generated files to the conanfile.generators_folder.
Generates the "qbs_settings.txt" file. This file contains Qbs settings such as toolchain
properties and can be imported using ``qbs config --import``."""
(definition of QbsProfile._check_for_compiler:)
def _check_for_compiler(self):
(definition of QbsProfile._get_qbs_toolchain:)
def _get_qbs_toolchain(self):
(definition of QbsProfile._default_compiler_names:)
def _default_compiler_names(self, toolchain):
(definition of QbsProfile._find_exe:)
def _find_exe(self, exe):
(definition of QbsProfile._toolchain_properties:)
def _toolchain_properties(self):
(definition of QbsProfile._properties_from_settings:)
def _properties_from_settings(self):
(definition of QbsProfile._properties_from_settings.map_qbs_property:)
def map_qbs_property(key, qbs_property, value_map, fallback=None):
(definition of QbsProfile._properties_from_options:)
def _properties_from_options(self):
(definition of QbsProfile._properties_from_options.maybe_bool_str:)
def maybe_bool_str(b):
(definition of QbsProfile._properties_from_conf:)
def _properties_from_conf(self):
(definition of QbsProfile._properties_from_conf.map_list_property:)
def map_list_property(key, qbs_property, extra):
(definition of QbsProfile._properties_from_conf.ldflags:)
def ldflags():
[end of new definitions in conan/tools/qbs/qbsprofile.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>
[feature] Make Qbs Generators ready for conan 2.0
The Qbs generators should be on par with CMake. Transparent integration should be possible.
For this multiple things have to get changed:
* [ ] QbsProfile generator should _not_ delete the settings directory
* [ ] in addition to create a file containing a profile the QbsProfile generator has to modify the config in the settings directory
* [ ] the Qbs build helper needs to detect and pass the settings directory
* [ ] a QbsDeps generator has to generate Modules for all required components
* [ ] the QbsDeps generator might generate a file containing additional information like environment variables
- [x] I've read the [CONTRIBUTING guide](https://github.com/conan-io/conan/blob/develop/.github/CONTRIBUTING.md).
----------
--------------------
</issues> | 4a5b19a75db9225316c8cb022a2dfb9705a2af34 | |
tobymao__sqlglot-3798 | 3,798 | tobymao/sqlglot | null | 44d650637d5d7a662b57ec1d8ca74dffe0f7ad73 | 2024-07-23T08:57:29Z | diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index a6409f862d..e08f8bae0e 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -1588,3 +1588,24 @@ def build_timestamp_from_parts(args: t.List) -> exp.Func:
def sha256_sql(self: Generator, expression: exp.SHA2) -> str:
return self.func(f"SHA{expression.text('length') or '256'}", expression.this)
+
+
+def sequence_sql(self: Generator, expression: exp.GenerateSeries):
+ start = expression.args["start"]
+ end = expression.args["end"]
+ step = expression.args.get("step")
+
+ if isinstance(start, exp.Cast):
+ target_type = start.to
+ elif isinstance(end, exp.Cast):
+ target_type = end.to
+ else:
+ target_type = None
+
+ if target_type and target_type.is_type("timestamp"):
+ if target_type is start.to:
+ end = exp.cast(end, target_type)
+ else:
+ start = exp.cast(start, target_type)
+
+ return self.func("SEQUENCE", start, end, step)
diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py
index 5120a1d8d8..fe7e2160a7 100644
--- a/sqlglot/dialects/hive.py
+++ b/sqlglot/dialects/hive.py
@@ -31,6 +31,7 @@
timestrtotime_sql,
unit_to_str,
var_map_sql,
+ sequence_sql,
)
from sqlglot.transforms import (
remove_unique_constraints,
@@ -310,6 +311,7 @@ class Parser(parser.Parser):
"REGEXP_EXTRACT": lambda args: exp.RegexpExtract(
this=seq_get(args, 0), expression=seq_get(args, 1), group=seq_get(args, 2)
),
+ "SEQUENCE": exp.GenerateSeries.from_arg_list,
"SIZE": exp.ArraySize.from_arg_list,
"SPLIT": exp.RegexpSplit.from_arg_list,
"STR_TO_MAP": lambda args: exp.StrToMap(
@@ -506,6 +508,7 @@ class Generator(generator.Generator):
exp.FileFormatProperty: lambda self,
e: f"STORED AS {self.sql(e, 'this') if isinstance(e.this, exp.InputOutputFormat) else e.name.upper()}",
exp.FromBase64: rename_func("UNBASE64"),
+ exp.GenerateSeries: sequence_sql,
exp.If: if_sql(),
exp.ILike: no_ilike_sql,
exp.IsNan: rename_func("ISNAN"),
diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py
index 27f050b43b..c8a3b00a6a 100644
--- a/sqlglot/dialects/presto.py
+++ b/sqlglot/dialects/presto.py
@@ -28,6 +28,7 @@
timestrtotime_sql,
ts_or_ds_add_cast,
unit_to_str,
+ sequence_sql,
)
from sqlglot.dialects.hive import Hive
from sqlglot.dialects.mysql import MySQL
@@ -435,6 +436,7 @@ class Generator(generator.Generator):
exp.FirstValue: _first_last_sql,
exp.FromTimeZone: lambda self,
e: f"WITH_TIMEZONE({self.sql(e, 'this')}, {self.sql(e, 'zone')}) AT TIME ZONE 'UTC'",
+ exp.GenerateSeries: sequence_sql,
exp.Group: transforms.preprocess([transforms.unalias_group]),
exp.GroupConcat: lambda self, e: self.func(
"ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator")
@@ -651,26 +653,6 @@ def transaction_sql(self, expression: exp.Transaction) -> str:
modes = f" {', '.join(modes)}" if modes else ""
return f"START TRANSACTION{modes}"
- def generateseries_sql(self, expression: exp.GenerateSeries) -> str:
- start = expression.args["start"]
- end = expression.args["end"]
- step = expression.args.get("step")
-
- if isinstance(start, exp.Cast):
- target_type = start.to
- elif isinstance(end, exp.Cast):
- target_type = end.to
- else:
- target_type = None
-
- if target_type and target_type.is_type("timestamp"):
- if target_type is start.to:
- end = exp.cast(end, target_type)
- else:
- start = exp.cast(start, target_type)
-
- return self.func("SEQUENCE", start, end, step)
-
def offset_limit_modifiers(
self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
) -> t.List[str]:
| diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py
index b89cd940ca..7aa279881f 100644
--- a/tests/dialects/test_postgres.py
+++ b/tests/dialects/test_postgres.py
@@ -565,24 +565,33 @@ def test_postgres(self):
"postgres": "GENERATE_SERIES(CAST('2019-01-01' AS TIMESTAMP), CURRENT_TIMESTAMP, INTERVAL '1 DAY')",
"presto": "SEQUENCE(CAST('2019-01-01' AS TIMESTAMP), CAST(CURRENT_TIMESTAMP AS TIMESTAMP), INTERVAL '1' DAY)",
"trino": "SEQUENCE(CAST('2019-01-01' AS TIMESTAMP), CAST(CURRENT_TIMESTAMP AS TIMESTAMP), INTERVAL '1' DAY)",
+ "hive": "SEQUENCE(CAST('2019-01-01' AS TIMESTAMP), CAST(CURRENT_TIMESTAMP() AS TIMESTAMP), INTERVAL '1' DAY)",
+ "spark2": "SEQUENCE(CAST('2019-01-01' AS TIMESTAMP), CAST(CURRENT_TIMESTAMP() AS TIMESTAMP), INTERVAL '1' DAY)",
+ "spark": "SEQUENCE(CAST('2019-01-01' AS TIMESTAMP), CAST(CURRENT_TIMESTAMP() AS TIMESTAMP), INTERVAL '1' DAY)",
+ "databricks": "SEQUENCE(CAST('2019-01-01' AS TIMESTAMP), CAST(CURRENT_TIMESTAMP() AS TIMESTAMP), INTERVAL '1' DAY)",
},
)
self.validate_all(
"GENERATE_SERIES(a, b)",
- write={
+ read={
"postgres": "GENERATE_SERIES(a, b)",
"presto": "SEQUENCE(a, b)",
"trino": "SEQUENCE(a, b)",
"tsql": "GENERATE_SERIES(a, b)",
+ "hive": "SEQUENCE(a, b)",
+ "spark2": "SEQUENCE(a, b)",
+ "spark": "SEQUENCE(a, b)",
+ "databricks": "SEQUENCE(a, b)",
},
- )
- self.validate_all(
- "GENERATE_SERIES(a, b)",
- read={
+ write={
"postgres": "GENERATE_SERIES(a, b)",
"presto": "SEQUENCE(a, b)",
"trino": "SEQUENCE(a, b)",
"tsql": "GENERATE_SERIES(a, b)",
+ "hive": "SEQUENCE(a, b)",
+ "spark2": "SEQUENCE(a, b)",
+ "spark": "SEQUENCE(a, b)",
+ "databricks": "SEQUENCE(a, b)",
},
)
self.validate_all(
| [] | [
"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_r... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(hive, spark, db): Support for exp.GenerateSeries
Fixes #3793
This PR adds support for the `SEQUENCE()` function across the Hive hierarchy. The generation is similar to the existing Presto/Trino, thus the code reuse.
Docs
--------
[Spark 2](https://spark.apache.org/docs/2.4.0/api/sql/index.html#sequence) | [Spark 3](https://spark.apache.org/docs/latest/api/sql/#sequence) | [Databricks](https://docs.databricks.com/en/sql/language-manual/functions/sequence.html)
----------
</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>
</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>
generate_series() is not transpiled to sequence() when going from duckdb to spark sql
**Fully reproducible code snippet**
```python
from sqlglot import transpile
# duckdb query
sql_query = """
WITH date_table AS (
SELECT
UNNEST(generate_series(DATE '2022-06-01', DATE '2024-01-01', INTERVAL '1 month')) AS date
)
select * from date_table
"""
spark_query = transpile(sql_query, read="duckdb", write="spark")[0]
spark = <your spark session>
spark.sql(spark_query).show()
```
This code throws an error because there is no `generate_series()` function in spark:
```
AnalysisException: [UNRESOLVED_ROUTINE] Cannot resolve function `GENERATE_SERIES` on search path [`system`.`builtin`, `system`.`session`, `spark_catalog`.`default`]
```
The output of transpile() is:
```
"WITH date_table AS (SELECT EXPLODE(GENERATE_SERIES(CAST('2022-06-01' AS DATE), CAST('2024-01-01' AS DATE), INTERVAL '1' MONTH)) AS date) SELECT * FROM date_table"
```
but it should be:
```
"WITH date_table AS (SELECT EXPLODE(SEQUENCE(CAST('2022-06-01' AS DATE), CAST('2024-01-01' AS DATE), INTERVAL '1' MONTH)) AS date) SELECT * FROM date_table"
```
I think the same case is when going from postgres -> spark.
---
A similar issue for trino was created before #1077
----------
--------------------
</issues> | ceb42fabad60312699e4b15936aeebac00e22e4d | |
pvlib__pvlib-python-2140 | 2,140 | pvlib/pvlib-python | 0.10 | 5e43be7a7a924f8161181a49e93053aa4a80f54d | 2024-07-20T20:42:11Z | diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index 15fd1d09b8..23b5f5bb6d 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -18,3 +18,4 @@ Spectrum
spectrum.spectral_factor_jrc
spectrum.sr_to_qe
spectrum.qe_to_sr
+ spectrum.average_photon_energy
diff --git a/docs/sphinx/source/whatsnew/v0.11.1.rst b/docs/sphinx/source/whatsnew/v0.11.1.rst
index 2839a0ff25..beaca6c466 100644
--- a/docs/sphinx/source/whatsnew/v0.11.1.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.1.rst
@@ -10,6 +10,9 @@ Deprecations
Enhancements
~~~~~~~~~~~~
+* Add new function to calculate the average photon energy,
+ :py:func:`pvlib.spectrum.average_photon_energy`.
+ (:issue:`2135`, :pull:`2140`)
* Add new losses function that accounts for non-uniform irradiance on bifacial
modules, :py:func:`pvlib.bifacial.power_mismatch_deline`.
(:issue:`2045`, :pull:`2046`)
diff --git a/pvlib/spectrum/__init__.py b/pvlib/spectrum/__init__.py
index 87deb86018..e282afc01f 100644
--- a/pvlib/spectrum/__init__.py
+++ b/pvlib/spectrum/__init__.py
@@ -10,6 +10,7 @@
from pvlib.spectrum.irradiance import ( # noqa: F401
get_am15g,
get_reference_spectra,
+ average_photon_energy,
)
from pvlib.spectrum.response import ( # noqa: F401
get_example_spectral_response,
diff --git a/pvlib/spectrum/irradiance.py b/pvlib/spectrum/irradiance.py
index 45846a0046..cb3e5e1ddb 100644
--- a/pvlib/spectrum/irradiance.py
+++ b/pvlib/spectrum/irradiance.py
@@ -9,6 +9,8 @@
import pandas as pd
from pathlib import Path
from functools import partial
+from scipy import constants
+from scipy.integrate import trapezoid
@deprecated(
@@ -176,3 +178,95 @@ def get_reference_spectra(wavelengths=None, standard="ASTM G173-03"):
)
return standard
+
+
+def average_photon_energy(spectra):
+ r"""
+ Calculate the average photon energy of one or more spectral irradiance
+ distributions.
+
+ Parameters
+ ----------
+ spectra : pandas.Series or pandas.DataFrame
+
+ Spectral irradiance, must be positive. [Wm⁻²nm⁻¹]
+
+ A single spectrum must be a :py:class:`pandas.Series` with wavelength
+ [nm] as the index, while multiple spectra must be rows in a
+ :py:class:`pandas.DataFrame` with column headers as wavelength [nm].
+
+ Returns
+ -------
+ ape : numeric or pandas.Series
+ Average Photon Energy [eV].
+ Note: returns ``np.nan`` in the case of all-zero spectral irradiance
+ input.
+
+ Notes
+ -----
+ The average photon energy (APE) is an index used to characterise the solar
+ spectrum. It has been used widely in the physics literature since the
+ 1900s, but its application for solar spectral irradiance characterisation
+ in the context of PV performance modelling was proposed in 2002 [1]_. The
+ APE is calculated based on the principle that a photon's energy is
+ inversely proportional to its wavelength:
+
+ .. math::
+
+ E_\gamma = \frac{hc}{\lambda},
+
+ where :math:`E_\gamma` is the energy of a photon with wavelength
+ :math:`\lambda`, :math:`h` is the Planck constant, and :math:`c` is the
+ speed of light. Therefore, the average energy of all photons within a
+ single spectral irradiance distribution provides an indication of the
+ general shape of the spectrum. A higher average photon energy
+ (shorter wavelength) indicates a blue-shifted spectrum, while a lower
+ average photon energy (longer wavelength) would indicate a red-shifted
+ spectrum. This value of the average photon energy can be calculated by
+ dividing the total energy in the spectrum by the total number of photons
+ in the spectrum as follows [1]_:
+
+ .. math::
+
+ \overline{E_\gamma} = \frac{1}{q} \cdot \frac{\int G(\lambda) \,
+ d\lambda}
+ {\int \Phi(\lambda) \, d\lambda}.
+
+ :math:`\Phi(\lambda)` is the photon flux density as a function of
+ wavelength, :math:`G(\lambda)` is the spectral irradiance, :math:`q` is the
+ elementary charge used here so that the average photon energy,
+ :math:`\overline{E_\gamma}`, is expressed in electronvolts (eV). The
+ integrals are computed over the full wavelength range of the ``spectra``
+ parameter.
+
+ References
+ ----------
+ .. [1] Jardine, C., et al., 2002, January. Influence of spectral effects on
+ the performance of multijunction amorphous silicon cells. In Proc.
+ Photovoltaic in Europe Conference (pp. 1756-1759).
+ """
+
+ if not isinstance(spectra, (pd.Series, pd.DataFrame)):
+ raise TypeError('`spectra` must be either a'
+ ' pandas Series or DataFrame')
+
+ if (spectra < 0).any().any():
+ raise ValueError('Spectral irradiance data must be positive')
+
+ hclambda = pd.Series((constants.h*constants.c)/(spectra.T.index*1e-9))
+ hclambda.index = spectra.T.index
+ pfd = spectra.div(hclambda)
+
+ def integrate(e):
+ return trapezoid(e, x=e.T.index, axis=-1)
+
+ int_spectra = integrate(spectra)
+ int_pfd = integrate(pfd)
+
+ with np.errstate(invalid='ignore'):
+ ape = (1/constants.elementary_charge)*int_spectra/int_pfd
+
+ if isinstance(spectra, pd.DataFrame):
+ ape = pd.Series(ape, index=spectra.index)
+
+ return ape
diff --git a/pvlib/spectrum/mismatch.py b/pvlib/spectrum/mismatch.py
index ab805130d0..3afc210e73 100644
--- a/pvlib/spectrum/mismatch.py
+++ b/pvlib/spectrum/mismatch.py
@@ -8,6 +8,7 @@
import numpy as np
import pandas as pd
from scipy.integrate import trapezoid
+
from warnings import warn
| diff --git a/pvlib/tests/spectrum/test_irradiance.py b/pvlib/tests/spectrum/test_irradiance.py
index dd6740a02f..63b0bc95d2 100644
--- a/pvlib/tests/spectrum/test_irradiance.py
+++ b/pvlib/tests/spectrum/test_irradiance.py
@@ -72,3 +72,67 @@ def test_get_reference_spectra_invalid_reference():
# test that an invalid reference identifier raises a ValueError
with pytest.raises(ValueError, match="Invalid standard identifier"):
spectrum.get_reference_spectra(standard="invalid")
+
+
+def test_average_photon_energy_series():
+ # test that the APE is calculated correctly with single spectrum
+ # series input
+
+ spectra = spectrum.get_reference_spectra()
+ spectra = spectra['global']
+ ape = spectrum.average_photon_energy(spectra)
+ expected = 1.45017
+ assert_allclose(ape, expected, rtol=1e-4)
+
+
+def test_average_photon_energy_dataframe():
+ # test that the APE is calculated correctly with multiple spectra
+ # dataframe input and that the output is a series
+
+ spectra = spectrum.get_reference_spectra().T
+ ape = spectrum.average_photon_energy(spectra)
+ expected = pd.Series([1.36848, 1.45017, 1.40885])
+ expected.index = spectra.index
+ assert_series_equal(ape, expected, rtol=1e-4)
+
+
+def test_average_photon_energy_invalid_type():
+ # test that spectrum argument is either a pandas Series or dataframe
+ spectra = 5
+ with pytest.raises(TypeError, match='must be either a pandas Series or'
+ ' DataFrame'):
+ spectrum.average_photon_energy(spectra)
+
+
+def test_average_photon_energy_neg_irr_series():
+ # test for handling of negative spectral irradiance values with a
+ # pandas Series input
+
+ spectra = spectrum.get_reference_spectra()['global']*-1
+ with pytest.raises(ValueError, match='must be positive'):
+ spectrum.average_photon_energy(spectra)
+
+
+def test_average_photon_energy_neg_irr_dataframe():
+ # test for handling of negative spectral irradiance values with a
+ # pandas DataFrame input
+
+ spectra = spectrum.get_reference_spectra().T*-1
+
+ with pytest.raises(ValueError, match='must be positive'):
+ spectrum.average_photon_energy(spectra)
+
+
+def test_average_photon_energy_zero_irr():
+ # test for handling of zero spectral irradiance values with
+ # pandas DataFrame and pandas Series input
+
+ spectra_df_zero = spectrum.get_reference_spectra().T
+ spectra_df_zero.iloc[1] = 0
+ spectra_series_zero = spectrum.get_reference_spectra()['global']*0
+ out_1 = spectrum.average_photon_energy(spectra_df_zero)
+ out_2 = spectrum.average_photon_energy(spectra_series_zero)
+ expected_1 = np.array([1.36848, np.nan, 1.40885])
+ expected_2 = np.nan
+ assert_allclose(out_1, expected_1, atol=1e-3)
+ assert_allclose(out_2, expected_2, atol=1e-3)
| diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index 15fd1d09b8..23b5f5bb6d 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -18,3 +18,4 @@ Spectrum
spectrum.spectral_factor_jrc
spectrum.sr_to_qe
spectrum.qe_to_sr
+ spectrum.average_photon_energy
diff --git a/docs/sphinx/source/whatsnew/v0.11.1.rst b/docs/sphinx/source/whatsnew/v0.11.1.rst
index 2839a0ff25..beaca6c466 100644
--- a/docs/sphinx/source/whatsnew/v0.11.1.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.1.rst
@@ -10,6 +10,9 @@ Deprecations
Enhancements
~~~~~~~~~~~~
+* Add new function to calculate the average photon energy,
+ :py:func:`pvlib.spectrum.average_photon_energy`.
+ (:issue:`2135`, :pull:`2140`)
* Add new losses function that accounts for non-uniform irradiance on bifacial
modules, :py:func:`pvlib.bifacial.power_mismatch_deline`.
(:issue:`2045`, :pull:`2046`)
| [
{
"components": [
{
"doc": "Calculate the average photon energy of one or more spectral irradiance\ndistributions.\n\nParameters\n----------\nspectra : pandas.Series or pandas.DataFrame\n\n Spectral irradiance, must be positive. [Wm⁻²nm⁻¹]\n\n A single spectrum must be a :py:class:`pandas.Se... | [
"pvlib/tests/spectrum/test_irradiance.py::test_average_photon_energy_series",
"pvlib/tests/spectrum/test_irradiance.py::test_average_photon_energy_dataframe",
"pvlib/tests/spectrum/test_irradiance.py::test_average_photon_energy_invalid_type",
"pvlib/tests/spectrum/test_irradiance.py::test_average_photon_energ... | [
"pvlib/tests/spectrum/test_irradiance.py::test_get_am15g",
"pvlib/tests/spectrum/test_irradiance.py::test_get_reference_spectra[ASTM",
"pvlib/tests/spectrum/test_irradiance.py::test_get_reference_spectra_custom_wavelengths",
"pvlib/tests/spectrum/test_irradiance.py::test_get_reference_spectra_invalid_referenc... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Create function to calculate average photon energy
- [X] Closes #2135
- [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.
docs: https://pvlib-python--2140.org.readthedocs.build/en/2140/reference/generated/pvlib.spectrum.average_photon_energy.html
----------
</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/spectrum/irradiance.py]
(definition of average_photon_energy:)
def average_photon_energy(spectra):
"""Calculate the average photon energy of one or more spectral irradiance
distributions.
Parameters
----------
spectra : pandas.Series or pandas.DataFrame
Spectral irradiance, must be positive. [Wm⁻²nm⁻¹]
A single spectrum must be a :py:class:`pandas.Series` with wavelength
[nm] as the index, while multiple spectra must be rows in a
:py:class:`pandas.DataFrame` with column headers as wavelength [nm].
Returns
-------
ape : numeric or pandas.Series
Average Photon Energy [eV].
Note: returns ``np.nan`` in the case of all-zero spectral irradiance
input.
Notes
-----
The average photon energy (APE) is an index used to characterise the solar
spectrum. It has been used widely in the physics literature since the
1900s, but its application for solar spectral irradiance characterisation
in the context of PV performance modelling was proposed in 2002 [1]_. The
APE is calculated based on the principle that a photon's energy is
inversely proportional to its wavelength:
.. math::
E_\gamma = \frac{hc}{\lambda},
where :math:`E_\gamma` is the energy of a photon with wavelength
:math:`\lambda`, :math:`h` is the Planck constant, and :math:`c` is the
speed of light. Therefore, the average energy of all photons within a
single spectral irradiance distribution provides an indication of the
general shape of the spectrum. A higher average photon energy
(shorter wavelength) indicates a blue-shifted spectrum, while a lower
average photon energy (longer wavelength) would indicate a red-shifted
spectrum. This value of the average photon energy can be calculated by
dividing the total energy in the spectrum by the total number of photons
in the spectrum as follows [1]_:
.. math::
\overline{E_\gamma} = \frac{1}{q} \cdot \frac{\int G(\lambda) \,
d\lambda}
{\int \Phi(\lambda) \, d\lambda}.
:math:`\Phi(\lambda)` is the photon flux density as a function of
wavelength, :math:`G(\lambda)` is the spectral irradiance, :math:`q` is the
elementary charge used here so that the average photon energy,
:math:`\overline{E_\gamma}`, is expressed in electronvolts (eV). The
integrals are computed over the full wavelength range of the ``spectra``
parameter.
References
----------
.. [1] Jardine, C., et al., 2002, January. Influence of spectral effects on
the performance of multijunction amorphous silicon cells. In Proc.
Photovoltaic in Europe Conference (pp. 1756-1759)."""
(definition of average_photon_energy.integrate:)
def integrate(e):
[end of new definitions in pvlib/spectrum/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>> | Here is the discussion in the issues of the pull request.
<issues>
Create calculate_avg_photon_energy function
I think a function to calculate the average photon energy (APE) using spectral irradiance data as an input would be a useful feature in pvlib.
**Additional context**
This would support PR #2126. While there are some discussions ongoing regarding that PR in Issue #2065, I think this may still be a useful feature in pvlib anyway regardless of the outcome of that PR.
The function would be in `pvlib/spectrum/spectral_irradiance.py` following the resolution of #2125 (I will create a PR for that soon issue soon)
I am wondering what people think about naming this function. Possibilities:
`calculate_avg_photon_energy`
`calculate_average_photon_energy`
`calculate_ape`
Switch "calculate" for "get" or "calc", or just omit this first word entirely?
Alternatives?
Any other thoughts on this?
----------
> or just omit this first word entirely?
+1 for `average_photon_energy`
> > or just omit this first word entirely?
>
> +1 for `average_photon_energy`
+2
--------------------
</issues> | 6af80da35a7c96059c534ee38be9123bcfc7f50f |
aws-cloudformation__cfn-lint-3523 | 3,523 | aws-cloudformation/cfn-lint | null | c6b81489c4cee413d458dcd264fe72f477a54aa0 | 2024-07-19T02:15:21Z | diff --git a/src/cfnlint/rules/resources/lmbd/PermissionSourceAccount.py b/src/cfnlint/rules/resources/lmbd/PermissionSourceAccount.py
new file mode 100644
index 0000000000..f1137c7ba7
--- /dev/null
+++ b/src/cfnlint/rules/resources/lmbd/PermissionSourceAccount.py
@@ -0,0 +1,99 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import regex as re
+
+from cfnlint.helpers import ensure_list, is_function
+from cfnlint.jsonschema import ValidationError, ValidationResult
+from cfnlint.jsonschema.protocols import Validator
+from cfnlint.rules.jsonschema import CfnLintKeyword
+
+
+class PermissionSourceAccount(CfnLintKeyword):
+
+ id = "W3663"
+ shortdesc = "Validate SourceAccount is required property"
+ description = (
+ "When configuration a Lambda permission with a SourceArn "
+ "that doesn't have an AccountId you should also specify "
+ "the SourceAccount"
+ )
+ source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html#cfn-lambda-permission-sourceaccount"
+ tags = ["resources", "lambda", "permission"]
+
+ def __init__(self):
+ super().__init__(
+ keywords=["Resources/AWS::Lambda::Permission/Properties"],
+ )
+
+ def _validate_sub_has_account_id(self, validator: Validator, value: Any) -> bool:
+ value = ensure_list(value)
+
+ if isinstance(value[0], str):
+ if re.search(r":(\d{12}|\${AWS::AccountId}):", value[0]):
+ return True
+
+ return False
+ return True
+
+ def _validate_is_gettatt_to_bucket(self, validator: Validator, value: Any) -> bool:
+ value = ensure_list(value)[0].split(".")[0]
+
+ resource = validator.context.resources[value]
+ if resource.type == "AWS::S3::Bucket":
+ return True
+ return False
+
+ def validate(
+ self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+ if not isinstance(instance, dict):
+ return
+
+ for scenario in validator.cfn.get_object_without_conditions(
+ instance, ["SourceArn", "SourceAccount"]
+ ):
+ if scenario.get("Scenario"):
+ scenario_validator = validator.evolve(
+ context=validator.context.evolve(
+ conditions=validator.context.conditions.evolve(
+ status=scenario.get("Scenario")
+ )
+ )
+ )
+ else:
+ scenario_validator = validator.evolve()
+
+ source_arn = scenario.get("Object").get("SourceArn")
+ source_account = scenario.get("Object").get("SourceAccount")
+ if not source_arn:
+ continue
+
+ if isinstance(source_arn, str):
+ if re.search(r":\d{12}:", source_arn):
+ continue
+
+ fn_k, fn_v = is_function(source_arn)
+ if fn_k is not None:
+ if fn_k == "Fn::Sub":
+ if self._validate_sub_has_account_id(scenario_validator, fn_v):
+ continue
+ elif fn_k == "Fn::GetAtt":
+ if not self._validate_is_gettatt_to_bucket(
+ scenario_validator, fn_v
+ ):
+ continue
+ else:
+ continue
+
+ if not source_account:
+ yield ValidationError(
+ "'SourceAccount' is a required property",
+ validator="required",
+ )
| diff --git a/test/unit/rules/resources/lmbd/test_permission_source_account.py b/test/unit/rules/resources/lmbd/test_permission_source_account.py
new file mode 100644
index 0000000000..3135a86ff1
--- /dev/null
+++ b/test/unit/rules/resources/lmbd/test_permission_source_account.py
@@ -0,0 +1,193 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.resources.lmbd.PermissionSourceAccount import PermissionSourceAccount
+
+
+@pytest.fixture(scope="module")
+def rule():
+ rule = PermissionSourceAccount()
+ yield rule
+
+
+@pytest.fixture
+def template():
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Conditions": {
+ "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
+ },
+ "Resources": {
+ "Bucket": {"Type": "AWS::S3::Bucket"},
+ "SQS": {"Type": "AWS::SQS::Queue"},
+ },
+ }
+
+
+@pytest.mark.parametrize(
+ "instance,expected",
+ [
+ (
+ {
+ "SourceArn": "arn:aws:s3:::bucket_name",
+ "SourceAccount": "123456789012",
+ },
+ [],
+ ),
+ (
+ {},
+ [],
+ ),
+ (
+ [],
+ [],
+ ),
+ (
+ {
+ "SourceArn": [],
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": "arn:aws:s3:::bucket_name",
+ },
+ [
+ ValidationError(
+ "'SourceAccount' is a required property",
+ validator="required",
+ )
+ ],
+ ),
+ (
+ {
+ "SourceArn": "arn:aws:sqs:us-east-1:123456789012:queue",
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {
+ "Fn::Sub": (
+ "arn:${AWS::Partition}:sqs:"
+ "${AWS::Region}:${AWS::AccountId}:queue"
+ )
+ },
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {"Fn::Sub": "arn:${AWS::Partition}:s3:::bucket"},
+ },
+ [
+ ValidationError(
+ "'SourceAccount' is a required property",
+ validator="required",
+ )
+ ],
+ ),
+ (
+ {
+ "SourceArn": {"Fn::Sub": [[], {}]},
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {"Fn::Sub": "arn:${AWS::Partition}:s3:::bucket"},
+ "SourceAccount": {"Ref": "AWS::AccountId"},
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {"Fn::GetAtt": ["Bucket", "Arn"]},
+ "SourceAccount": {"Ref": "AWS::AccountId"},
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {"Fn::GetAtt": ["Bucket", "Arn"]},
+ },
+ [
+ ValidationError(
+ "'SourceAccount' is a required property",
+ validator="required",
+ )
+ ],
+ ),
+ (
+ {
+ "SourceArn": {"Fn::GetAtt": ["SQS", "Arn"]},
+ "SourceAccount": {"Ref": "AWS::AccountId"},
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {"Fn::GetAtt": ["SQS", "Arn"]},
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {"Ref": "Foo"},
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {
+ "Fn::If": [
+ "IsUsEast1",
+ {"Fn::GetAtt": ["Bucket", "Arn"]},
+ {"Fn::GetAtt": ["SQS", "Arn"]},
+ ]
+ },
+ "SourceAccount": {
+ "Fn::If": [
+ "IsUsEast1",
+ {"Ref": "AWS::AccountId"},
+ {"Ref": "AWS::NoValue"},
+ ]
+ },
+ },
+ [],
+ ),
+ (
+ {
+ "SourceArn": {
+ "Fn::If": [
+ "IsUsEast1",
+ {"Fn::GetAtt": ["Bucket", "Arn"]},
+ {"Fn::GetAtt": ["SQS", "Arn"]},
+ ]
+ },
+ "SourceAccount": {
+ "Fn::If": [
+ "IsUsEast1",
+ {"Ref": "AWS::NoValue"},
+ {"Ref": "AWS::AccountId"},
+ ]
+ },
+ },
+ [
+ ValidationError(
+ "'SourceAccount' is a required property",
+ validator="required",
+ )
+ ],
+ ),
+ ],
+)
+def test_validate(instance, expected, rule, validator):
+ errs = list(rule.validate(validator, "", instance, {}))
+
+ assert errs == expected, f"Expected {expected} got {errs}"
| [
{
"components": [
{
"doc": "",
"lines": [
18,
98
],
"name": "PermissionSourceAccount",
"signature": "class PermissionSourceAccount(CfnLintKeyword):",
"type": "class"
},
{
"doc": "",
"lines": [
30,
... | [
"test/unit/rules/resources/lmbd/test_permission_source_account.py::test_validate[instance0-expected0]",
"test/unit/rules/resources/lmbd/test_permission_source_account.py::test_validate[instance1-expected1]",
"test/unit/rules/resources/lmbd/test_permission_source_account.py::test_validate[instance2-expected2]",
... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Create rule W3663 to validate lmbd permission account
*Issue #, if available:*
fix #2155
*Description of changes:*
- Create rule W3663 to validate lmbd permission account
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
----------
</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/cfnlint/rules/resources/lmbd/PermissionSourceAccount.py]
(definition of PermissionSourceAccount:)
class PermissionSourceAccount(CfnLintKeyword):
(definition of PermissionSourceAccount.__init__:)
def __init__(self):
(definition of PermissionSourceAccount._validate_sub_has_account_id:)
def _validate_sub_has_account_id(self, validator: Validator, value: Any) -> bool:
(definition of PermissionSourceAccount._validate_is_gettatt_to_bucket:)
def _validate_is_gettatt_to_bucket(self, validator: Validator, value: Any) -> bool:
(definition of PermissionSourceAccount.validate:)
def validate( self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/lmbd/PermissionSourceAccount.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>
[RFE] Warn when AWS::Lambda::Permission.SouceAccount is missing for S3 SourceArns
*cfn-lint version: (`cfn-lint --version`)*
>$ cfn-lint --version
>cfn-lint 0.54.3
*Feature Request - Warn when AWS::Lambda::Permission.SouceAccount is missing*
When setting a Lamba permission using the AWS::Lambda::Permission resource, if (and I believe only if) the SourceArn is an S3 Arn, it is almost always appropriate to specify a SourceAccount in addition to the SourceArn, since S3 Arns do not specify an account id.
I'm not sure how feasible it is, given that you would presumably need to be able to at least partially resolve whatever value / intrinsic are specified for SourceArn, but it would be useful if a warning could be raised when the SourceArn will resolve to an S3 Arn, but SourceAccount is missing.
If a SourceAccount is missing there are potential security issues with the deployed resources, especially if wildcards have been used in the SourceArn, and Security Hub will flag the permission as a Critical security issue.
The CloudFormation Docs say the following about SourceAccount:
> For Amazon S3, the ID of the account that owns the resource. Use this together with SourceArn to ensure that the resource is owned by the specified account. It is possible for an Amazon S3 bucket to be deleted by its owner and recreated by another account.
----------
At least according to the GUI the only option asking for an Account is when using S3.
From a template this is valid and the account is applied to the policy:
```yaml
Permission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt Function.Arn
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt Rule.Arn
SourceAccount: !Ref AWS::AccountId
```
This is also valid but should have the account specified since it isn't in the s3 arn.
```yaml
Permission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt Function.Arn
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt Bucket.Arn
```
Warning is the right level. My thoughts are that any ARN that doesn't have the account in it should have the source account added.
So maybe If `SourceArn` exists and has an ARN that doesn't include an account ID then warn to add the `SourceAccount`
--------------------
</issues> | 4b214774e419d871b7b498fb5256e2ed09393795 | |
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",
... | [
"[",
"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"... | [] | 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 | |
aws-cloudformation__cfn-lint-3513 | 3,513 | aws-cloudformation/cfn-lint | null | fbdd7fa73f13dd78e252b87c6c9fb9872bee7bae | 2024-07-17T18:20:09Z | diff --git a/src/cfnlint/conditions/conditions.py b/src/cfnlint/conditions/conditions.py
index da42ee8918..915932361c 100644
--- a/src/cfnlint/conditions/conditions.py
+++ b/src/cfnlint/conditions/conditions.py
@@ -240,6 +240,22 @@ def build_scenarios(
# formatting or just the wrong condition name
return
+ def _build_cfn_implies(self, scenarios) -> And:
+ conditions = []
+ for condition_name, opt in scenarios.items():
+ if opt:
+ conditions.append(
+ self._conditions[condition_name].build_true_cnf(self._solver_params)
+ )
+ else:
+ conditions.append(
+ self._conditions[condition_name].build_false_cnf(
+ self._solver_params
+ )
+ )
+
+ return And(*conditions)
+
def check_implies(self, scenarios: dict[str, bool], implies: str) -> bool:
"""Based on a bunch of scenario conditions and their Truth/False value
determine if implies condition is True any time the scenarios are satisfied
@@ -260,36 +276,18 @@ def check_implies(self, scenarios: dict[str, bool], implies: str) -> bool:
if not scenarios.get(implies, True):
return False
- conditions = []
- for condition_name, opt in scenarios.items():
- if opt:
- conditions.append(
- self._conditions[condition_name].build_true_cnf(
- self._solver_params
- )
- )
- else:
- conditions.append(
- self._conditions[condition_name].build_false_cnf(
- self._solver_params
- )
- )
-
+ and_condition = self._build_cfn_implies(scenarios)
+ cnf.add_prop(and_condition)
implies_condition = self._conditions[implies].build_true_cnf(
self._solver_params
)
+ cnf.add_prop(Not(Implies(and_condition, implies_condition)))
- and_condition = And(*conditions)
- cnf.add_prop(and_condition)
-
- # if the implies condition has to be true already then we don't
- # need to imply it
- if not scenarios.get(implies):
- cnf.add_prop(Not(Implies(and_condition, implies_condition)))
- if satisfiable(cnf):
- return True
+ results = satisfiable(cnf)
+ if results:
+ return False
- return False
+ return True
except KeyError:
# KeyError is because the listed condition doesn't exist because of bad
# formatting or just the wrong condition name
@@ -354,7 +352,8 @@ def satisfiable(
determine if the conditions are satisfied
Args:
- condition_names (list[str]): A list of condition names
+ condition_names (dict[str, bool]): A list of condition names with if
+ they are True or False
Returns:
bool: True if the conditions are satisfied
diff --git a/src/cfnlint/context/context.py b/src/cfnlint/context/context.py
index 7c35c57fb4..e70cb364ce 100644
--- a/src/cfnlint/context/context.py
+++ b/src/cfnlint/context/context.py
@@ -357,6 +357,7 @@ class Resource(_Ref):
"""
type: str = field(init=False)
+ condition: str | None = field(init=False, default=None)
resource: InitVar[Any]
def __post_init__(self, resource) -> None:
@@ -369,6 +370,11 @@ def __post_init__(self, resource) -> None:
if self.type.startswith("Custom::"):
self.type = "AWS::CloudFormation::CustomResource"
+ c = resource.get("Condition")
+ if not isinstance(t, str):
+ raise ValueError("Condition must be a string")
+ self.condition = c
+
@property
def get_atts(self, region: str = "us-east-1") -> AttributeDict:
return PROVIDER_SCHEMA_MANAGER.get_type_getatts(self.type, region)
diff --git a/src/cfnlint/rules/__init__.py b/src/cfnlint/rules/__init__.py
index 54c32fcbc5..976c6058c8 100644
--- a/src/cfnlint/rules/__init__.py
+++ b/src/cfnlint/rules/__init__.py
@@ -5,9 +5,7 @@
from cfnlint.rules._rule import CloudFormationLintRule, Match, RuleMatch
from cfnlint.rules._rules import Rules, RulesCollection
-from cfnlint.rules.jsonschema import (
- CfnLintJsonSchema,
- CfnLintJsonSchemaRegional,
- CfnLintKeyword,
- SchemaDetails,
-)
+from cfnlint.rules.jsonschema import CfnLintJsonSchema # type: ignore
+from cfnlint.rules.jsonschema import CfnLintJsonSchemaRegional # type: ignore
+from cfnlint.rules.jsonschema import CfnLintKeyword # type: ignore
+from cfnlint.rules.jsonschema import SchemaDetails
diff --git a/src/cfnlint/rules/helpers/__init__.py b/src/cfnlint/rules/helpers/__init__.py
new file mode 100644
index 0000000000..44d8de325f
--- /dev/null
+++ b/src/cfnlint/rules/helpers/__init__.py
@@ -0,0 +1,12 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from cfnlint.rules.helpers.get_resource_by_name import get_resource_by_name
+from cfnlint.rules.helpers.get_value_from_path import get_value_from_path
+
+__all__ = [
+ "get_value_from_path",
+ "get_resource_by_name",
+]
diff --git a/src/cfnlint/rules/helpers/get_resource_by_name.py b/src/cfnlint/rules/helpers/get_resource_by_name.py
new file mode 100644
index 0000000000..c8f9327900
--- /dev/null
+++ b/src/cfnlint/rules/helpers/get_resource_by_name.py
@@ -0,0 +1,50 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any, Sequence
+
+from cfnlint.context import Path
+from cfnlint.context.conditions import Unsatisfiable
+from cfnlint.jsonschema import Validator
+
+
+def get_resource_by_name(
+ validator: Validator, name: str, types: Sequence[str] | None = None
+) -> tuple[Any, Validator]:
+
+ resource = validator.context.resources.get(name)
+ if not resource:
+ return None, validator
+
+ if types and resource.type not in types:
+ return None, validator
+
+ if resource.condition:
+ try:
+ validator = validator.evolve(
+ context=validator.context.evolve(
+ conditions=validator.context.conditions.evolve(
+ {
+ resource.condition: True,
+ }
+ ),
+ )
+ )
+ except Unsatisfiable:
+ return None, validator
+
+ validator = validator.evolve(
+ context=validator.context.evolve(
+ path=Path(
+ path=deque(["Resources", name]),
+ cfn_path=deque(["Resources", resource.type]),
+ )
+ )
+ )
+
+ return validator.cfn.template.get("Resources", {}).get(name), validator
diff --git a/src/cfnlint/rules/helpers/get_value_from_path.py b/src/cfnlint/rules/helpers/get_value_from_path.py
new file mode 100644
index 0000000000..b5bcb61fad
--- /dev/null
+++ b/src/cfnlint/rules/helpers/get_value_from_path.py
@@ -0,0 +1,119 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any, Iterator
+
+from cfnlint.context.conditions import Unsatisfiable
+from cfnlint.helpers import is_function
+from cfnlint.jsonschema import Validator
+
+
+def _get_relationship_fn_if(
+ validator: Validator, key: Any, value: Any, path: deque[str | int]
+) -> Iterator[tuple[Any, Validator]]:
+ if not isinstance(value, list) or len(value) != 3:
+ return
+ condition = value[0]
+
+ for i in [1, 2]:
+ try:
+ if_validator = validator.evolve(
+ context=validator.context.evolve(
+ conditions=validator.context.conditions.evolve(
+ status={
+ condition: True if i == 1 else False,
+ },
+ ),
+ path=validator.context.path.descend(path=key).descend(path=i),
+ )
+ )
+ for r, v in get_value_from_path(
+ if_validator,
+ value[i],
+ path.copy(),
+ ):
+ yield r, v
+ except Unsatisfiable:
+ pass
+
+
+def _get_value_from_path_list(
+ validator: Validator, instance: Any, path: deque[str | int]
+) -> Iterator[tuple[Any, Validator]]:
+ for i, v in enumerate(instance):
+ for r, v in get_value_from_path(
+ validator.evolve(
+ context=validator.context.evolve(
+ path=validator.context.path.descend(path=i)
+ ),
+ ),
+ v,
+ path.copy(),
+ ):
+ yield r, v
+
+
+def get_value_from_path(
+ validator: Validator, instance: Any, path: deque[str | int]
+) -> Iterator[tuple[Any, Validator]]:
+ """
+ Retrieve a value from a nested dictionary or list using a path.
+
+ Args:
+ validator (Validator): The validator instance
+ data (Any): The dictionary or list to search.
+ path (deque[str | int]): The path to the value.
+
+ Returns:
+ The value at the specified path, or None if the key doesn't exist.
+
+ Examples:
+ >>> data = {'a': {'b': {'c': 3}}}
+ >>> get_value_from_path(data, ['a', 'b', 'c'])
+ 3
+ """
+
+ fn_k, fn_v = is_function(instance)
+ if fn_k is not None:
+ if fn_k == "Fn::If":
+ yield from _get_relationship_fn_if(validator, fn_k, fn_v, path)
+ elif fn_k == "Ref" and fn_v == "AWS::NoValue":
+ yield None, validator.evolve(
+ context=validator.context.evolve(
+ path=validator.context.path.descend(path=fn_k)
+ )
+ )
+ elif not path:
+ yield instance, validator
+ return
+
+ if not path:
+ yield instance, validator
+ return
+
+ key = path.popleft()
+ if isinstance(instance, list) and key == "*":
+ yield from _get_value_from_path_list(validator, instance, path)
+ return
+
+ if not isinstance(instance, dict):
+ yield None, validator
+ return
+
+ for r, v in get_value_from_path(
+ validator.evolve(
+ context=validator.context.evolve(
+ path=validator.context.path.descend(path=key)
+ )
+ ),
+ instance.get(key),
+ path.copy(),
+ ):
+ yield r, v
+
+ return
diff --git a/src/cfnlint/rules/jsonschema/__init__.py b/src/cfnlint/rules/jsonschema/__init__.py
index e1d5a72bee..60f460db6f 100644
--- a/src/cfnlint/rules/jsonschema/__init__.py
+++ b/src/cfnlint/rules/jsonschema/__init__.py
@@ -12,10 +12,10 @@
__all__ = [
"BaseJsonSchema",
- "CfnLintKeyword",
"CfnLintJsonSchema",
- "SchemaDetails",
"CfnLintJsonSchemaRegional",
+ "CfnLintKeyword",
"MaxProperties",
"PropertyNames",
+ "SchemaDetails",
]
diff --git a/src/cfnlint/rules/resources/ecs/ServiceDynamicPorts.py b/src/cfnlint/rules/resources/ecs/ServiceDynamicPorts.py
new file mode 100644
index 0000000000..00079aad94
--- /dev/null
+++ b/src/cfnlint/rules/resources/ecs/ServiceDynamicPorts.py
@@ -0,0 +1,215 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any, Iterator
+
+from cfnlint.helpers import ensure_list, is_function
+from cfnlint.jsonschema import ValidationError, ValidationResult
+from cfnlint.jsonschema.protocols import Validator
+from cfnlint.rules.helpers import get_resource_by_name, get_value_from_path
+from cfnlint.rules.jsonschema.CfnLintKeyword import CfnLintKeyword
+
+
+class ServiceDynamicPorts(CfnLintKeyword):
+ id = "E3049"
+ shortdesc = (
+ "Validate ECS tasks with dynamic host port have traffic-port ELB target groups"
+ )
+ description = (
+ "When using an ECS task definition of host port 0 and "
+ "associating that container to an ELB the target group "
+ "has to have a 'HealthCheckPort' of 'traffic-port'"
+ )
+ tags = ["resources"]
+
+ def __init__(self) -> None:
+ super().__init__(
+ keywords=["Resources/AWS::ECS::Service/Properties"],
+ )
+
+ def _filter_resource_name(self, instance: Any) -> str | None:
+ fn_k, fn_v = is_function(instance)
+ if fn_k is None:
+ return None
+ if fn_k == "Ref":
+ if isinstance(fn_v, str):
+ return fn_v
+ elif fn_k == "Fn::GetAtt":
+ name = ensure_list(fn_v)[0].split(".")[0]
+ if isinstance(name, str):
+ return name
+ return None
+
+ def _get_service_lb_containers(
+ self, validator: Validator, instance: Any
+ ) -> Iterator[tuple[str, str, str, Validator]]:
+ for load_balancer, load_balancer_validator in get_value_from_path(
+ validator,
+ instance,
+ path=deque(["LoadBalancers", "*"]),
+ ):
+ for name, name_validator in get_value_from_path(
+ load_balancer_validator,
+ load_balancer,
+ path=deque(["ContainerName"]),
+ ):
+ if name is None or not isinstance(name, str):
+ continue
+ for port, port_validator in get_value_from_path(
+ name_validator,
+ load_balancer,
+ path=deque(["ContainerPort"]),
+ ):
+ if port is None or not isinstance(port, (str, int)):
+ continue
+ for tg, tg_validator in get_value_from_path(
+ port_validator,
+ load_balancer,
+ path=deque(["TargetGroupArn"]),
+ ):
+ tg = self._filter_resource_name(tg)
+ if tg is None:
+ continue
+ yield name, port, tg, tg_validator
+
+ def _get_service_properties(
+ self, validator: Validator, instance: Any
+ ) -> Iterator[tuple[str, str, str, str, Validator]]:
+ for task_definition_id, task_definition_validator in get_value_from_path(
+ validator, instance, deque(["TaskDefinition"])
+ ):
+ task_definition_resource_name = self._filter_resource_name(
+ task_definition_id
+ )
+ if task_definition_resource_name is None:
+ continue
+ for (
+ container_name,
+ container_port,
+ target_group,
+ lb_validator,
+ ) in self._get_service_lb_containers(task_definition_validator, instance):
+ yield (
+ task_definition_resource_name,
+ container_name,
+ container_port,
+ target_group,
+ lb_validator,
+ )
+
+ def _get_target_group_properties(
+ self, validator: Validator, resource_name: Any
+ ) -> Iterator[tuple[str | int | None, Validator]]:
+ target_group, target_group_validator = get_resource_by_name(
+ validator, resource_name, ["AWS::ElasticLoadBalancingV2::TargetGroup"]
+ )
+ if not target_group:
+ return
+
+ for port, port_validator in get_value_from_path(
+ target_group_validator,
+ target_group,
+ path=deque(["Properties", "HealthCheckPort"]),
+ ):
+ if port is None:
+ yield port, port_validator
+ continue
+
+ if not isinstance(port, (str, int)):
+ continue
+ yield port, port_validator
+
+ def _get_task_containers(
+ self,
+ validator: Validator,
+ resource_name: str,
+ container_name: str,
+ container_port: str | int,
+ ) -> Iterator[Validator]:
+ task_def, task_def_validator = get_resource_by_name(
+ validator, resource_name, ["AWS::ECS::TaskDefinition"]
+ )
+
+ if not task_def:
+ return
+
+ for container, container_validator in get_value_from_path(
+ task_def_validator,
+ task_def,
+ path=deque(["Properties", "ContainerDefinitions", "*"]),
+ ):
+ for name, name_validator in get_value_from_path(
+ container_validator,
+ container,
+ path=deque(["Name"]),
+ ):
+ if not isinstance(name, str):
+ continue
+ if name == container_name:
+ for host_port_validator in self._filter_port_mappings(
+ name_validator, container, container_port
+ ):
+ yield host_port_validator
+
+ def _filter_port_mappings(
+ self, validator: Validator, instance: Any, port: Any
+ ) -> Iterator[Validator]:
+ for port_mapping, port_mapping_validator in get_value_from_path(
+ validator,
+ instance,
+ path=deque(["PortMappings", "*"]),
+ ):
+ for container_port, container_port_validator in get_value_from_path(
+ port_mapping_validator,
+ port_mapping,
+ path=deque(["ContainerPort"]),
+ ):
+ if not isinstance(container_port, (str, int)):
+ continue
+ if str(port) == str(container_port):
+ for _, host_part_validator in get_value_from_path(
+ container_port_validator,
+ port_mapping,
+ path=deque(["HostPort"]),
+ ):
+ yield host_part_validator
+
+ def validate(
+ self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+
+ for (
+ task_definition_resource_name,
+ lb_container_name,
+ lb_container_port,
+ lb_target_group,
+ lb_service_validator,
+ ) in self._get_service_properties(validator, instance):
+ for container_validator in self._get_task_containers(
+ lb_service_validator,
+ task_definition_resource_name,
+ lb_container_name,
+ lb_container_port,
+ ):
+ for (
+ health_check_port,
+ health_check_port_validator,
+ ) in self._get_target_group_properties(
+ container_validator, lb_target_group
+ ):
+ if health_check_port != "traffic-port":
+ err_validator = "const"
+ if health_check_port is None:
+ err_validator = "required"
+ yield ValidationError(
+ "When using an ECS task definition of host port 0 and "
+ "associating that container to an ELB the target group "
+ "has to have a 'HealthCheckPort' of 'traffic-port'",
+ path_override=health_check_port_validator.context.path.path,
+ validator=err_validator,
+ )
diff --git a/src/cfnlint/rules/resources/ectwo/InstanceImageId.py b/src/cfnlint/rules/resources/ectwo/InstanceImageId.py
new file mode 100644
index 0000000000..7219d3c10b
--- /dev/null
+++ b/src/cfnlint/rules/resources/ectwo/InstanceImageId.py
@@ -0,0 +1,127 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any, Iterator
+
+from cfnlint.helpers import ensure_list, is_function
+from cfnlint.jsonschema import ValidationError, ValidationResult, Validator
+from cfnlint.rules.helpers import get_resource_by_name, get_value_from_path
+from cfnlint.rules.jsonschema.CfnLintKeyword import CfnLintKeyword
+
+
+class InstanceImageId(CfnLintKeyword):
+ id = "E3673"
+ shortdesc = "Validate if an ImageId is required"
+ description = (
+ "Validate if an ImageID is required. It can be "
+ "required if the associated LaunchTemplate doesn't specify "
+ "an ImageID"
+ )
+ tags = ["resources", "ec2"]
+
+ def __init__(self) -> None:
+ super().__init__(
+ keywords=[
+ "Resources/AWS::EC2::Instance/Properties",
+ ],
+ )
+
+ def _get_related_launch_template(
+ self, validator: Validator, instance: Any
+ ) -> Iterator[tuple[Any, Validator]]:
+
+ for launch_template, launch_template_validator in get_value_from_path(
+ validator, instance, deque(["LaunchTemplate"])
+ ):
+ if not launch_template:
+ continue
+ for id, id_validator in get_value_from_path(
+ launch_template_validator, launch_template, deque(["LaunchTemplateId"])
+ ):
+ if id is None:
+ for name, name_validator in get_value_from_path(
+ id_validator,
+ launch_template,
+ deque(["LaunchTemplateName"]),
+ ):
+ yield name, name_validator
+ yield id, id_validator
+
+ def validate(
+ self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+
+ for (
+ instance_image_id,
+ instance_image_id_validator,
+ ) in get_value_from_path(
+ validator,
+ instance,
+ path=deque(["ImageId"]),
+ ):
+ if instance_image_id:
+ continue
+
+ launch_templates = list(
+ self._get_related_launch_template(instance_image_id_validator, instance)
+ )
+
+ if not launch_templates:
+ yield ValidationError(
+ "'ImageId' is a required property",
+ path_override=instance_image_id_validator.context.path.path,
+ )
+ continue
+
+ for (
+ instance_launch_template,
+ instance_launch_template_validator,
+ ) in launch_templates:
+ fn_k, fn_v = is_function(instance_launch_template)
+
+ # if its not a function we can't tell from a string
+ # if the image ID is there or not
+ if fn_k is None:
+ continue
+
+ launch_template, launch_template_validator = None, None
+ if fn_k == "Ref":
+ if fn_v in instance_launch_template_validator.context.parameters:
+ continue
+ elif fn_v in instance_launch_template_validator.context.resources:
+ launch_template, launch_template_validator = (
+ get_resource_by_name(
+ instance_launch_template_validator,
+ fn_v,
+ ["AWS::EC2::LaunchTemplate"],
+ )
+ )
+ else:
+ continue
+ elif fn_k == "Fn::GetAtt":
+ launch_template, launch_template_validator = get_resource_by_name(
+ instance_launch_template_validator,
+ ensure_list(fn_v)[0].split(".")[0],
+ ["AWS::EC2::LaunchTemplate"],
+ )
+ else:
+ continue
+
+ for (
+ launch_template_image_id,
+ _,
+ ) in get_value_from_path(
+ launch_template_validator,
+ launch_template or {},
+ path=deque(["Properties", "LaunchTemplateData", "ImageId"]),
+ ):
+ if launch_template_image_id is None and instance_image_id is None:
+ yield ValidationError(
+ "'ImageId' is a required property",
+ path_override=instance_image_id_validator.context.path.path,
+ )
diff --git a/src/cfnlint/template/template.py b/src/cfnlint/template/template.py
index 65767f350e..d14b562910 100644
--- a/src/cfnlint/template/template.py
+++ b/src/cfnlint/template/template.py
@@ -824,7 +824,7 @@ def is_resource_available(self, path: Path, resource: str) -> list[dict[str, boo
return results
scenario[condition_name] = list(condition_bool)[0]
- if self.conditions.check_implies(scenario, resource_condition):
+ if not self.conditions.check_implies(scenario, resource_condition):
return [{**{resource_condition: False}, **scenario}]
# if resource condition isn't available then the resource is available
| diff --git a/test/unit/module/cfn_yaml/test_yaml.py b/test/unit/module/cfn_yaml/test_yaml.py
index b4668a19b8..4e5b5afc80 100644
--- a/test/unit/module/cfn_yaml/test_yaml.py
+++ b/test/unit/module/cfn_yaml/test_yaml.py
@@ -27,7 +27,7 @@ def setUp(self):
},
"generic_bad": {
"filename": "test/fixtures/templates/bad/generic.yaml",
- "failures": 34,
+ "failures": 35,
},
}
diff --git a/test/unit/module/conditions/test_conditions.py b/test/unit/module/conditions/test_conditions.py
index 4012a69fa2..d3d248652c 100644
--- a/test/unit/module/conditions/test_conditions.py
+++ b/test/unit/module/conditions/test_conditions.py
@@ -30,7 +30,14 @@ def test_bad_condition_definition(self):
len(cfn.conditions._conditions), 1
) # would be 2 but IsProd fails
# test coverage for KeyErrors in the following functions
- self.assertTrue(cfn.conditions.check_implies({"Test": True}, "IsUsEast1"))
+ self.assertTrue(
+ cfn.conditions.check_implies(
+ {
+ "Test": True,
+ },
+ "IsUsEast1",
+ )
+ )
self.assertEqual(
list(cfn.conditions.build_scenarios({"IsProd": None, "IsUsEast1": None})),
[],
@@ -105,7 +112,7 @@ def test_check_always_true_or_false(self):
cfn = Template("", template)
self.assertEqual(len(cfn.conditions._conditions), 2)
# test coverage for KeyErrors in the following functions
- self.assertFalse(cfn.conditions.check_implies({"IsTrue": True}, "IsFalse"))
+ self.assertTrue(cfn.conditions.check_implies({"IsTrue": True}, "IsFalse"))
def test_check_never_false(self):
"""With allowed values two conditions can not both be false"""
diff --git a/test/unit/module/test_rules_collections.py b/test/unit/module/test_rules_collections.py
index 3c2cd97917..edde4715a7 100644
--- a/test/unit/module/test_rules_collections.py
+++ b/test/unit/module/test_rules_collections.py
@@ -69,7 +69,7 @@ def test_fail_run(self):
filename = "test/fixtures/templates/bad/generic.yaml"
template = cfnlint.decode.cfn_yaml.load(filename)
cfn = Template(filename, template, ["us-east-1"])
- expected_err_count = 37
+ expected_err_count = 38
matches = []
matches.extend(self.rules.run(filename, cfn))
assert (
diff --git a/test/unit/rules/helpers/__init__.py b/test/unit/rules/helpers/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/test/unit/rules/helpers/test_get_resource_by_name.py b/test/unit/rules/helpers/test_get_resource_by_name.py
new file mode 100644
index 0000000000..408b902efd
--- /dev/null
+++ b/test/unit/rules/helpers/test_get_resource_by_name.py
@@ -0,0 +1,169 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+
+import pytest
+
+from cfnlint.rules.helpers import get_resource_by_name
+
+
+@pytest.fixture
+def template():
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Parameters": {
+ "ImageId": {
+ "Type": "String",
+ }
+ },
+ "Conditions": {
+ "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
+ "IsNotUsEast1": {"Fn::Not": [{"Condition": "IsUsEast1"}]},
+ "IsImageId": {"Fn::Not": {"Fn::Equals": [{"Ref": "ImageId"}, ""]}},
+ },
+ "Resources": {
+ "Foo": {"Type": "AWS::S3::Bucket"},
+ "Bar": {"Type": "AWS::S3::Bucket", "Condition": "IsUsEast1"},
+ "FooBar": {"Type": "AWS::S3::Bucket", "Condition": "IsNotUsEast1"},
+ "BadShape": [],
+ "NoType": {},
+ },
+ }
+
+
+@pytest.mark.parametrize(
+ "name,resource_name,types,status,expected",
+ [
+ (
+ "Standard get",
+ "Foo",
+ None,
+ {},
+ ({"Type": "AWS::S3::Bucket"}, {}, deque(["Resources", "Foo"])),
+ ),
+ (
+ "Doesn't exist",
+ "Foo2",
+ None,
+ {},
+ (
+ None,
+ {},
+ deque([]),
+ ),
+ ),
+ (
+ "The destination isn't a dict",
+ "BadShape",
+ None,
+ {},
+ (
+ None,
+ {},
+ deque([]),
+ ),
+ ),
+ (
+ "The destination doesn't have type",
+ "NoType",
+ None,
+ {},
+ (
+ None,
+ {},
+ deque([]),
+ ),
+ ),
+ (
+ "Get a valid resource with a filter",
+ "Foo",
+ ["AWS::S3::Bucket"],
+ {},
+ (
+ {
+ "Type": "AWS::S3::Bucket",
+ },
+ {},
+ deque(["Resources", "Foo"]),
+ ),
+ ),
+ (
+ "No result when type filters it out",
+ "Foo",
+ ["AWS::EC2::Instance"],
+ {},
+ (
+ None,
+ {},
+ deque([]),
+ ),
+ ),
+ (
+ "Get a resource with a condition",
+ "Bar",
+ None,
+ {},
+ (
+ {"Type": "AWS::S3::Bucket", "Condition": "IsUsEast1"},
+ {"IsUsEast1": True},
+ deque(["Resources", "Bar"]),
+ ),
+ ),
+ (
+ "No resource when conditions don't align 1",
+ "Bar",
+ None,
+ {"IsUsEast1": False},
+ (
+ None,
+ {"IsUsEast1": False},
+ deque([]),
+ ),
+ ),
+ (
+ "No resource when conditions don't align 2",
+ "FooBar",
+ None,
+ {"IsUsEast1": True},
+ (
+ None,
+ {"IsUsEast1": True},
+ deque([]),
+ ),
+ ),
+ (
+ "Unrelated conditions return full results",
+ "Bar",
+ None,
+ {"IsImageId": False},
+ (
+ {"Type": "AWS::S3::Bucket", "Condition": "IsUsEast1"},
+ {"IsUsEast1": True, "IsImageId": False},
+ deque(["Resources", "Bar"]),
+ ),
+ ),
+ ],
+)
+def test_get_resource_by_name(name, resource_name, types, status, expected, validator):
+ validator = validator.evolve(
+ context=validator.context.evolve(
+ conditions=validator.context.conditions.evolve(
+ status=status,
+ ),
+ ),
+ )
+
+ result = get_resource_by_name(validator, resource_name, types)
+
+ assert result[0] == expected[0], f"Test {name!r} got {result[0]!r}"
+ assert (
+ result[1].context.conditions.status == expected[1]
+ ), f"Test {name!r} got {result[1].context.conditions.status!r}"
+ assert (
+ result[1].context.path.path == expected[2]
+ ), f"Test {name!r} got {result[1].context.path.path!r}"
diff --git a/test/unit/rules/helpers/test_get_value_from_path.py b/test/unit/rules/helpers/test_get_value_from_path.py
new file mode 100644
index 0000000000..bdcf72672c
--- /dev/null
+++ b/test/unit/rules/helpers/test_get_value_from_path.py
@@ -0,0 +1,194 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+
+import pytest
+
+from cfnlint.rules.helpers import get_value_from_path
+
+
+@pytest.fixture
+def template():
+ return {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Parameters": {
+ "ImageId": {
+ "Type": "AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>",
+ "Default": "/aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2", # noqa: E501
+ }
+ },
+ "Conditions": {
+ "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
+ "IsNotUsEast1": {"Fn::Not": [{"Condition": "IsUsEast1"}]},
+ "IsImageIdSpecified": {
+ "Fn::Not": [{"Fn::Equals": [{"Ref": "ImageId"}, ""]}]
+ },
+ },
+ "Resources": {},
+ }
+
+
+@pytest.mark.parametrize(
+ "name,instance,v_path,status,expected",
+ [
+ (
+ "No path",
+ {"Foo": "Bar"},
+ deque([]),
+ {},
+ [
+ ({"Foo": "Bar"}, {}, deque([])),
+ ],
+ ),
+ (
+ "Small path with out it being found",
+ {"Foo": "Bar"},
+ deque(["Bar"]),
+ {},
+ [
+ (None, {}, deque(["Bar"])),
+ ],
+ ),
+ (
+ "Bad path returns an empty value with list",
+ {"Foo": [{"Bar": "One"}]},
+ deque(["Foo", "Bar"]),
+ {},
+ [
+ (
+ None,
+ {},
+ deque(["Foo"]),
+ )
+ ],
+ ),
+ (
+ "Bad path returns an empty value with string",
+ {"Foo": "Misvalued"},
+ deque(["Foo", "Bar"]),
+ {},
+ [
+ (
+ None,
+ {},
+ deque(["Foo"]),
+ )
+ ],
+ ),
+ (
+ "With a path and no conditions",
+ {"Foo": {"Bar": True}},
+ deque(["Foo", "Bar"]),
+ {},
+ [
+ (True, {}, deque(["Foo", "Bar"])),
+ ],
+ ),
+ (
+ "With a list item",
+ {"Foo": [{"Bar": "One"}, {"Bar": "Two"}, {"NoValue": "Three"}]},
+ deque(["Foo", "*", "Bar"]),
+ {},
+ [
+ ("One", {}, deque(["Foo", 0, "Bar"])),
+ ("Two", {}, deque(["Foo", 1, "Bar"])),
+ (None, {}, deque(["Foo", 2, "Bar"])),
+ ],
+ ),
+ (
+ "With a basic condition",
+ {
+ "Foo": {
+ "Fn::If": [
+ "IsUsEast1",
+ {"Bar": "One"},
+ {"Bar": "Two"},
+ ]
+ }
+ },
+ deque(["Foo", "Bar"]),
+ {},
+ [
+ ("One", {"IsUsEast1": True}, deque(["Foo", "Fn::If", 1, "Bar"])),
+ ("Two", {"IsUsEast1": False}, deque(["Foo", "Fn::If", 2, "Bar"])),
+ ],
+ ),
+ (
+ "With a basic condition and a current status",
+ {
+ "Foo": {
+ "Fn::If": [
+ "IsUsEast1",
+ {"Bar": "One"},
+ {"Bar": "Two"},
+ ]
+ }
+ },
+ deque(["Foo", "Bar"]),
+ {"IsUsEast1": True},
+ [
+ ("One", {"IsUsEast1": True}, deque(["Foo", "Fn::If", 1, "Bar"])),
+ ],
+ ),
+ (
+ "With a basic condition and a current status on a related condition",
+ {
+ "Foo": {
+ "Fn::If": [
+ "IsUsEast1",
+ {"Bar": "One"},
+ {"Bar": "Two"},
+ ]
+ }
+ },
+ deque(["Foo", "Bar"]),
+ {"IsNotUsEast1": True},
+ [
+ (
+ "Two",
+ {"IsUsEast1": False, "IsNotUsEast1": True},
+ deque(["Foo", "Fn::If", 2, "Bar"]),
+ ),
+ ],
+ ),
+ (
+ "With a random function in the way",
+ {"Foo": {"Fn::FindInMap": ["A", "B", "C"]}},
+ deque(["Foo", "*", "Bar"]),
+ {},
+ [],
+ ),
+ (
+ "With a ref at the desination",
+ {"Foo": {"Ref": "Bar"}},
+ deque(["Foo"]),
+ {},
+ [({"Ref": "Bar"}, {}, deque(["Foo"]))],
+ ),
+ ],
+)
+def test_get_value_from_path(name, instance, v_path, status, expected, validator):
+ validator = validator.evolve(
+ context=validator.context.evolve(
+ conditions=validator.context.conditions.evolve(
+ status=status,
+ ),
+ ),
+ )
+
+ results = list(get_value_from_path(validator, instance, v_path))
+
+ assert len(results) == len(expected), f"Test {name!r} got {len(results)!r}"
+ for result, exp in zip(results, expected):
+ assert result[0] == exp[0], f"Test {name!r} got {result[0]!r}"
+ assert (
+ result[1].context.conditions.status == exp[1]
+ ), f"Test {name!r} got {result[1].context.conditions.status!r}"
+ assert (
+ result[1].context.path.path == exp[2]
+ ), f"Test {name!r} got {result[1].context.path.path!r}"
diff --git a/test/unit/rules/resources/ec2/test_instance_image_id.py b/test/unit/rules/resources/ec2/test_instance_image_id.py
new file mode 100644
index 0000000000..845d5876ae
--- /dev/null
+++ b/test/unit/rules/resources/ec2/test_instance_image_id.py
@@ -0,0 +1,293 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from collections import deque
+
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.resources.ectwo.InstanceImageId import InstanceImageId
+
+
+@pytest.fixture(scope="module")
+def rule():
+ rule = InstanceImageId()
+ yield rule
+
+
+@pytest.mark.parametrize(
+ "name,template,instance,path,expected",
+ [
+ (
+ "Valid with no ImageId in LaunchTemplate",
+ {
+ "Resources": {
+ "LaunchTemplate": {
+ "Type": "AWS::EC2::LaunchTemplate",
+ "Properties": {
+ "LaunchTemplateName": "a-template",
+ "LaunchTemplateData": {
+ "Monitoring": {"Enabled": True},
+ },
+ },
+ },
+ }
+ },
+ {
+ "LaunchTemplate": {
+ "LaunchTemplateId": {
+ "Fn::GetAtt": [
+ "LaunchTemplate",
+ "LaunchTemplateId",
+ ],
+ }
+ },
+ "ImageId": "ami-12345678",
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [],
+ ),
+ (
+ "Valid with no ImageId and a string launch template",
+ {
+ "Resources": {},
+ },
+ {
+ "LaunchTemplate": {"LaunchTemplateId": "foo"},
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [],
+ ),
+ (
+ "Valid with no ImageId and a parameter",
+ {
+ "Parameters": {
+ "LaunchTemplateId": {
+ "Type": "String",
+ }
+ },
+ "Resources": {},
+ },
+ {
+ "LaunchTemplate": {"LaunchTemplateId": {"Ref": "LaunchTemplateId"}},
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [],
+ ),
+ (
+ "Valid with no ImageId a random ref",
+ {
+ "Resources": {},
+ },
+ {
+ "LaunchTemplate": {"LaunchTemplateName": {"Ref": "AWS::StackName"}},
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [],
+ ),
+ (
+ "Valid with no ImageId and another function",
+ {
+ "Parameters": {
+ "LaunchTemplateId": {
+ "Type": "String",
+ }
+ },
+ "Resources": {},
+ },
+ {
+ "LaunchTemplate": {
+ "LaunchTemplateId": {"Fn::FindInMap": ["One", "Two", "Three"]}
+ },
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [],
+ ),
+ (
+ "Valid with ImageId in LaunchTemplate",
+ {
+ "Resources": {
+ "LaunchTemplate": {
+ "Type": "AWS::EC2::LaunchTemplate",
+ "Properties": {
+ "LaunchTemplateName": "a-template",
+ "LaunchTemplateData": {
+ "Monitoring": {"Enabled": True},
+ "ImageId": "ami-12345678",
+ },
+ },
+ },
+ }
+ },
+ {
+ "LaunchTemplate": {
+ "LaunchTemplateId": {
+ "Fn::GetAtt": [
+ "LaunchTemplate",
+ "LaunchTemplateId",
+ ],
+ }
+ },
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [],
+ ),
+ (
+ "Valid with ImageId in LaunchTemplate using Name",
+ {
+ "Resources": {
+ "LaunchTemplate": {
+ "Type": "AWS::EC2::LaunchTemplate",
+ "Properties": {
+ "LaunchTemplateName": "a-template",
+ "LaunchTemplateData": {
+ "Monitoring": {"Enabled": True},
+ "ImageId": "ami-12345678",
+ },
+ },
+ },
+ }
+ },
+ {
+ "LaunchTemplate": {
+ "LaunchTemplateName": {
+ "Ref": "LaunchTemplate",
+ }
+ },
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [],
+ ),
+ (
+ "Invalid with no relationship",
+ {},
+ {},
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [
+ ValidationError(
+ "'ImageId' is a required property",
+ path_override=deque(
+ ["Resources", "Instance", "Properties", "ImageId"]
+ ),
+ )
+ ],
+ ),
+ (
+ "Invalid with no ImageId in LaunchTemplate",
+ {
+ "Resources": {
+ "LaunchTemplate": {
+ "Type": "AWS::EC2::LaunchTemplate",
+ "Properties": {
+ "LaunchTemplateName": "a-template",
+ "LaunchTemplateData": {
+ "Monitoring": {"Enabled": True},
+ },
+ },
+ },
+ }
+ },
+ {
+ "LaunchTemplate": {
+ "LaunchTemplateId": {
+ "Fn::GetAtt": [
+ "LaunchTemplate",
+ "LaunchTemplateId",
+ ],
+ }
+ },
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [
+ ValidationError(
+ "'ImageId' is a required property",
+ path_override=deque(
+ ["Resources", "Instance", "Properties", "ImageId"]
+ ),
+ )
+ ],
+ ),
+ (
+ "Invalid with no ImageId in LaunchTemplate with condition",
+ {
+ "Conditions": {
+ "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}
+ },
+ "Resources": {
+ "LaunchTemplate": {
+ "Type": "AWS::EC2::LaunchTemplate",
+ "Properties": {
+ "LaunchTemplateName": "a-template",
+ "LaunchTemplateData": {
+ "Monitoring": {"Enabled": True},
+ },
+ },
+ },
+ },
+ },
+ {
+ "LaunchTemplate": {
+ "LaunchTemplateId": {
+ "Fn::GetAtt": [
+ "LaunchTemplate",
+ "LaunchTemplateId",
+ ],
+ }
+ },
+ "ImageId": {
+ "Fn::If": [
+ "IsUsEast1",
+ "ami-12345678",
+ {"Ref": "AWS::NoValue"},
+ ]
+ },
+ },
+ {
+ "path": ["Resources", "Instance", "Properties"],
+ },
+ [
+ ValidationError(
+ "'ImageId' is a required property",
+ path_override=deque(
+ [
+ "Resources",
+ "Instance",
+ "Properties",
+ "ImageId",
+ "Fn::If",
+ 2,
+ "Ref",
+ ]
+ ),
+ )
+ ],
+ ),
+ ],
+ indirect=["template", "path"],
+)
+def test_validate(name, instance, expected, rule, validator):
+ errs = list(rule.validate(validator, "", instance, {}))
+
+ assert (
+ errs == expected
+ ), f"Expected test {name!r} to have {expected!r} but got {errs!r}"
diff --git a/test/unit/rules/resources/ecs/test_service_dynamic_ports.py b/test/unit/rules/resources/ecs/test_service_dynamic_ports.py
new file mode 100644
index 0000000000..86ea9f71e9
--- /dev/null
+++ b/test/unit/rules/resources/ecs/test_service_dynamic_ports.py
@@ -0,0 +1,563 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+
+import jsonpatch
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.helpers import get_value_from_path
+from cfnlint.rules.resources.ecs.ServiceDynamicPorts import ServiceDynamicPorts
+
+
+@pytest.fixture
+def rule():
+ rule = ServiceDynamicPorts()
+ yield rule
+
+
+_task_definition = {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "ContainerDefinitions": [
+ {
+ "Name": "my-container",
+ "Image": "my-image",
+ "PortMappings": [
+ {
+ "ContainerPort": 8080,
+ "HostPort": 0,
+ }
+ ],
+ }
+ ],
+ },
+}
+
+_target_group = {
+ "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
+ "Properties": {
+ "HealthCheckPort": "traffic-port",
+ "Port": 8080,
+ "Protocol": "HTTP",
+ },
+}
+
+_service = {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "TaskDefinition": {"Ref": "TaskDefinition"},
+ "LoadBalancers": [
+ {
+ "TargetGroupArn": {"Ref": "TargetGroup"},
+ "ContainerName": "my-container",
+ "ContainerPort": 8080,
+ }
+ ],
+ },
+}
+
+
+@pytest.mark.parametrize(
+ "template,start_path,expected",
+ [
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": dict(_target_group),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": "3000",
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {
+ "MyHealthCheckPort": {
+ "Type": "String",
+ },
+ },
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": {"Ref": "MyHealthCheckPort"},
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {
+ "MyContainerPort": {
+ "Type": "String",
+ },
+ },
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": (
+ "/Properties/ContainerDefinitions"
+ "/0/PortMappings/0/ContainerPort"
+ ),
+ "value": {"Ref": "MyContainerPort"},
+ },
+ ],
+ ),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": "3000",
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {
+ "MyTaskDefinition": {
+ "Type": "String",
+ },
+ },
+ "Resources": {
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": "3000",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Ref": "MyTaskDefinition"},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": "3000",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Fn::FindInMap": ["A", "B", "C"]},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": "3000",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Fn::GetAtt": ["TaskDefinition", "Arn"]},
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ (
+ "When using an ECS task definition of host "
+ "port 0 and associating that container to "
+ "an ELB the target group has to have a "
+ "'HealthCheckPort' of 'traffic-port'"
+ ),
+ validator="const",
+ path_override=deque(
+ ["Resources", "TargetGroup", "Properties", "HealthCheckPort"]
+ ),
+ )
+ ],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": "3000",
+ },
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/TaskDefinition",
+ "value": {"Ref": []},
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/HealthCheckPort",
+ "value": "3000",
+ },
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ (
+ "When using an ECS task definition of host "
+ "port 0 and associating that container to "
+ "an ELB the target group has to have a "
+ "'HealthCheckPort' of 'traffic-port'"
+ ),
+ validator="const",
+ path_override=deque(
+ ["Resources", "TargetGroup", "Properties", "HealthCheckPort"]
+ ),
+ )
+ ],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [
+ ValidationError(
+ (
+ "When using an ECS task definition of host "
+ "port 0 and associating that container to "
+ "an ELB the target group has to have a "
+ "'HealthCheckPort' of 'traffic-port'"
+ ),
+ validator="required",
+ path_override=deque(
+ ["Resources", "TargetGroup", "Properties", "HealthCheckPort"]
+ ),
+ )
+ ],
+ ),
+ (
+ {
+ "Parameters": {
+ "MyContainerName": {
+ "Type": "String",
+ }
+ },
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/ContainerDefinitions/0/Name",
+ "value": {"Ref": "MyContainerName"},
+ },
+ ],
+ ),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": dict(_service),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {
+ "MyContainerName": {
+ "Type": "String",
+ }
+ },
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/LoadBalancers/0/ContainerName",
+ "value": {"Ref": "MyContainerName"},
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Parameters": {
+ "MyContainerName": {
+ "Type": "String",
+ }
+ },
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/LoadBalancers/0/ContainerName",
+ },
+ ],
+ ),
+ },
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/LoadBalancers/0/ContainerPort",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": dict(_task_definition),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": jsonpatch.apply_patch(
+ dict(_service),
+ [
+ {
+ "op": "remove",
+ "path": "/Properties/LoadBalancers/0/TargetGroupArn",
+ },
+ ],
+ ),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": "/Properties/ContainerDefinitions/0/Name",
+ "value": "Changed",
+ },
+ ],
+ ),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ (
+ {
+ "Resources": {
+ "TaskDefinition": jsonpatch.apply_patch(
+ dict(_task_definition),
+ [
+ {
+ "op": "replace",
+ "path": (
+ "/Properties/ContainerDefinitions/"
+ "0/PortMappings/0/ContainerPort"
+ ),
+ "value": "30",
+ },
+ ],
+ ),
+ "TargetGroup": jsonpatch.apply_patch(
+ dict(_target_group),
+ [
+ {"op": "remove", "path": "/Properties/HealthCheckPort"},
+ ],
+ ),
+ "Service": dict(_service),
+ }
+ },
+ deque(["Resources", "Service", "Properties"]),
+ [],
+ ),
+ ],
+ indirect=["template"],
+)
+def test_validate(template, start_path, expected, rule, validator):
+ for instance, instance_validator in get_value_from_path(
+ validator, template, start_path
+ ):
+ errs = list(rule.validate(instance_validator, "", instance, {}))
+ assert errs == expected, f"Expected {expected} got {errs}"
| [
{
"components": [
{
"doc": "",
"lines": [
243,
257
],
"name": "Conditions._build_cfn_implies",
"signature": "def _build_cfn_implies(self, scenarios) -> And:",
"type": "function"
}
],
"file": "src/cfnlint/conditions/condition... | [
"test/unit/module/cfn_yaml/test_yaml.py::TestYamlParse::test_map_failure",
"test/unit/module/cfn_yaml/test_yaml.py::TestYamlParse::test_success_parse",
"test/unit/module/cfn_yaml/test_yaml.py::TestYamlParse::test_success_parse_stdin",
"test/unit/module/conditions/test_conditions.py::TestConditions::test_bad_c... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Create relationship rule and validate ImageId on Instance
*Issue #, if available:*
fix #3473
fix #817
*Description of changes:*
- Create relationship rule and validate ImageId on Instance
- Create rule E3673 to validate ImageId being required on an instance
- Create rule E3049 to validate ECS Task/Service and LB target configuration with dynamic host ports
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
----------
</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/cfnlint/conditions/conditions.py]
(definition of Conditions._build_cfn_implies:)
def _build_cfn_implies(self, scenarios) -> And:
[end of new definitions in src/cfnlint/conditions/conditions.py]
[start of new definitions in src/cfnlint/rules/helpers/get_resource_by_name.py]
(definition of get_resource_by_name:)
def get_resource_by_name( validator: Validator, name: str, types: Sequence[str] | None = None ) -> tuple[Any, Validator]:
[end of new definitions in src/cfnlint/rules/helpers/get_resource_by_name.py]
[start of new definitions in src/cfnlint/rules/helpers/get_value_from_path.py]
(definition of _get_relationship_fn_if:)
def _get_relationship_fn_if( validator: Validator, key: Any, value: Any, path: deque[str | int] ) -> Iterator[tuple[Any, Validator]]:
(definition of _get_value_from_path_list:)
def _get_value_from_path_list( validator: Validator, instance: Any, path: deque[str | int] ) -> Iterator[tuple[Any, Validator]]:
(definition of get_value_from_path:)
def get_value_from_path( validator: Validator, instance: Any, path: deque[str | int] ) -> Iterator[tuple[Any, Validator]]:
"""Retrieve a value from a nested dictionary or list using a path.
Args:
validator (Validator): The validator instance
data (Any): The dictionary or list to search.
path (deque[str | int]): The path to the value.
Returns:
The value at the specified path, or None if the key doesn't exist.
Examples:
>>> data = {'a': {'b': {'c': 3}}}
>>> get_value_from_path(data, ['a', 'b', 'c'])
3"""
[end of new definitions in src/cfnlint/rules/helpers/get_value_from_path.py]
[start of new definitions in src/cfnlint/rules/resources/ecs/ServiceDynamicPorts.py]
(definition of ServiceDynamicPorts:)
class ServiceDynamicPorts(CfnLintKeyword):
(definition of ServiceDynamicPorts.__init__:)
def __init__(self) -> None:
(definition of ServiceDynamicPorts._filter_resource_name:)
def _filter_resource_name(self, instance: Any) -> str | None:
(definition of ServiceDynamicPorts._get_service_lb_containers:)
def _get_service_lb_containers( self, validator: Validator, instance: Any ) -> Iterator[tuple[str, str, str, Validator]]:
(definition of ServiceDynamicPorts._get_service_properties:)
def _get_service_properties( self, validator: Validator, instance: Any ) -> Iterator[tuple[str, str, str, str, Validator]]:
(definition of ServiceDynamicPorts._get_target_group_properties:)
def _get_target_group_properties( self, validator: Validator, resource_name: Any ) -> Iterator[tuple[str | int | None, Validator]]:
(definition of ServiceDynamicPorts._get_task_containers:)
def _get_task_containers( self, validator: Validator, resource_name: str, container_name: str, container_port: str | int, ) -> Iterator[Validator]:
(definition of ServiceDynamicPorts._filter_port_mappings:)
def _filter_port_mappings( self, validator: Validator, instance: Any, port: Any ) -> Iterator[Validator]:
(definition of ServiceDynamicPorts.validate:)
def validate( self, validator: Validator, _: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/ecs/ServiceDynamicPorts.py]
[start of new definitions in src/cfnlint/rules/resources/ectwo/InstanceImageId.py]
(definition of InstanceImageId:)
class InstanceImageId(CfnLintKeyword):
(definition of InstanceImageId.__init__:)
def __init__(self) -> None:
(definition of InstanceImageId._get_related_launch_template:)
def _get_related_launch_template( self, validator: Validator, instance: Any ) -> Iterator[tuple[Any, Validator]]:
(definition of InstanceImageId.validate:)
def validate( self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/ectwo/InstanceImageId.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>
The task definition is configured to use a dynamic host port, but the target group has a health check port specified
*cfn-lint version: (`cfn-lint --version`)*
```
pip install cfn-lint
Collecting cfn-lint
Downloading https://files.pythonhosted.org/packages/97/1c/eca74684dea7385c505c52eb5adf578e83f7d3e6890c50791753c54b1639/cfn-lint-0.18.1.tar.gz (1.8MB)
```
*Description of issue.*
When updating a stack I found that there is no check for this
```
The task definition is configured to use a dynamic host port, but the target group with targetGroupArn arn:aws:elasticloadbalancing:us-east-1:**********:targetgroup/*************/bcd1d8e7fa7324f8 has a health check port specified. (Service: AmazonECS; Status Code: 400; Error Code: InvalidParameterException; Request ID: **************)
, removeing the healthcheckport works as the default is what we need to support dynamic ports.
```
Please provide as much information as possible:
* Template linting issues:
* Please provide a CloudFormation sample that generated the issue.
``` TaskTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 30
HealthCheckPath: '/'
HealthCheckPort: '3000'
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 25
Matcher:
HttpCode: '200'
Port: 3000
Protocol: HTTP
```
working template,
```
TaskTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 30
HealthCheckPath: '/'
HealthCheckPort: 'traffic-port'
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 25
Matcher:
HttpCode: '200'
Port: 3000
Protocol: HTTP
```
* If present, please add links to the (official) documentation for clarification.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-healthcheckport
* Validate if the issue still exists with the latest version of `cfn-lint` and/or the latest Spec files
* Feature request:
* Please provide argumentation about the missing feature. Context is key!
Cfn-lint uses the [CloudFormation Resource Specifications](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) as the base to do validation. These files are included as part of the application version. Please update to the latest version of `cfn-lint` or update the spec files manually (`cfn-lint -u`)
----------
Interesting. So this looks associated to the ECS Task Definition? So we would have to associate the ECS Task to the ALB being used? Validating that ECS is using Port 0 which means `HealthCheckPort: 'traffic-port'`
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-portmappings.html#cfn-ecs-taskdefinition-containerdefinition-portmappings-hostport
So many odd little quirks across the services. This one failed the pipe
line, so I thought why not try an issue. The template might have the info
you need to make a check. Let me know if I can help.
On Wed, Apr 10, 2019, 8:32 PM Kevin DeJong <notifications@github.com> wrote:
> Interesting. So this looks associated to the ECS Task Definition? So we
> would have to associate the ECS Task to the ALB being used? Validating that
> ECS is using Port 0 which means HealthCheckPort: 'traffic-port'
>
>
> https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-portmappings.html#cfn-ecs-taskdefinition-containerdefinition-portmappings-hostport
>
> —
> You are receiving this because you authored the thread.
> Reply to this email directly, view it on GitHub
> <https://github.com/aws-cloudformation/cfn-python-lint/issues/817#issuecomment-481920861>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/ABjykKWQkGYwanetjxTsdujk-o1yJ9QCks5vfoKWgaJpZM4cibYA>
> .
>
Yes please create issues for this. These are the types of things we are trying to detect. We do have rules that compare values across resources so we should be able to check for this. We would need the ALB resource in the same template to do this work though.
Of course cdk has the same behaviour.
Using "traffic-port", as suggested, fixes the error.
```js
...
healthCheck: {
protocol: elb.Protocol.HTTP,
path: '/healthz',
port: "traffic-port",
healthyThresholdCount: 2,
unhealthyThresholdCount: 2,
interval: cdk.Duration.seconds(10),
timeout: cdk.Duration.seconds(5)
}
...
```
This one got me, too. Even though the default HealthCheckPort is 'traffic-port', you have to specify it anyways, or the update fails when using dynamic host ports. Is there any intent to add this check to the standard rules?
--------------------
</issues> | 4b214774e419d871b7b498fb5256e2ed09393795 | |
google-deepmind__optax-1015 | 1,015 | google-deepmind/optax | null | f21430a07de801957ee0083bd51b721b1243065e | 2024-07-17T07:07:35Z | diff --git a/optax/transforms/_masking.py b/optax/transforms/_masking.py
index 1e0648a55..f35001bea 100644
--- a/optax/transforms/_masking.py
+++ b/optax/transforms/_masking.py
@@ -36,6 +36,13 @@ class MaskedNode(NamedTuple):
"""
+def _mask_callable(
+ mask: Union[base.PyTree, Callable[[base.Params], base.PyTree]]
+):
+ callable_leaves = jtu.tree_leaves(jtu.tree_map(callable, mask))
+ return (len(callable_leaves) > 0) and all(callable_leaves) # pylint:disable=g-explicit-length-test
+
+
def masked(
inner: base.GradientTransformation,
mask: Union[base.PyTree, Callable[[base.Params], base.PyTree]],
@@ -115,12 +122,12 @@ def init_fn(params):
if isinstance(params, _state_utils._ParamsPlaceholder): # pylint:disable=protected-access
return MaskedState(inner_state=inner.init(params))
- mask_tree = mask(params) if callable(mask) else mask
+ mask_tree = mask(params) if _mask_callable(mask) else mask
masked_params = mask_pytree(params, mask_tree)
return MaskedState(inner_state=inner.init(masked_params))
def update_fn(updates, state, params=None, **extra_args):
- mask_tree = mask(updates) if callable(mask) else mask
+ mask_tree = mask(updates) if _mask_callable(mask) else mask
masked_extra_args = maybe_mask_values(extra_args, updates, mask_tree)
masked_updates = mask_pytree(updates, mask_tree)
masked_params = None if params is None else mask_pytree(params, mask_tree)
| diff --git a/optax/transforms/_masking_test.py b/optax/transforms/_masking_test.py
index 9bba78eaf..d23e46b51 100644
--- a/optax/transforms/_masking_test.py
+++ b/optax/transforms/_masking_test.py
@@ -15,14 +15,16 @@
"""Tests for optax.transforms._masking."""
import copy
+import dataclasses
from typing import cast
from absl.testing import absltest
from absl.testing import parameterized
import chex
-from jax import tree_util as jtu
+import jax
import jax.numpy as jnp
+import jax.tree_util as jtu
import numpy as np
from optax._src import alias
@@ -343,6 +345,42 @@ def test_masked_state_structure(self):
}
chex.assert_trees_all_equal_structs(trace, expected_trace)
+ def test_mask_compatible_callable_pytree(self):
+ """Test if mask is compatible with callable pytrees a la equinox."""
+ # https://github.com/google-deepmind/optax/issues/913
+
+ # Define a dataclass with a callable
+ @dataclasses.dataclass
+ class _MaskCompatibleModule():
+ w: jax.Array
+
+ def __call__(self, x):
+ return self.w.dot(x)
+
+ # Make it a pytree by registring it as a pytree node
+ jtu.register_pytree_node(
+ _MaskCompatibleModule,
+ lambda m: ((m.w,), None),
+ lambda _, c: _MaskCompatibleModule(*c)
+ )
+ module = _MaskCompatibleModule(jnp.array([1., 2., 3.]))
+
+ with self.subTest('test _mask_callable utility'):
+ # The module is then callable (like the Module class in equinox)
+ self.assertTrue(callable(module))
+ # But it won't be treated as a callable by the masking logic
+ self.assertFalse(_masking._mask_callable(module))
+
+ with self.subTest('test masked transform on callable pytree'):
+ mask = _MaskCompatibleModule(False)
+ opt = _masking.masked(
+ _build_sgd(),
+ mask
+ )
+ state = opt.init(module)
+ updates = module
+ new_updates, _ = opt.update(updates, state)
+ chex.assert_trees_all_equal(updates, new_updates)
if __name__ == '__main__':
absltest.main()
| [
{
"components": [
{
"doc": "",
"lines": [
39,
43
],
"name": "_mask_callable",
"signature": "def _mask_callable( mask: Union[base.PyTree, Callable[[base.Params], base.PyTree]] ):",
"type": "function"
}
],
"file": "optax/trans... | [
"optax/transforms/_masking_test.py::MaskedTest::test_mask_compatible_callable_pytree"
] | [
"optax/transforms/_masking_test.py::MaskedTest::test_empty0",
"optax/transforms/_masking_test.py::MaskedTest::test_empty1",
"optax/transforms/_masking_test.py::MaskedTest::test_empty2",
"optax/transforms/_masking_test.py::MaskedTest::test_mask_fn__with_device",
"optax/transforms/_masking_test.py::MaskedTest... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Make masking compatible with callable pytrees a la Equinox
Make masking compatible with callable pytrees a la Equinox
----------
</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/transforms/_masking.py]
(definition of _mask_callable:)
def _mask_callable( mask: Union[base.PyTree, Callable[[base.Params], base.PyTree]] ):
[end of new definitions in optax/transforms/_masking.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 | ||
aws-cloudformation__cfn-lint-3505 | 3,505 | aws-cloudformation/cfn-lint | null | 33acafd3d1739b85daf7d49eb6729b0239561add | 2024-07-16T16:46:05Z | diff --git a/src/cfnlint/data/schemas/extensions/aws_lambda_function/environment_variable_keys.json b/src/cfnlint/data/schemas/extensions/aws_lambda_function/environment_variable_keys.json
new file mode 100644
index 0000000000..6c3897baea
--- /dev/null
+++ b/src/cfnlint/data/schemas/extensions/aws_lambda_function/environment_variable_keys.json
@@ -0,0 +1,26 @@
+{
+ "propertyNames": {
+ "not": {
+ "enum": [
+ "_HANDLER",
+ "_X_AMZN_TRACE_ID",
+ "AWS_DEFAULT_REGION",
+ "AWS_REGION",
+ "AWS_EXECUTION_ENV",
+ "AWS_LAMBDA_FUNCTION_NAME",
+ "AWS_LAMBDA_FUNCTION_MEMORY_SIZE",
+ "AWS_LAMBDA_FUNCTION_VERSION",
+ "AWS_LAMBDA_INITIALIZATION_TYPE",
+ "AWS_LAMBDA_LOG_GROUP_NAME",
+ "AWS_LAMBDA_LOG_STREAM_NAME",
+ "AWS_ACCESS_KEY",
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN",
+ "AWS_LAMBDA_RUNTIME_API",
+ "LAMBDA_TASK_ROOT",
+ "LAMBDA_RUNTIME_DIR"
+ ]
+ }
+ }
+}
diff --git a/src/cfnlint/rules/resources/lmbd/FunctionEnvironmentKeys.py b/src/cfnlint/rules/resources/lmbd/FunctionEnvironmentKeys.py
new file mode 100644
index 0000000000..756398a27f
--- /dev/null
+++ b/src/cfnlint/rules/resources/lmbd/FunctionEnvironmentKeys.py
@@ -0,0 +1,51 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import cfnlint.data.schemas.extensions.aws_lambda_function
+from cfnlint.jsonschema import ValidationResult
+from cfnlint.jsonschema.protocols import Validator
+from cfnlint.rules.jsonschema import CfnLintJsonSchema, SchemaDetails
+
+
+class FunctionEnvironmentKeys(CfnLintJsonSchema):
+
+ id = "E3663"
+ shortdesc = "Validate Lambda environment variable names aren't reserved"
+ description = (
+ "Lambda reserves a set of environment variable names for its use. "
+ "This rule validates that the provided environment variable names "
+ "don't use the reserved variable names"
+ )
+ source_url = (
+ "https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html"
+ )
+ tags = ["resources", "lambda", "runtime"]
+
+ def __init__(self):
+ """Init"""
+ super().__init__(
+ keywords=[
+ "Resources/AWS::Lambda::Function/Properties/Environment/Variables"
+ ],
+ schema_details=SchemaDetails(
+ cfnlint.data.schemas.extensions.aws_lambda_function,
+ "environment_variable_keys.json",
+ ),
+ all_matches=True,
+ )
+
+ def validate(
+ self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+ for err in super().validate(validator, keywords, instance, schema):
+ err.message = (
+ f"{err.instance!r} is a reserved variable name, one of "
+ f"{self.schema.get('propertyNames').get('not').get('enum')!r}"
+ )
+ yield err
| diff --git a/test/unit/rules/resources/lmbd/test_function_environment_keys.py b/test/unit/rules/resources/lmbd/test_function_environment_keys.py
new file mode 100644
index 0000000000..bad7695b21
--- /dev/null
+++ b/test/unit/rules/resources/lmbd/test_function_environment_keys.py
@@ -0,0 +1,109 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from collections import deque
+
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.resources.lmbd.FunctionEnvironmentKeys import FunctionEnvironmentKeys
+
+
+@pytest.fixture(scope="module")
+def rule():
+ rule = FunctionEnvironmentKeys()
+ yield rule
+
+
+@pytest.mark.parametrize(
+ "instance,expected",
+ [
+ (
+ {"Foo": "Bar"},
+ [],
+ ),
+ (
+ {"AWS_REGION": "Bar"},
+ [
+ ValidationError(
+ (
+ "'AWS_REGION' is a reserved variable name, one of "
+ "['_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_DEFAULT_REGION', "
+ "'AWS_REGION', 'AWS_EXECUTION_ENV', "
+ "'AWS_LAMBDA_FUNCTION_NAME', "
+ "'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', "
+ "'AWS_LAMBDA_FUNCTION_VERSION', "
+ "'AWS_LAMBDA_INITIALIZATION_TYPE', "
+ "'AWS_LAMBDA_LOG_GROUP_NAME', "
+ "'AWS_LAMBDA_LOG_STREAM_NAME', "
+ "'AWS_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', "
+ "'AWS_SECRET_ACCESS_KEY', "
+ "'AWS_SESSION_TOKEN', 'AWS_LAMBDA_RUNTIME_API', "
+ "'LAMBDA_TASK_ROOT', 'LAMBDA_RUNTIME_DIR']"
+ ),
+ schema_path=deque(["propertyNames", "not"]),
+ path=deque(["AWS_REGION"]),
+ rule=FunctionEnvironmentKeys(),
+ validator="not",
+ )
+ ],
+ ),
+ (
+ {
+ "Foo": "Bar",
+ "AWS_REGION": "Bar",
+ "Bar": "Foo",
+ "AWS_ACCESS_KEY": "Foo",
+ },
+ [
+ ValidationError(
+ (
+ "'AWS_REGION' is a reserved variable name, one of "
+ "['_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_DEFAULT_REGION', "
+ "'AWS_REGION', 'AWS_EXECUTION_ENV', "
+ "'AWS_LAMBDA_FUNCTION_NAME', "
+ "'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', "
+ "'AWS_LAMBDA_FUNCTION_VERSION', "
+ "'AWS_LAMBDA_INITIALIZATION_TYPE', "
+ "'AWS_LAMBDA_LOG_GROUP_NAME', "
+ "'AWS_LAMBDA_LOG_STREAM_NAME', "
+ "'AWS_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', "
+ "'AWS_SECRET_ACCESS_KEY', "
+ "'AWS_SESSION_TOKEN', 'AWS_LAMBDA_RUNTIME_API', "
+ "'LAMBDA_TASK_ROOT', 'LAMBDA_RUNTIME_DIR']"
+ ),
+ schema_path=deque(["propertyNames", "not"]),
+ path=deque(["AWS_REGION"]),
+ rule=FunctionEnvironmentKeys(),
+ validator="not",
+ ),
+ ValidationError(
+ (
+ "'AWS_ACCESS_KEY' is a reserved variable name, one of "
+ "['_HANDLER', '_X_AMZN_TRACE_ID', 'AWS_DEFAULT_REGION', "
+ "'AWS_REGION', 'AWS_EXECUTION_ENV', "
+ "'AWS_LAMBDA_FUNCTION_NAME', "
+ "'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', "
+ "'AWS_LAMBDA_FUNCTION_VERSION', "
+ "'AWS_LAMBDA_INITIALIZATION_TYPE', "
+ "'AWS_LAMBDA_LOG_GROUP_NAME', "
+ "'AWS_LAMBDA_LOG_STREAM_NAME', "
+ "'AWS_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', "
+ "'AWS_SECRET_ACCESS_KEY', "
+ "'AWS_SESSION_TOKEN', 'AWS_LAMBDA_RUNTIME_API', "
+ "'LAMBDA_TASK_ROOT', 'LAMBDA_RUNTIME_DIR']"
+ ),
+ schema_path=deque(["propertyNames", "not"]),
+ path=deque(["AWS_ACCESS_KEY"]),
+ rule=FunctionEnvironmentKeys(),
+ validator="not",
+ ),
+ ],
+ ),
+ ],
+)
+def test_validate(instance, expected, rule, validator):
+ errs = list(rule.validate(validator, "LambdaRuntime", instance, {}))
+ assert errs == expected, f"Expected {expected} got {errs}"
| diff --git a/src/cfnlint/data/schemas/extensions/aws_lambda_function/environment_variable_keys.json b/src/cfnlint/data/schemas/extensions/aws_lambda_function/environment_variable_keys.json
new file mode 100644
index 0000000000..6c3897baea
--- /dev/null
+++ b/src/cfnlint/data/schemas/extensions/aws_lambda_function/environment_variable_keys.json
@@ -0,0 +1,26 @@
+{
+ "propertyNames": {
+ "not": {
+ "enum": [
+ "_HANDLER",
+ "_X_AMZN_TRACE_ID",
+ "AWS_DEFAULT_REGION",
+ "AWS_REGION",
+ "AWS_EXECUTION_ENV",
+ "AWS_LAMBDA_FUNCTION_NAME",
+ "AWS_LAMBDA_FUNCTION_MEMORY_SIZE",
+ "AWS_LAMBDA_FUNCTION_VERSION",
+ "AWS_LAMBDA_INITIALIZATION_TYPE",
+ "AWS_LAMBDA_LOG_GROUP_NAME",
+ "AWS_LAMBDA_LOG_STREAM_NAME",
+ "AWS_ACCESS_KEY",
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN",
+ "AWS_LAMBDA_RUNTIME_API",
+ "LAMBDA_TASK_ROOT",
+ "LAMBDA_RUNTIME_DIR"
+ ]
+ }
+ }
+}
| [
{
"components": [
{
"doc": "",
"lines": [
16,
51
],
"name": "FunctionEnvironmentKeys",
"signature": "class FunctionEnvironmentKeys(CfnLintJsonSchema):",
"type": "class"
},
{
"doc": "Init",
"lines": [
... | [
"test/unit/rules/resources/lmbd/test_function_environment_keys.py::test_validate[instance0-expected0]",
"test/unit/rules/resources/lmbd/test_function_environment_keys.py::test_validate[instance1-expected1]",
"test/unit/rules/resources/lmbd/test_function_environment_keys.py::test_validate[instance2-expected2]"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add rule E3663 to validate lambda fn env vars
*Issue #, if available:*
*Description of changes:*
- Add rule E3663 to validate lambda fn env vars
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
----------
</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/cfnlint/rules/resources/lmbd/FunctionEnvironmentKeys.py]
(definition of FunctionEnvironmentKeys:)
class FunctionEnvironmentKeys(CfnLintJsonSchema):
(definition of FunctionEnvironmentKeys.__init__:)
def __init__(self):
"""Init"""
(definition of FunctionEnvironmentKeys.validate:)
def validate( self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/lmbd/FunctionEnvironmentKeys.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>> | 4b214774e419d871b7b498fb5256e2ed09393795 | |
Textualize__textual-4739 | 4,739 | Textualize/textual | null | 7c8450887d3e9850898130270a5e0e4b34de2fd2 | 2024-07-14T17:07:05Z | diff --git a/CHANGELOG.md b/CHANGELOG.md
index c530fcf562..fbb4b8a577 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added
- `TextArea.line_number_start` reactive attribute https://github.com/Textualize/textual/pull/4471
+- Added "quality" parameter to `textual.color.Gradient` https://github.com/Textualize/textual/pull/4739
+- Added `textual.color.Gradient.get_rich_color` https://github.com/Textualize/textual/pull/4739
- `Widget.remove_children` now accepts an iterable if widgets in addition to a selector https://github.com/Textualize/textual/issues/4735
- Raise `ValueError` with improved error message when number of cells inserted using `DataTable.add_row` doesn't match the number of columns in the table https://github.com/Textualize/textual/pull/4742
diff --git a/src/textual/color.py b/src/textual/color.py
index 449843a2c2..31ce703844 100644
--- a/src/textual/color.py
+++ b/src/textual/color.py
@@ -42,12 +42,11 @@
from rich.color_triplet import ColorTriplet
from typing_extensions import Final
-from textual.css.scalar import percentage_string_to_float
-from textual.css.tokenize import CLOSE_BRACE, COMMA, DECIMAL, OPEN_BRACE, PERCENT
-from textual.suggestions import get_suggestion
-
from ._color_constants import COLOR_NAME_TO_RGB
+from .css.scalar import percentage_string_to_float
+from .css.tokenize import CLOSE_BRACE, COMMA, DECIMAL, OPEN_BRACE, PERCENT
from .geometry import clamp
+from .suggestions import get_suggestion
_TRUECOLOR = ColorType.TRUECOLOR
@@ -224,6 +223,7 @@ def clamped(self) -> Color:
return color
@property
+ @lru_cache(1024)
def rich_color(self) -> RichColor:
"""This color encoded in Rich's Color class.
@@ -551,25 +551,74 @@ def get_contrast_text(self, alpha: float = 0.95) -> Color:
class Gradient:
"""Defines a color gradient."""
- def __init__(self, *stops: tuple[float, Color]) -> None:
+ def __init__(self, *stops: tuple[float, Color | str], quality: int = 200) -> None:
"""Create a color gradient that blends colors to form a spectrum.
- A gradient is defined by a sequence of "stops" consisting of a float and a color.
- The stop indicate the color at that point on a spectrum between 0 and 1.
+ A gradient is defined by a sequence of "stops" consisting of a tuple containing a float and a color.
+ The stop indicates the color at that point on a spectrum between 0 and 1.
+ Colors may be given as a [Color][textual.color.Color] instance, or a string that
+ can be parsed into a Color (with [Color.parse][textual.color.Color.parse]).
+
+ The quality of the argument defines the number of _steps_ in the gradient.
+ 200 was chosen so that there was no obvious banding in [LinearGradient][textual.renderables.gradient.LinearGradient].
+ Higher values are unlikely to yield any benefit, but lower values may result in quicker rendering.
Args:
- stops: A colors stop.
+ stops: Color stops.
+ quality: The number of steps in the gradient.
Raises:
ValueError: If any stops are missing (must be at least a stop for 0 and 1).
"""
- self._stops = sorted(stops)
+ parse = Color.parse
+ self._stops = sorted(
+ [
+ (
+ (position, parse(color))
+ if isinstance(color, str)
+ else (position, color)
+ )
+ for position, color in stops
+ ]
+ )
if len(stops) < 2:
raise ValueError("At least 2 stops required.")
if self._stops[0][0] != 0.0:
raise ValueError("First stop must be 0.")
if self._stops[-1][0] != 1.0:
raise ValueError("Last stop must be 1.")
+ self._quality = quality
+ self._colors: list[Color] | None = None
+ self._rich_colors: list[RichColor] | None = None
+
+ @property
+ def colors(self) -> list[Color]:
+ """A list of colors in the gradient."""
+ position = 0
+ quality = self._quality
+
+ if self._colors is None:
+ colors: list[Color] = []
+ add_color = colors.append
+ (stop1, color1), (stop2, color2) = self._stops[0:2]
+ for step_position in range(quality):
+ step = step_position / (quality - 1)
+ while step > stop2:
+ position += 1
+ (stop1, color1), (stop2, color2) = self._stops[
+ position : position + 2
+ ]
+ add_color(color1.blend(color2, (step - stop1) / (stop2 - stop1)))
+ self._colors = colors
+ assert len(self._colors) == self._quality
+ return self._colors
+
+ @property
+ def rich_colors(self) -> list[RichColor]:
+ """A list of colors in the gradient (for the Rich library)."""
+ if self._rich_colors is None:
+ self._rich_colors = [color.rich_color for color in self.colors]
+ return self._rich_colors
def get_color(self, position: float) -> Color:
"""Get a color from the gradient at a position between 0 and 1.
@@ -580,17 +629,26 @@ def get_color(self, position: float) -> Color:
position: A number between 0 and 1, where 0 is the first stop, and 1 is the last.
Returns:
- A color.
+ A Textual color.
"""
- # TODO: consider caching
- position = clamp(position, 0.0, 1.0)
- for (stop1, color1), (stop2, color2) in zip(self._stops, self._stops[1:]):
- if stop2 >= position >= stop1:
- return color1.blend(
- color2,
- (position - stop1) / (stop2 - stop1),
- )
- raise AssertionError("Can't get here if `_stops` is valid")
+ quality = self._quality - 1
+ color_index = int(clamp(position * quality, 0, quality))
+ return self.colors[color_index]
+
+ def get_rich_color(self, position: float) -> RichColor:
+ """Get a (Rich) color from the gradient at a position between 0 and 1.
+
+ Positions that are between stops will return a blended color.
+
+ Args:
+ position: A number between 0 and 1, where 0 is the first stop, and 1 is the last.
+
+ Returns:
+ A (Rich) color.
+ """
+ quality = self._quality - 1
+ color_index = int(clamp(position * quality, 0, quality))
+ return self.rich_colors[color_index]
# Color constants
diff --git a/src/textual/renderables/gradient.py b/src/textual/renderables/gradient.py
index 7dd359f7a7..82534b8f7f 100644
--- a/src/textual/renderables/gradient.py
+++ b/src/textual/renderables/gradient.py
@@ -1,10 +1,8 @@
from __future__ import annotations
-from functools import lru_cache
from math import cos, pi, sin
from typing import Sequence
-from rich.color import Color as RichColor
from rich.console import Console, ConsoleOptions, RenderResult
from rich.segment import Segment
from rich.style import Style
@@ -59,6 +57,7 @@ def __init__(
(stop, Color.parse(color) if isinstance(color, str) else color)
for stop, color in stops
]
+ self._color_gradient = Gradient(*self._stops)
def __rich_console__(
self, console: Console, options: ConsoleOptions
@@ -75,38 +74,20 @@ def __rich_console__(
new_line = Segment.line()
- color_gradient = Gradient(*self._stops)
-
_Segment = Segment
- get_color = color_gradient.get_color
+ get_color = self._color_gradient.get_rich_color
from_color = Style.from_color
- @lru_cache(maxsize=1024)
- def get_rich_color(color_offset: int) -> RichColor:
- """Get a Rich color in the gradient.
-
- Args:
- color_index: A offset within the color gradient normalized between 0 and 255.
-
- Returns:
- A Rich color.
- """
- return get_color(color_offset / 255).rich_color
-
for line_y in range(height):
point_y = float(line_y) * 2 - center_y
point_x = 0 - center_x
- x1 = (center_x + (point_x * cos_angle - point_y * sin_angle)) / width * 255
+ x1 = (center_x + (point_x * cos_angle - point_y * sin_angle)) / width
x2 = (
- (center_x + (point_x * cos_angle - (point_y + 1.0) * sin_angle))
- / width
- * 255
- )
+ center_x + (point_x * cos_angle - (point_y + 1.0) * sin_angle)
+ ) / width
point_x = width - center_x
- end_x1 = (
- (center_x + (point_x * cos_angle - point_y * sin_angle)) / width * 255
- )
+ end_x1 = (center_x + (point_x * cos_angle - point_y * sin_angle)) / width
delta_x = (end_x1 - x1) / width
if abs(delta_x) < 0.0001:
@@ -114,8 +95,8 @@ def get_rich_color(color_offset: int) -> RichColor:
yield _Segment(
"▀" * width,
from_color(
- get_rich_color(int(x1)),
- get_rich_color(int(x2)),
+ get_color(x1),
+ get_color(x2),
),
)
@@ -124,8 +105,8 @@ def get_rich_color(color_offset: int) -> RichColor:
_Segment(
"▀",
from_color(
- get_rich_color(int(x1 + x * delta_x)),
- get_rich_color(int(x2 + x * delta_x)),
+ get_color(x1 + x * delta_x),
+ get_color(x2 + x * delta_x),
),
)
for x in range(width)
| diff --git a/tests/test_color.py b/tests/test_color.py
index bdae7a7cbb..127d24d716 100644
--- a/tests/test_color.py
+++ b/tests/test_color.py
@@ -245,8 +245,9 @@ def test_gradient_errors():
def test_gradient():
gradient = Gradient(
(0, Color(255, 0, 0)),
- (0.5, Color(0, 0, 255)),
+ (0.5, "blue"),
(1, Color(0, 255, 0)),
+ quality=11,
)
assert gradient.get_color(-1) == Color(255, 0, 0)
@@ -255,7 +256,3 @@ def test_gradient():
assert gradient.get_color(1.2) == Color(0, 255, 0)
assert gradient.get_color(0.5) == Color(0, 0, 255)
assert gradient.get_color(0.7) == Color(0, 101, 153)
-
- gradient._stops.pop()
- with pytest.raises(AssertionError):
- gradient.get_color(1.0)
| diff --git a/CHANGELOG.md b/CHANGELOG.md
index c530fcf562..fbb4b8a577 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added
- `TextArea.line_number_start` reactive attribute https://github.com/Textualize/textual/pull/4471
+- Added "quality" parameter to `textual.color.Gradient` https://github.com/Textualize/textual/pull/4739
+- Added `textual.color.Gradient.get_rich_color` https://github.com/Textualize/textual/pull/4739
- `Widget.remove_children` now accepts an iterable if widgets in addition to a selector https://github.com/Textualize/textual/issues/4735
- Raise `ValueError` with improved error message when number of cells inserted using `DataTable.add_row` doesn't match the number of columns in the table https://github.com/Textualize/textual/pull/4742
| [
{
"components": [
{
"doc": "A list of colors in the gradient.",
"lines": [
595,
614
],
"name": "Gradient.colors",
"signature": "def colors(self) -> list[Color]:",
"type": "function"
},
{
"doc": "A list of colors in the... | [
"tests/test_color.py::test_gradient"
] | [
"tests/test_color.py::test_rich_color",
"tests/test_color.py::test_normalized",
"tests/test_color.py::test_clamped",
"tests/test_color.py::test_css",
"tests/test_color.py::test_monochrome",
"tests/test_color.py::test_rgb",
"tests/test_color.py::test_hsl",
"tests/test_color.py::test_color_brightness",
... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
faster gradients
Optimized linear color gradients, with some precalculation.
In the future gradients will become more of a first class feature.
----------
</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/color.py]
(definition of Gradient.colors:)
def colors(self) -> list[Color]:
"""A list of colors in the gradient."""
(definition of Gradient.rich_colors:)
def rich_colors(self) -> list[RichColor]:
"""A list of colors in the gradient (for the Rich library)."""
(definition of Gradient.get_rich_color:)
def get_rich_color(self, position: float) -> RichColor:
"""Get a (Rich) color from the gradient at a position between 0 and 1.
Positions that are between stops will return a blended color.
Args:
position: A number between 0 and 1, where 0 is the first stop, and 1 is the last.
Returns:
A (Rich) color."""
[end of new definitions in src/textual/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>> | 86e93536b991014e0ea4bf993068202b446bb698 | |
astronomer__astronomer-cosmos-1091 | 1,091 | astronomer/astronomer-cosmos | null | 1f276384da7c165f943ef5df32a550a48dff61a5 | 2024-07-13T20:17:34Z | diff --git a/cosmos/profiles/__init__.py b/cosmos/profiles/__init__.py
index 392b4f78b..00b934881 100644
--- a/cosmos/profiles/__init__.py
+++ b/cosmos/profiles/__init__.py
@@ -10,6 +10,7 @@
from .bigquery.service_account_file import GoogleCloudServiceAccountFileProfileMapping
from .bigquery.service_account_keyfile_dict import GoogleCloudServiceAccountDictProfileMapping
from .clickhouse.user_pass import ClickhouseUserPasswordProfileMapping
+from .databricks.oauth import DatabricksOauthProfileMapping
from .databricks.token import DatabricksTokenProfileMapping
from .exasol.user_pass import ExasolUserPasswordProfileMapping
from .postgres.user_pass import PostgresUserPasswordProfileMapping
@@ -32,6 +33,7 @@
GoogleCloudServiceAccountDictProfileMapping,
GoogleCloudOauthProfileMapping,
DatabricksTokenProfileMapping,
+ DatabricksOauthProfileMapping,
PostgresUserPasswordProfileMapping,
RedshiftUserPasswordProfileMapping,
SnowflakeUserPasswordProfileMapping,
@@ -73,6 +75,7 @@ def get_automatic_profile_mapping(
"GoogleCloudServiceAccountDictProfileMapping",
"GoogleCloudOauthProfileMapping",
"DatabricksTokenProfileMapping",
+ "DatabricksOauthProfileMapping",
"DbtProfileConfigVars",
"PostgresUserPasswordProfileMapping",
"RedshiftUserPasswordProfileMapping",
diff --git a/cosmos/profiles/databricks/__init__.py b/cosmos/profiles/databricks/__init__.py
index 2e3a9d114..7ce683c7a 100644
--- a/cosmos/profiles/databricks/__init__.py
+++ b/cosmos/profiles/databricks/__init__.py
@@ -1,5 +1,6 @@
"""Databricks Airflow connection -> dbt profile mappings"""
+from .oauth import DatabricksOauthProfileMapping
from .token import DatabricksTokenProfileMapping
-__all__ = ["DatabricksTokenProfileMapping"]
+__all__ = ["DatabricksTokenProfileMapping", "DatabricksOauthProfileMapping"]
diff --git a/cosmos/profiles/databricks/oauth.py b/cosmos/profiles/databricks/oauth.py
new file mode 100644
index 000000000..fd6875c49
--- /dev/null
+++ b/cosmos/profiles/databricks/oauth.py
@@ -0,0 +1,48 @@
+"""Maps Airflow Databricks connections with the client auth to dbt profiles."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from ..base import BaseProfileMapping
+
+
+class DatabricksOauthProfileMapping(BaseProfileMapping):
+ """
+ Maps Airflow Databricks connections with the client auth to dbt profiles.
+
+ https://docs.getdbt.com/reference/warehouse-setups/databricks-setup
+ https://airflow.apache.org/docs/apache-airflow-providers-databricks/stable/connections/databricks.html
+ """
+
+ airflow_connection_type: str = "databricks"
+ dbt_profile_type: str = "databricks"
+
+ required_fields = [
+ "host",
+ "schema",
+ "client_secret",
+ "client_id",
+ "http_path",
+ ]
+
+ secret_fields = ["client_secret", "client_id"]
+
+ airflow_param_mapping = {
+ "host": "host",
+ "schema": "schema",
+ "client_id": ["login", "extra.client_id"],
+ "client_secret": ["password", "extra.client_secret"],
+ "http_path": "extra.http_path",
+ }
+
+ @property
+ def profile(self) -> dict[str, Any | None]:
+ """Generates profile. The client-id and client-secret is stored in an environment variable."""
+ return {
+ **self.mapped_params,
+ **self.profile_args,
+ "auth_type": "oauth",
+ "client_secret": self.get_env_var_format("client_secret"),
+ "client_id": self.get_env_var_format("client_id"),
+ }
| diff --git a/tests/profiles/databricks/test_dbr_oauth.py b/tests/profiles/databricks/test_dbr_oauth.py
new file mode 100644
index 000000000..96228c4bb
--- /dev/null
+++ b/tests/profiles/databricks/test_dbr_oauth.py
@@ -0,0 +1,71 @@
+"""Tests for the databricks OAuth profile."""
+
+from unittest.mock import patch
+
+import pytest
+from airflow.models.connection import Connection
+
+from cosmos.profiles.databricks import DatabricksOauthProfileMapping
+
+
+@pytest.fixture()
+def mock_databricks_conn(): # type: ignore
+ """
+ Mocks and returns an Airflow Databricks connection.
+ """
+ conn = Connection(
+ conn_id="my_databricks_connection",
+ conn_type="databricks",
+ host="https://my_host",
+ login="my_client_id",
+ password="my_client_secret",
+ extra='{"http_path": "my_http_path"}',
+ )
+
+ with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn):
+ yield conn
+
+
+def test_connection_claiming() -> None:
+ """
+ Tests that the Databricks profile mapping claims the correct connection type.
+ """
+ # should only claim when:
+ # - conn_type == databricks
+ # and the following exist:
+ # - schema
+ # - host
+ # - http_path
+ # - client_id
+ # - client_secret
+ potential_values = {
+ "conn_type": "databricks",
+ "host": "my_host",
+ "login": "my_client_id",
+ "password": "my_client_secret",
+ "extra": '{"http_path": "my_http_path"}',
+ }
+
+ # if we're missing any of the values, it shouldn't claim
+ for key in potential_values:
+ values = potential_values.copy()
+ del values[key]
+ conn = Connection(**values) # type: ignore
+
+ print("testing with", values)
+
+ with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn):
+ profile_mapping = DatabricksOauthProfileMapping(conn, {"schema": "my_schema"})
+ assert not profile_mapping.can_claim_connection()
+
+ # also test when there's no schema
+ conn = Connection(**potential_values) # type: ignore
+ with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn):
+ profile_mapping = DatabricksOauthProfileMapping(conn, {})
+ assert not profile_mapping.can_claim_connection()
+
+ # if we have them all, it should claim
+ conn = Connection(**potential_values) # type: ignore
+ with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn):
+ profile_mapping = DatabricksOauthProfileMapping(conn, {"schema": "my_schema"})
+ assert profile_mapping.can_claim_connection()
| [
{
"components": [
{
"doc": "Maps Airflow Databricks connections with the client auth to dbt profiles.\n\nhttps://docs.getdbt.com/reference/warehouse-setups/databricks-setup\nhttps://airflow.apache.org/docs/apache-airflow-providers-databricks/stable/connections/databricks.html",
"lines": [
... | [
"tests/profiles/databricks/test_dbr_oauth.py::test_connection_claiming"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
add DatabricksOauthProfileMapping profile
## Description
As of now, Token-based auth is the only possible way to access databricks from cosmos, even though dbt-databricks support OAuth-based access as can be seen [here ](https://docs.getdbt.com/docs/core/connect-data-platform/databricks-setup).
This PR aims to enhance the support offered by cosmos to databricks. The final goal is to close #1085
I have tested locally and got a positive result.
## Breaking Change?
No
## Checklist
- [X] 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/databricks/oauth.py]
(definition of DatabricksOauthProfileMapping:)
class DatabricksOauthProfileMapping(BaseProfileMapping):
"""Maps Airflow Databricks connections with the client auth to dbt profiles.
https://docs.getdbt.com/reference/warehouse-setups/databricks-setup
https://airflow.apache.org/docs/apache-airflow-providers-databricks/stable/connections/databricks.html"""
(definition of DatabricksOauthProfileMapping.profile:)
def profile(self) -> dict[str, Any | None]:
"""Generates profile. The client-id and client-secret is stored in an environment variable."""
[end of new definitions in cosmos/profiles/databricks/oauth.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>
[Feature] Databricks - Allow each dbt node to run in its own configurable cluster
### Description
I am currently working in a company that is using an in-house solution to run dbt-like transformations on databricks and I am trying to switch to dbt & cosmos. The issue arrives in the fact that the current solution has an extra level of control which is **the ability to spin up a cluster with custom resources, run the transformation in that cluster and, once concluded, the cluster stops**. The time wasted spinning up clusters for singular SQL tasks is not a big concern, since the money saved on the process is tremendous in comparison with deploying dbt models in an all-purpose cluster or in the databricks SQL warehouse, which is what dbt supports at the moment.
# General Idea
- For dbt-databricks DAGs, there should be an extra operator with the option to pass a json file as a parameter mapping cluster resources for individual nodes
- The dbt node and its corresponding tests should run in the same cluster
# Implementation ideas
## Functionality
1. Allow cosmos to call databricks API for some custom Operator (for example, _DbtDatabricksClusterOperator_)
airflow [DatabricksSubmitRunOperator](https://airflow.apache.org/docs/apache-airflow-providers-databricks/stable/operators/submit_run.html) allows to submit **dbt_task** commands from it. The issue I saw is that the [PR](https://github.com/apache/airflow/pull/25623/files#diff-30731826b25d422cb6069898701e34f8ef23b2a32b7782444793a14bc52b0cb1R365) that added this feature hard-codes it to only work with git sync, which is the opposite direction of cosmos. I can submit a PR later on airflow repo to change that, but for now as a solution I can think of is directly calling databricks API which allows us to specify the [project path](https://docs.databricks.com/api/workspace/jobs/submit#tasks-dbt_task-project_directory). The drawback I can think about is that in the case the user is using the `manifest.json` to trigger jobs, this approach would not work by default.
An alternative would be to run a task's query as a databricks [sql_task](https://docs.databricks.com/api/workspace/jobs/submit#tasks-sql_task) API request, which would be a more universal approach since cosmos is essentially doing dbt's job by rendering the query in the first place.
2. add an extra field (`cluster_resources`) to this operator
The custom operator would have an extra field where we can map the dbt task name with the cluster configs it should have. one of the fields can be called `default` and if no task cluster config is given, the task should use the default resources.
`DbtDatabricksClusterOperator(...,
cluster_resources = {
"default" : { "new_cluster" : {...}},
"my_task_1" : {"new_cluster":{...}},
...
}
)`
## Observation
This is the most straightforward idea I could think of, but it has been a long time I do not touch the project and I am more than open for suggestions before I even start working on it. I thought about other ideas, such as maybe deploying the models to different warehouses based on tags (`low`, `medium`, `high`), spinning up the cluster with a custom task and shutting it down at the end of a successful task and so on, but all of them had implementation problems. What do you think @tatiana ? Any feedback before I start implementing? or recommendations? The project changed a lot since the last time I dealt with it, so maybe there is a better way I am not aware of.
## Other useful links
[specifying compute resources for nodes in the dbt_project.yaml](https://docs.getdbt.com/reference/resource-configs/databricks-configs#specifying-the-compute-for-models)
### Use case/motivation
- There is a huge price difference depending on how you deploy your dbt model on databricks, and unfortunately dbt does not support the most economical way possible : creating a cluster per task that is terminated once the task is done
- when you have an all-purpose data warehouse for dbt transformations, you will have to deal with dbt nodes competing for resources
- It is easier to track resource consumption per dbt node when you map one task to one cluster
### Related issues
_No response_
### Are you willing to submit a PR?
- [X] Yes, I am willing to submit a PR!
----------
--------------------
</issues> | c5edba07d2265d5185eaba149a639e8a0740e498 | |
tobymao__sqlglot-3757 | 3,757 | tobymao/sqlglot | null | 15ca924ac6e8a72396a882c394856e466cae9ac3 | 2024-07-11T11:02:22Z | diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index c8313054fd..0aaf69c6da 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -381,6 +381,7 @@ class Generator(generator.Generator):
SUPPORTS_TO_NUMBER = False
COPY_HAS_INTO_KEYWORD = False
STAR_EXCEPT = "EXCLUDE"
+ PAD_FILL_PATTERN_IS_REQUIRED = True
TRANSFORMS = {
**generator.Generator.TRANSFORMS,
diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py
index a447d13671..5120a1d8d8 100644
--- a/sqlglot/dialects/hive.py
+++ b/sqlglot/dialects/hive.py
@@ -447,6 +447,7 @@ class Generator(generator.Generator):
SUPPORTS_TO_NUMBER = False
WITH_PROPERTIES_PREFIX = "TBLPROPERTIES"
PARSE_JSON_NAME = None
+ PAD_FILL_PATTERN_IS_REQUIRED = True
EXPRESSIONS_WITHOUT_NESTED_CTES = {
exp.Insert,
diff --git a/sqlglot/dialects/mysql.py b/sqlglot/dialects/mysql.py
index 4ffe2fd7bf..630ced554d 100644
--- a/sqlglot/dialects/mysql.py
+++ b/sqlglot/dialects/mysql.py
@@ -690,6 +690,7 @@ class Generator(generator.Generator):
JSON_KEY_VALUE_PAIR_SEP = ","
SUPPORTS_TO_NUMBER = False
PARSE_JSON_NAME = None
+ PAD_FILL_PATTERN_IS_REQUIRED = True
TRANSFORMS = {
**generator.Generator.TRANSFORMS,
diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py
index e79014d84a..b4e69aa97d 100644
--- a/sqlglot/dialects/presto.py
+++ b/sqlglot/dialects/presto.py
@@ -335,6 +335,7 @@ class Generator(generator.Generator):
SUPPORTS_TO_NUMBER = False
HEX_FUNC = "TO_HEX"
PARSE_JSON_NAME = "JSON_PARSE"
+ PAD_FILL_PATTERN_IS_REQUIRED = True
PROPERTIES_LOCATION = {
**generator.Generator.PROPERTIES_LOCATION,
diff --git a/sqlglot/dialects/spark.py b/sqlglot/dialects/spark.py
index 2f2ec8783d..75c477caa3 100644
--- a/sqlglot/dialects/spark.py
+++ b/sqlglot/dialects/spark.py
@@ -129,6 +129,7 @@ def _parse_generated_as_identity(
class Generator(Spark2.Generator):
SUPPORTS_TO_NUMBER = True
+ PAD_FILL_PATTERN_IS_REQUIRED = False
TYPE_MAPPING = {
**Spark2.Generator.TYPE_MAPPING,
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 79511da48d..7f295e3fbe 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -4793,6 +4793,11 @@ class List(Func):
is_var_len_args = True
+# String pad, kind True -> LPAD, False -> RPAD
+class Pad(Func):
+ arg_types = {"this": True, "expression": True, "fill_pattern": False, "is_left": True}
+
+
# https://docs.snowflake.com/en/sql-reference/functions/to_char
# https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/TO_CHAR-number.html
class ToChar(Func):
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index 40ad468009..0fdd431144 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -374,6 +374,9 @@ class Generator(metaclass=_Generator):
# Whether to quote the generated expression of exp.JsonPath
QUOTE_JSON_PATH = True
+ # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space)
+ PAD_FILL_PATTERN_IS_REQUIRED = False
+
# The name to generate for the JSONPath expression. If `None`, only `this` will be generated
PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
@@ -4041,3 +4044,12 @@ def changes_sql(self, expression: exp.Changes) -> str:
end = f"{self.seg('')}{end}" if end else ""
return f"CHANGES ({information}){at_before}{end}"
+
+ def pad_sql(self, expression: exp.Pad) -> str:
+ prefix = "L" if expression.args.get("is_left") else "R"
+
+ fill_pattern = self.sql(expression, "fill_pattern") or None
+ if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
+ fill_pattern = "' '"
+
+ return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index d655b8495d..83c29b7c9b 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -108,6 +108,15 @@ def build_mod(args: t.List) -> exp.Mod:
return exp.Mod(this=this, expression=expression)
+def build_pad(args: t.List, is_left: bool = True):
+ return exp.Pad(
+ this=seq_get(args, 0),
+ expression=seq_get(args, 1),
+ fill_pattern=seq_get(args, 2),
+ is_left=is_left,
+ )
+
+
class _Parser(type):
def __new__(cls, clsname, bases, attrs):
klass = super().__new__(cls, clsname, bases, attrs)
@@ -159,7 +168,11 @@ class Parser(metaclass=_Parser):
"LOG2": lambda args: exp.Log(this=exp.Literal.number(2), expression=seq_get(args, 0)),
"LOG10": lambda args: exp.Log(this=exp.Literal.number(10), expression=seq_get(args, 0)),
"LOWER": build_lower,
+ "LPAD": lambda args: build_pad(args),
+ "LEFTPAD": lambda args: build_pad(args),
"MOD": build_mod,
+ "RPAD": lambda args: build_pad(args, is_left=False),
+ "RIGHTPAD": lambda args: build_pad(args, is_left=False),
"SCOPE_RESOLUTION": lambda args: exp.ScopeResolution(expression=seq_get(args, 0))
if len(args) != 2
else exp.ScopeResolution(this=seq_get(args, 0), expression=seq_get(args, 1)),
| diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py
index c0afb2f467..54cbb4975d 100644
--- a/tests/dialects/test_dialect.py
+++ b/tests/dialects/test_dialect.py
@@ -2566,3 +2566,33 @@ def test_reserved_keywords(self):
"""SELECT partition.d FROM t PARTITION (d)""",
"""SELECT partition.d FROM t AS PARTITION(d)""",
)
+
+ def test_string_functions(self):
+ for pad_func in ("LPAD", "RPAD"):
+ ch_alias = "LEFTPAD" if pad_func == "LPAD" else "RIGHTPAD"
+ for fill_pattern in ("", ", ' '"):
+ with self.subTest(f"Testing {pad_func}() with pattern {fill_pattern}"):
+ self.validate_all(
+ f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ read={
+ "snowflake": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "databricks": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "spark": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "postgres": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "clickhouse": f"SELECT {ch_alias}('bar', 5{fill_pattern})",
+ },
+ write={
+ "": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "spark": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "postgres": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "clickhouse": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "snowflake": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "databricks": f"SELECT {pad_func}('bar', 5{fill_pattern})",
+ "duckdb": f"SELECT {pad_func}('bar', 5, ' ')",
+ "mysql": f"SELECT {pad_func}('bar', 5, ' ')",
+ "hive": f"SELECT {pad_func}('bar', 5, ' ')",
+ "spark2": f"SELECT {pad_func}('bar', 5, ' ')",
+ "presto": f"SELECT {pad_func}('bar', 5, ' ')",
+ "trino": f"SELECT {pad_func}('bar', 5, ' ')",
+ },
+ )
| [] | [
"tests/dialects/test_dialect.py::TestDialect::test_string_functions"
] | [
"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_defin... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Support for RPAD & LPAD functions
Introduce `exp.Pad` which supports the string padding functions `LPAD()`, `RPAD()`; The joint node is used because these 2 functions share the same signature but differ on the result (left/right application of padding)
Most dialects default to whitespace for the padding (3rd parameter) while DuckDB, MySQL, Presto/Trino, and Hive/Spark2 require it explicitly, so the flag `PAD_FILL_PATTERN_IS_REQUIRED` was introduced to facilitate transpilation during generation.
Docs
--------
[Databricks / Spark3](https://docs.databricks.com/en/sql/language-manual/functions/lpad.html) | [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/string_functions#lpad) | [DuckDB](https://duckdb.org/docs/sql/functions/char.html#lpadstring-count-character) | [Postgres](https://www.postgresql.org/docs/9.1/functions-string.html) | [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_LPAD.html) | [Snowflake](https://docs.snowflake.com/en/sql-reference/functions/lpad) | [MySQL](https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_lpad) | [Hive / Spark2](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF) | [Presto](https://prestodb.io/docs/current/functions/string.html#lpad-string-size-padstring-varchar) | [Trino](https://trino.io/docs/current/functions/string.html#lpad)
----------
</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>
</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 | ||
pvlib__pvlib-python-2124 | 2,124 | pvlib/pvlib-python | 0.10 | 899b10c2f327aecb4603c36d33ac6e1561c694c3 | 2024-07-10T16:00:30Z | diff --git a/docs/sphinx/source/reference/airmass_atmospheric.rst b/docs/sphinx/source/reference/airmass_atmospheric.rst
index fbd33a5f28..384c345aec 100644
--- a/docs/sphinx/source/reference/airmass_atmospheric.rst
+++ b/docs/sphinx/source/reference/airmass_atmospheric.rst
@@ -17,3 +17,4 @@ Airmass and atmospheric models
atmosphere.kasten96_lt
atmosphere.angstrom_aod_at_lambda
atmosphere.angstrom_alpha
+ atmosphere.windspeed_powerlaw
diff --git a/docs/sphinx/source/whatsnew/v0.11.1.rst b/docs/sphinx/source/whatsnew/v0.11.1.rst
index 4ccc9687c3..3197882d93 100644
--- a/docs/sphinx/source/whatsnew/v0.11.1.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.1.rst
@@ -17,6 +17,9 @@ Enhancements
:py:func:`pvlib.spectrum.spectral_factor_firstsolar`.
(:issue:`2086`, :pull:`2100`)
+* Added function for calculating wind speed at different heights,
+ :py:func:`pvlib.atmosphere.windspeed_powerlaw`.
+ (:issue:`2118`, :pull:`2124`)
Bug fixes
~~~~~~~~~
@@ -45,4 +48,3 @@ Contributors
* Leonardo Micheli (:ghuser:`lmicheli`)
* Echedey Luis (:ghuser:`echedey-ls`)
* Rajiv Daxini (:ghuser:`RDaxini`)
-
diff --git a/pvlib/atmosphere.py b/pvlib/atmosphere.py
index 08e40b9fc2..5b7ffff4ee 100644
--- a/pvlib/atmosphere.py
+++ b/pvlib/atmosphere.py
@@ -1,6 +1,7 @@
"""
The ``atmosphere`` module contains methods to calculate relative and
-absolute airmass and to determine pressure from altitude or vice versa.
+absolute airmass, determine pressure from altitude or vice versa, and wind
+speed at different heights.
"""
import numpy as np
@@ -533,3 +534,158 @@ def angstrom_alpha(aod1, lambda1, aod2, lambda2):
pvlib.atmosphere.angstrom_aod_at_lambda
"""
return - np.log(aod1 / aod2) / np.log(lambda1 / lambda2)
+
+
+# Values of the Hellmann exponent
+HELLMANN_SURFACE_EXPONENTS = {
+ 'unstable_air_above_open_water_surface': 0.06,
+ 'neutral_air_above_open_water_surface': 0.10,
+ 'stable_air_above_open_water_surface': 0.27,
+ 'unstable_air_above_flat_open_coast': 0.11,
+ 'neutral_air_above_flat_open_coast': 0.16,
+ 'stable_air_above_flat_open_coast': 0.40,
+ 'unstable_air_above_human_inhabited_areas': 0.27,
+ 'neutral_air_above_human_inhabited_areas': 0.34,
+ 'stable_air_above_human_inhabited_areas': 0.60,
+}
+
+
+def windspeed_powerlaw(wind_speed_reference, height_reference,
+ height_desired, exponent=None,
+ surface_type=None):
+ r"""
+ Estimate wind speed for different heights.
+
+ The model is based on the power law equation by Hellmann [1]_ [2]_.
+
+ Parameters
+ ----------
+ wind_speed_reference : numeric
+ Measured wind speed. [m/s]
+
+ height_reference : float
+ The height above ground at which the wind speed is measured. [m]
+
+ height_desired : float
+ The height above ground at which the wind speed will be estimated. [m]
+
+ exponent : float, optional
+ Exponent based on the surface type. [unitless]
+
+ surface_type : string, optional
+ If supplied, overrides ``exponent``. Can be one of the following
+ (see [1]_):
+
+ * ``'unstable_air_above_open_water_surface'``
+ * ``'neutral_air_above_open_water_surface'``
+ * ``'stable_air_above_open_water_surface'``
+ * ``'unstable_air_above_flat_open_coast'``
+ * ``'neutral_air_above_flat_open_coast'``
+ * ``'stable_air_above_flat_open_coast'``
+ * ``'unstable_air_above_human_inhabited_areas'``
+ * ``'neutral_air_above_human_inhabited_areas'``
+ * ``'stable_air_above_human_inhabited_areas'``
+
+ Returns
+ -------
+ wind_speed : numeric
+ Adjusted wind speed for the desired height. [m/s]
+
+ Raises
+ ------
+ ValueError
+ If neither of ``exponent`` nor a ``surface_type`` is given.
+ If both ``exponent`` and a ``surface_type`` is given. These parameters
+ are mutually exclusive.
+
+ KeyError
+ If the specified ``surface_type`` is invalid.
+
+ Notes
+ -----
+ Module temperature functions often require wind speeds at a height of 10 m
+ and not the wind speed at the module height.
+
+ For example, the following temperature functions require the input wind
+ speed to be 10 m: :py:func:`~pvlib.temperature.sapm_cell`, and
+ :py:func:`~pvlib.temperature.sapm_module` whereas the
+ :py:func:`~pvlib.temperature.fuentes` model requires wind speed at 9.144 m.
+
+ Additionally, the heat loss coefficients of some models have been developed
+ for wind speed measurements at 10 m (e.g.,
+ :py:func:`~pvlib.temperature.pvsyst_cell`,
+ :py:func:`~pvlib.temperature.faiman`, and
+ :py:func:`~pvlib.temperature.faiman_rad`).
+
+ The equation for calculating the wind speed at a height of :math:`h` is
+ given by the following power law equation [1]_ [2]_:
+
+ .. math::
+ :label: wind speed
+
+ WS_{h} = WS_{ref} \cdot \left( \frac{h}{h_{ref}} \right)^a
+
+ where :math:`h` [m] is the height at which we would like to calculate the
+ wind speed, :math:`h_{ref}` [m] is the reference height at which the wind
+ speed is known, and :math:`WS_{h}` [m/s] and :math:`WS_{ref}`
+ [m/s] are the corresponding wind speeds at these heights. The exponent
+ :math:`a` [unitless] depends on the surface type. Some values found in the
+ literature [1]_ for :math:`a` are:
+
+ .. table:: Values for the Hellmann-exponent
+
+ +-----------+--------------------+------------------+------------------+
+ | Stability | Open water surface | Flat, open coast | Cities, villages |
+ +===========+====================+==================+==================+
+ | Unstable | 0.06 | 0.10 | 0.27 |
+ +-----------+--------------------+------------------+------------------+
+ | Neutral | 0.11 | 0.16 | 0.40 |
+ +-----------+--------------------+------------------+------------------+
+ | Stable | 0.27 | 0.34 | 0.60 |
+ +-----------+--------------------+------------------+------------------+
+
+ In a report by Sandia [3]_, the equation was experimentally tested for a
+ height of 30 ft (:math:`h_{ref} = 9.144` [m]) at their test site in
+ Albuquerque for a period of six weeks where a coefficient of
+ :math:`a = 0.219` was calculated.
+
+ It should be noted that the equation returns a value of NaN if the
+ reference heights or wind speed are negative.
+
+ References
+ ----------
+ .. [1] Kaltschmitt M., Streicher W., Wiese A. (2007). "Renewable Energy:
+ Technology, Economics and Environment." Springer,
+ :doi:`10.1007/3-540-70949-5`.
+
+ .. [2] Hellmann G. (1915). "Über die Bewegung der Luft in den untersten
+ Schichten der Atmosphäre." Meteorologische Zeitschrift, 32
+
+ .. [3] Menicucci D.F., Hall I.J. (1985). "Estimating wind speed as a
+ function of height above ground: An analysis of data obtained at the
+ southwest residential experiment station, Las Cruses, New Mexico."
+ SAND84-2530, Sandia National Laboratories.
+ Accessed at:
+ https://web.archive.org/web/20230418202422/https://www2.jpl.nasa.gov/adv_tech/photovol/2016CTR/SNL%20-%20Est%20Wind%20Speed%20vs%20Height_1985.pdf
+ """ # noqa:E501
+ if surface_type is not None and exponent is None:
+ # use the Hellmann exponent from dictionary
+ exponent = HELLMANN_SURFACE_EXPONENTS[surface_type]
+ elif surface_type is None and exponent is not None:
+ # use the provided exponent
+ pass
+ else:
+ raise ValueError(
+ "Either a 'surface_type' or an 'exponent' parameter must be given")
+
+ wind_speed = wind_speed_reference * (
+ (height_desired / height_reference) ** exponent)
+
+ # if wind speed is negative or complex return NaN
+ wind_speed = np.where(np.iscomplex(wind_speed) | (wind_speed < 0),
+ np.nan, wind_speed)
+
+ if isinstance(wind_speed_reference, pd.Series):
+ wind_speed = pd.Series(wind_speed, index=wind_speed_reference.index)
+
+ return wind_speed
| diff --git a/pvlib/tests/test_atmosphere.py b/pvlib/tests/test_atmosphere.py
index 46db622ee5..e12a41dc6d 100644
--- a/pvlib/tests/test_atmosphere.py
+++ b/pvlib/tests/test_atmosphere.py
@@ -131,3 +131,74 @@ def test_bird_hulstrom80_aod_bb():
aod380, aod500 = 0.22072480948195175, 0.1614279181106312
bird_hulstrom = atmosphere.bird_hulstrom80_aod_bb(aod380, aod500)
assert np.isclose(0.11738229553812768, bird_hulstrom)
+
+
+@pytest.fixture
+def windspeeds_data_powerlaw():
+ data = pd.DataFrame(
+ index=pd.date_range(start="2015-01-01 00:00", end="2015-01-01 05:00",
+ freq="1h"),
+ columns=["wind_ref", "height_ref", "height_desired", "wind_calc"],
+ data=[
+ (10, -2, 5, np.nan),
+ (-10, 2, 5, np.nan),
+ (5, 4, 5, 5.067393209486324),
+ (7, 6, 10, 7.2178684911195905),
+ (10, 8, 20, 10.565167835216586),
+ (12, 10, 30, 12.817653329393977)
+ ]
+ )
+ return data
+
+
+def test_windspeed_powerlaw_ndarray(windspeeds_data_powerlaw):
+ # test wind speed estimation by passing in surface_type
+ result_surface = atmosphere.windspeed_powerlaw(
+ windspeeds_data_powerlaw["wind_ref"].to_numpy(),
+ windspeeds_data_powerlaw["height_ref"],
+ windspeeds_data_powerlaw["height_desired"],
+ surface_type='unstable_air_above_open_water_surface')
+ assert_allclose(windspeeds_data_powerlaw["wind_calc"].to_numpy(),
+ result_surface)
+ # test wind speed estimation by passing in the exponent corresponding
+ # to the surface_type above
+ result_exponent = atmosphere.windspeed_powerlaw(
+ windspeeds_data_powerlaw["wind_ref"].to_numpy(),
+ windspeeds_data_powerlaw["height_ref"],
+ windspeeds_data_powerlaw["height_desired"],
+ exponent=0.06)
+ assert_allclose(windspeeds_data_powerlaw["wind_calc"].to_numpy(),
+ result_exponent)
+
+
+def test_windspeed_powerlaw_series(windspeeds_data_powerlaw):
+ result = atmosphere.windspeed_powerlaw(
+ windspeeds_data_powerlaw["wind_ref"],
+ windspeeds_data_powerlaw["height_ref"],
+ windspeeds_data_powerlaw["height_desired"],
+ surface_type='unstable_air_above_open_water_surface')
+ assert_series_equal(windspeeds_data_powerlaw["wind_calc"],
+ result, check_names=False)
+
+
+def test_windspeed_powerlaw_invalid():
+ with pytest.raises(ValueError, match="Either a 'surface_type' or an "
+ "'exponent' parameter must be given"):
+ # no exponent or surface_type given
+ atmosphere.windspeed_powerlaw(wind_speed_reference=10,
+ height_reference=5,
+ height_desired=10)
+ with pytest.raises(ValueError, match="Either a 'surface_type' or an "
+ "'exponent' parameter must be given"):
+ # no exponent or surface_type given
+ atmosphere.windspeed_powerlaw(wind_speed_reference=10,
+ height_reference=5,
+ height_desired=10,
+ exponent=1.2,
+ surface_type="surf")
+ with pytest.raises(KeyError, match='not_an_exponent'):
+ # invalid surface_type
+ atmosphere.windspeed_powerlaw(wind_speed_reference=10,
+ height_reference=5,
+ height_desired=10,
+ surface_type='not_an_exponent')
| diff --git a/docs/sphinx/source/reference/airmass_atmospheric.rst b/docs/sphinx/source/reference/airmass_atmospheric.rst
index fbd33a5f28..384c345aec 100644
--- a/docs/sphinx/source/reference/airmass_atmospheric.rst
+++ b/docs/sphinx/source/reference/airmass_atmospheric.rst
@@ -17,3 +17,4 @@ Airmass and atmospheric models
atmosphere.kasten96_lt
atmosphere.angstrom_aod_at_lambda
atmosphere.angstrom_alpha
+ atmosphere.windspeed_powerlaw
diff --git a/docs/sphinx/source/whatsnew/v0.11.1.rst b/docs/sphinx/source/whatsnew/v0.11.1.rst
index 4ccc9687c3..3197882d93 100644
--- a/docs/sphinx/source/whatsnew/v0.11.1.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.1.rst
@@ -17,6 +17,9 @@ Enhancements
:py:func:`pvlib.spectrum.spectral_factor_firstsolar`.
(:issue:`2086`, :pull:`2100`)
+* Added function for calculating wind speed at different heights,
+ :py:func:`pvlib.atmosphere.windspeed_powerlaw`.
+ (:issue:`2118`, :pull:`2124`)
Bug fixes
~~~~~~~~~
@@ -45,4 +48,3 @@ Contributors
* Leonardo Micheli (:ghuser:`lmicheli`)
* Echedey Luis (:ghuser:`echedey-ls`)
* Rajiv Daxini (:ghuser:`RDaxini`)
-
| [
{
"components": [
{
"doc": "Estimate wind speed for different heights.\n\nThe model is based on the power law equation by Hellmann [1]_ [2]_.\n\nParameters\n----------\nwind_speed_reference : numeric\n Measured wind speed. [m/s]\n\nheight_reference : float\n The height above ground at which ... | [
"pvlib/tests/test_atmosphere.py::test_windspeed_powerlaw_ndarray",
"pvlib/tests/test_atmosphere.py::test_windspeed_powerlaw_series",
"pvlib/tests/test_atmosphere.py::test_windspeed_powerlaw_invalid"
] | [
"pvlib/tests/test_atmosphere.py::test_pres2alt",
"pvlib/tests/test_atmosphere.py::test_alt2pres",
"pvlib/tests/test_atmosphere.py::test_airmass[simple-expected0]",
"pvlib/tests/test_atmosphere.py::test_airmass[kasten1966-expected1]",
"pvlib/tests/test_atmosphere.py::test_airmass[youngirvine1967-expected2]",... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Function to estimate wind speed at different heights
- [X] Closes #2118
- [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.
The wind speed at different heights is calculated using the Hellmann power law expression ([source 1](https://link-springer-com.proxy.findit.cvt.dk/book/10.1007/3-540-70949-5), [source 2](https://en.wikipedia.org/wiki/Wind_gradient)). The Sandia method (discussed in #2118) is a subcase of this model, so it was added in the notes as a possible coefficient combination that could be used by the user.
----------
</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/atmosphere.py]
(definition of windspeed_powerlaw:)
def windspeed_powerlaw(wind_speed_reference, height_reference, height_desired, exponent=None, surface_type=None):
"""Estimate wind speed for different heights.
The model is based on the power law equation by Hellmann [1]_ [2]_.
Parameters
----------
wind_speed_reference : numeric
Measured wind speed. [m/s]
height_reference : float
The height above ground at which the wind speed is measured. [m]
height_desired : float
The height above ground at which the wind speed will be estimated. [m]
exponent : float, optional
Exponent based on the surface type. [unitless]
surface_type : string, optional
If supplied, overrides ``exponent``. Can be one of the following
(see [1]_):
* ``'unstable_air_above_open_water_surface'``
* ``'neutral_air_above_open_water_surface'``
* ``'stable_air_above_open_water_surface'``
* ``'unstable_air_above_flat_open_coast'``
* ``'neutral_air_above_flat_open_coast'``
* ``'stable_air_above_flat_open_coast'``
* ``'unstable_air_above_human_inhabited_areas'``
* ``'neutral_air_above_human_inhabited_areas'``
* ``'stable_air_above_human_inhabited_areas'``
Returns
-------
wind_speed : numeric
Adjusted wind speed for the desired height. [m/s]
Raises
------
ValueError
If neither of ``exponent`` nor a ``surface_type`` is given.
If both ``exponent`` and a ``surface_type`` is given. These parameters
are mutually exclusive.
KeyError
If the specified ``surface_type`` is invalid.
Notes
-----
Module temperature functions often require wind speeds at a height of 10 m
and not the wind speed at the module height.
For example, the following temperature functions require the input wind
speed to be 10 m: :py:func:`~pvlib.temperature.sapm_cell`, and
:py:func:`~pvlib.temperature.sapm_module` whereas the
:py:func:`~pvlib.temperature.fuentes` model requires wind speed at 9.144 m.
Additionally, the heat loss coefficients of some models have been developed
for wind speed measurements at 10 m (e.g.,
:py:func:`~pvlib.temperature.pvsyst_cell`,
:py:func:`~pvlib.temperature.faiman`, and
:py:func:`~pvlib.temperature.faiman_rad`).
The equation for calculating the wind speed at a height of :math:`h` is
given by the following power law equation [1]_ [2]_:
.. math::
:label: wind speed
WS_{h} = WS_{ref} \cdot \left( \frac{h}{h_{ref}} \right)^a
where :math:`h` [m] is the height at which we would like to calculate the
wind speed, :math:`h_{ref}` [m] is the reference height at which the wind
speed is known, and :math:`WS_{h}` [m/s] and :math:`WS_{ref}`
[m/s] are the corresponding wind speeds at these heights. The exponent
:math:`a` [unitless] depends on the surface type. Some values found in the
literature [1]_ for :math:`a` are:
.. table:: Values for the Hellmann-exponent
+-----------+--------------------+------------------+------------------+
| Stability | Open water surface | Flat, open coast | Cities, villages |
+===========+====================+==================+==================+
| Unstable | 0.06 | 0.10 | 0.27 |
+-----------+--------------------+------------------+------------------+
| Neutral | 0.11 | 0.16 | 0.40 |
+-----------+--------------------+------------------+------------------+
| Stable | 0.27 | 0.34 | 0.60 |
+-----------+--------------------+------------------+------------------+
In a report by Sandia [3]_, the equation was experimentally tested for a
height of 30 ft (:math:`h_{ref} = 9.144` [m]) at their test site in
Albuquerque for a period of six weeks where a coefficient of
:math:`a = 0.219` was calculated.
It should be noted that the equation returns a value of NaN if the
reference heights or wind speed are negative.
References
----------
.. [1] Kaltschmitt M., Streicher W., Wiese A. (2007). "Renewable Energy:
Technology, Economics and Environment." Springer,
:doi:`10.1007/3-540-70949-5`.
.. [2] Hellmann G. (1915). "Über die Bewegung der Luft in den untersten
Schichten der Atmosphäre." Meteorologische Zeitschrift, 32
.. [3] Menicucci D.F., Hall I.J. (1985). "Estimating wind speed as a
function of height above ground: An analysis of data obtained at the
southwest residential experiment station, Las Cruses, New Mexico."
SAND84-2530, Sandia National Laboratories.
Accessed at:
https://web.archive.org/web/20230418202422/https://www2.jpl.nasa.gov/adv_tech/photovol/2016CTR/SNL%20-%20Est%20Wind%20Speed%20vs%20Height_1985.pdf"""
[end of new definitions in pvlib/atmosphere.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>
Expression for calculating wind speed at different heights
Most times, the wind speed provided in weather files is measured at a height of 10 m. However, in many cases it is required to estimate the wind speed at panel height. Which equation should be used in order to do this?
I found this issue (#1814), which mentions an equation from a Sandia report (I couldn't find the report, though... some help from Sandia people? @cwhanse @kandersolar). This is what is mentioned:
`Estimate wind speed at module height - use technique developed by menicucci and hall (sand84-2530) */`
`windmd=ws2*pow(height/9.144,0.2) + 0.0001`
And then there is the expression used in wind engineering, described [here](https://en.wikipedia.org/wiki/Wind_gradient) (for a more official reference, it is also mentioned in the book by Siegfried Heier (2014), Grid Integration of Wind Energy Conversion Systems (publisher: Wiley))
I am willing to take up the task of making the PR, etc., but first, I would like to know your thoughts on which expression should be added (maybe both?) or if there is some other equation you think is more relevant.
----------
Here is a public copy of SAND 84-2530: https://web.archive.org/web/20230418202422/https://www2.jpl.nasa.gov/adv_tech/photovol/2016CTR/SNL%20-%20Est%20Wind%20Speed%20vs%20Height_1985.pdf
A word of caution here: some temperature model coefficients (e.g. those for the SAPM) implicitly account for the difference between anemometer and PV module height above ground. They do so by regressing measured module temperature to wind speed at 10m.
The proposed function is worth adding but I would be cautious about suggesting it needs to be in a PV modeling pipeline.
> A word of caution here: some temperature model coefficients (e.g. those for the SAPM) implicitly account for the difference between anemometer and PV module height above ground. They do so by regressing measured module temperature to wind speed at 10m.
Great insight @cwhanse. Let's add this info in a warning admonition for the proposed wind speed function.
Probably worth checking out if there is similar functionality in metpy.
Good point, @cwhanse! From a quick search, I can see that only the SAPM models and the generic_linear require the wind speed at 10 m as an input. The rest of the temperature models either require wind speed at module height or don't specify (e.g., Fuentes), but I would still imagine it requires at module height...
I agree with @cwhanse we we need to tread cautiously because in my experience there is already a lot of misunderstanding about correlation coefficients and their relation to wind speed height measurements.
1. I emphasize what Cliff says: correlation coefficients like `Uc = 25 W/m2/K` and `Uv = 1.2 W/m2/K/(m/s)` require and depend on wind speed measured at 10-m. So if wind speeds were measured at array height, eg 2-m, a function such as the one proposed could be helpful in estimating wind speed at 10-m
2. Ideally I would prefer to see a discussion added to the documentation explaining why free stream velocity measurements are preferred and used in temperature correlations, before adding new functions
3. I have most frequently seen a power law but there is often debate over what exponent to use. Eg: `Uw(10m) = Uw(2m)*(10m/2m)^n` where `n` is the exponent. Other methods may be more accurate but I’m not familiar with them. I also don’t have a reference for this or know the history why it’s so prevalent
This is my view on the subject:
> B. Wind speed
>
>Each model has a coefficient that multiplies wind speed. In practice, wind speed increases with height above the ground in a non-linear manner, therefore the model coefficients are valid for a specific combination of module installation height and wind speed measurement height. The Faiman model coefficients and NOCT values are typically determined using wind speed measured near module height, but the modules are not necessarily near ground level. SAPM and PVsyst coefficients are specified for use with wind speed data at the standard 10 m height, but that information is only useful if the module height corresponding to those coefficients is also clearly specified.
>
>To accommodate a different installation or measurement height, either the wind speed data or the wind speed coefficient can be adjusted. The basis for such an adjustment is often either the log law or the power law which describe the wind speed profile as a function of height using an empirical parameter related to the surface roughness; **however, these profiles are not applicable close to the ground or close to the level of the objects that contribute to the roughness.** [12] For the adjustment from 10 m to 2 m, a nominal height for a ground-mounted array, some reduction ratios found in the literature are: 0.51 [7], 0.56 [13], 0.67 [14] and 0.725 [15]. This range gives an indication of the level of uncertainty associated with such adjustments.
>
>The SAM NOCT model uses a predetermined factor of 0.51 to reduce 10 m wind speed data to ground-mounted, module-level wind speed, but unfortunately the origin of this value is undocumented. The need for adjustments with other models to or from different heights should be evaluated by the user of the models on a case by case basis taking into consideration the both the source of the empirical parameters and the source of the wind speed data.
Thanks Anton! Can we get those references?
Here is a link to my temperature model equivalence paper that contains the above excerpt:
https://www.osti.gov/biblio/2003640
Thanks Anton. So I think there is a case for pvlib to include an expression to account for wind speed height measurement, but IMO. I still think the documentation takes precedence so that folks don’t misuse it. In particular I’d like to see a table of weather resources that shows the wind speed height. Eg ground campaigns most often measure at about 3-m while satellite is usually at 10-m. Also a corresponding table of temperature models. Finally some gallery examples that show when and how an adjustment should be made. My personal preference is to adjust the wind coefficient rather than the wind speed measurements which is associative (ie: `Uv’ * Uw = Uv * adj * Uw = Uv * Uw’` in which prime indicates adjustment. Also a discussion of uncertainty would be useful.
I think this is another area where the PV modellers are just muddling along. Someone needs to access a large amount of data and do some thorough analysis in order to develop some well-founded correlations that are useful for PV systems!
--------------------
</issues> | 6af80da35a7c96059c534ee38be9123bcfc7f50f |
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... | [
"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... | [] | 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} containi... | [
"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 ... | [
"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_cu... | 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 | |
conan-io__conan-16613 | 16,613 | conan-io/conan | null | 3c72e2a83b468bb0d18e958c7e160fbb324b146e | 2024-07-04T20:02:53Z | diff --git a/conan/tools/gnu/makedeps.py b/conan/tools/gnu/makedeps.py
index c3d0017b988..d02cc353404 100644
--- a/conan/tools/gnu/makedeps.py
+++ b/conan/tools/gnu/makedeps.py
@@ -30,7 +30,9 @@
import textwrap
from jinja2 import Template, StrictUndefined
+from typing import Optional
+from conan.api.output import ConanOutput
from conan.internal import check_duplicated_generator
from conan.tools.files import save
@@ -67,6 +69,30 @@ def _makefy(name: str) -> str:
return re.sub(r'[^0-9A-Z_]', '_', name.upper())
+def _makefy_properties(properties: Optional[dict]) -> dict:
+ """
+ Convert property dictionary keys to Make-variable-friendly syntax
+ :param properties: The property dictionary to be converted (None is also accepted)
+ :return: Modified property dictionary with keys not including bad characters that are not parsed correctly
+ """
+ return {_makefy(name): value for name, value in properties.items()} if properties else {}
+
+def _check_property_value(name, value, output):
+ if "\n" in value:
+ output.warning(f"Skipping propery '{name}' because it contains newline")
+ return False
+ else:
+ return True
+
+def _filter_properties(properties: Optional[dict], output) -> dict:
+ """
+ Filter out properties whose values contain newlines, because they would break the generated makefile
+ :param properties: A property dictionary (None is also accepted)
+ :return: A property dictionary without the properties containing newlines
+ """
+ return {name: value for name, value in properties.items() if _check_property_value(name, value, output)} if properties else {}
+
+
def _conan_prefix_flag(variable: str) -> str:
"""
Return a global flag to be used as prefix to any value in the makefile
@@ -131,6 +157,12 @@ def _jinja_format_list_values() -> str:
{%- endif -%}
{%- endmacro %}
+ {%- macro define_multiple_variable_value(var, values) -%}
+ {% for property_name, value in values.items() %}
+ {{ var }}_{{ property_name }} = {{ value }}
+ {% endfor %}
+ {%- endmacro %}
+
{%- macro define_variable_value(var, values) -%}
{%- if values is not none -%}
{%- if values|length > 0 -%}
@@ -332,9 +364,10 @@ class DepComponentContentGenerator:
{{- define_variable_value_safe("CONAN_FRAMEWORKS_{}_{}".format(dep_name, name), cpp_info_flags, 'frameworks') -}}
{{- define_variable_value_safe("CONAN_REQUIRES_{}_{}".format(dep_name, name), cpp_info_flags, 'requires') -}}
{{- define_variable_value_safe("CONAN_SYSTEM_LIBS_{}_{}".format(dep_name, name), cpp_info_flags, 'system_libs') -}}
+ {{- define_multiple_variable_value("CONAN_PROPERTY_{}_{}".format(dep_name, name), properties) -}}
""")
- def __init__(self, dependency, component_name: str, dirs: dict, flags: dict):
+ def __init__(self, dependency, component_name: str, dirs: dict, flags: dict, output):
"""
:param dependency: The dependency object that owns the component
:param component_name: component raw name e.g. poco::poco_json
@@ -345,6 +378,7 @@ def __init__(self, dependency, component_name: str, dirs: dict, flags: dict):
self._name = component_name
self._dirs = dirs or {}
self._flags = flags or {}
+ self._output = output
def content(self) -> str:
"""
@@ -356,7 +390,8 @@ def content(self) -> str:
"dep_name": _makefy(self._dep.ref.name),
"name": _makefy(self._name),
"cpp_info_dirs": self._dirs,
- "cpp_info_flags": self._flags
+ "cpp_info_flags": self._flags,
+ "properties": _makefy_properties(_filter_properties(self._dep.cpp_info.components[self._name]._properties, self._output)),
}
template = Template(_jinja_format_list_values() + self.template, trim_blocks=True,
lstrip_blocks=True, undefined=StrictUndefined)
@@ -397,15 +432,17 @@ class DepContentGenerator:
{{- define_variable_value_safe("CONAN_REQUIRES_{}".format(name), cpp_info_flags, 'requires') -}}
{{- define_variable_value_safe("CONAN_SYSTEM_LIBS_{}".format(name), cpp_info_flags, 'system_libs') -}}
{{- define_variable_value("CONAN_COMPONENTS_{}".format(name), components) -}}
+ {{- define_multiple_variable_value("CONAN_PROPERTY_{}".format(name), properties) -}}
""")
- def __init__(self, dependency, require, root: str, sysroot, dirs: dict, flags: dict):
+ def __init__(self, dependency, require, root: str, sysroot, dirs: dict, flags: dict, output):
self._dep = dependency
self._req = require
self._root = root
self._sysroot = sysroot
self._dirs = dirs or {}
self._flags = flags or {}
+ self._output = output
def content(self) -> str:
"""
@@ -420,6 +457,7 @@ def content(self) -> str:
"components": list(self._dep.cpp_info.get_sorted_components().keys()),
"cpp_info_dirs": self._dirs,
"cpp_info_flags": self._flags,
+ "properties": _makefy_properties(_filter_properties(self._dep.cpp_info._properties, self._output)),
}
template = Template(_jinja_format_list_values() + self.template, trim_blocks=True,
lstrip_blocks=True, undefined=StrictUndefined)
@@ -431,7 +469,7 @@ class DepComponentGenerator:
Generates Makefile content for a dependency component
"""
- def __init__(self, dependency, makeinfo: MakeInfo, component_name: str, component, root: str):
+ def __init__(self, dependency, makeinfo: MakeInfo, component_name: str, component, root: str, output):
"""
:param dependency: The dependency object that owns the component
:param makeinfo: Makeinfo to store component variables
@@ -444,6 +482,7 @@ def __init__(self, dependency, makeinfo: MakeInfo, component_name: str, componen
self._comp = component
self._root = root
self._makeinfo = makeinfo
+ self._output = output
def _get_component_dirs(self) -> dict:
"""
@@ -500,7 +539,7 @@ def generate(self) -> str:
"""
dirs = self._get_component_dirs()
flags = self._get_component_flags()
- comp_content_gen = DepComponentContentGenerator(self._dep, self._name, dirs, flags)
+ comp_content_gen = DepComponentContentGenerator(self._dep, self._name, dirs, flags, self._output)
comp_content = comp_content_gen.content()
return comp_content
@@ -510,10 +549,11 @@ class DepGenerator:
Process a dependency cpp_info variables and generate its Makefile content
"""
- def __init__(self, dependency, require):
+ def __init__(self, dependency, require, output):
self._dep = dependency
self._req = require
self._info = MakeInfo(self._dep.ref.name, [], [])
+ self._output = output
@property
def makeinfo(self) -> MakeInfo:
@@ -585,11 +625,11 @@ def generate(self) -> str:
sysroot = self._get_sysroot(root)
dirs = self._get_dependency_dirs(root, self._dep)
flags = self._get_dependency_flags(self._dep)
- dep_content_gen = DepContentGenerator(self._dep, self._req, root, sysroot, dirs, flags)
+ dep_content_gen = DepContentGenerator(self._dep, self._req, root, sysroot, dirs, flags, self._output)
content = dep_content_gen.content()
for comp_name, comp in self._dep.cpp_info.get_sorted_components().items():
- component_gen = DepComponentGenerator(self._dep, self._info, comp_name, comp, root)
+ component_gen = DepComponentGenerator(self._dep, self._info, comp_name, comp, root, self._output)
content += component_gen.generate()
return content
@@ -630,8 +670,8 @@ def generate(self) -> None:
# Require is not used at the moment, but its information could be used, and will be used in Conan 2.0
if require.build:
continue
-
- dep_gen = DepGenerator(dep, require)
+ output = ConanOutput(scope=f"{self._conanfile} MakeDeps: {dep}:")
+ dep_gen = DepGenerator(dep, require, output)
make_infos.append(dep_gen.makeinfo)
deps_buffer += dep_gen.generate()
| diff --git a/test/integration/toolchains/gnu/test_makedeps.py b/test/integration/toolchains/gnu/test_makedeps.py
index 948174280b1..31fd5d3a6fd 100644
--- a/test/integration/toolchains/gnu/test_makedeps.py
+++ b/test/integration/toolchains/gnu/test_makedeps.py
@@ -30,6 +30,8 @@ def package_info(self):
lib_dir2 = os.path.join(self.package_folder, "lib2")
self.cpp_info.includedirs = [include_dir]
self.cpp_info.libdirs = [lib_dir, lib_dir2]
+ self.cpp_info.set_property("my_prop", "my prop value")
+ self.cpp_info.set_property("my_prop_with_newline", "my\\nprop")
""")
client = TestClient()
client.save({"conanfile.py": conanfile})
@@ -44,6 +46,9 @@ def package_info(self):
assert f'CONAN_LIB_DIRS_MYLIB = \\\n\t$(CONAN_LIB_DIR_FLAG){prefix}/my_absoulte_path/fake/mylib/lib \\\n\t$(CONAN_LIB_DIR_FLAG)$(CONAN_ROOT_MYLIB)/lib2' in makefile_content
assert f'CONAN_INCLUDE_DIRS_MYLIB = $(CONAN_INCLUDE_DIR_FLAG){prefix}/my_absoulte_path/fake/mylib/include' in makefile_content
assert 'CONAN_BIN_DIRS_MYLIB = $(CONAN_BIN_DIR_FLAG)$(CONAN_ROOT_MYLIB)/bin' in makefile_content
+ assert 'CONAN_PROPERTY_MYLIB_MY_PROP = my prop value' in makefile_content
+ assert 'CONAN_PROPERTY_MYLIB_MY_PROP_WITH_NEWLINE' not in makefile_content
+ assert "WARN: Skipping propery 'my_prop_with_newline' because it contains newline" in client.stderr
lines = makefile_content.splitlines()
for line_no, line in enumerate(lines):
@@ -90,6 +95,7 @@ def package_info(self):
assert 'CONAN_BIN_DIRS' not in makefile_content
assert 'CONAN_LIBS' not in makefile_content
assert 'CONAN_FRAMEWORK_DIRS' not in makefile_content
+ assert 'CONAN_PROPERTY' not in makefile_content
def test_libs_and_system_libs():
@@ -197,6 +203,8 @@ class TestMakeDepsConan(ConanFile):
def package_info(self):
self.cpp_info.components["mycomponent"].requires.append("lib::cmp1")
self.cpp_info.components["myfirstcomp"].requires.append("mycomponent")
+ self.cpp_info.components["myfirstcomp"].set_property("my_prop", "my prop value")
+ self.cpp_info.components["myfirstcomp"].set_property("my_prop_with_newline", "my\\nprop")
""")
client.save({"conanfile.py": conanfile}, clean_first=True)
@@ -236,6 +244,10 @@ def package_info(self):
assert 'CONAN_REQUIRES = $(CONAN_REQUIRES_SECOND)\n' in makefile_content
assert 'CONAN_LIBS = $(CONAN_LIBS_LIB)\n' in makefile_content
+ assert 'CONAN_PROPERTY_SECOND_MYFIRSTCOMP_MY_PROP = my prop value\n' in makefile_content
+ assert 'CONAN_PROPERTY_SECOND_MYFIRSTCOMP_MY_PROP_WITH_NEWLINE' not in makefile_content
+ assert "WARN: Skipping propery 'my_prop_with_newline' because it contains newline" in client2.stderr
+
def test_make_with_public_deps_and_component_requires_second():
"""
| [
{
"components": [
{
"doc": "Convert property dictionary keys to Make-variable-friendly syntax\n:param properties: The property dictionary to be converted (None is also accepted)\n:return: Modified property dictionary with keys not including bad characters that are not parsed correctly",
"l... | [
"test/integration/toolchains/gnu/test_makedeps.py::test_make_dirs_with_abs_path",
"test/integration/toolchains/gnu/test_makedeps.py::test_make_with_public_deps_and_component_requires"
] | [
"test/integration/toolchains/gnu/test_makedeps.py::test_make_empty_dirs",
"test/integration/toolchains/gnu/test_makedeps.py::test_libs_and_system_libs",
"test/integration/toolchains/gnu/test_makedeps.py::test_multiple_include_and_lib_dirs",
"test/integration/toolchains/gnu/test_makedeps.py::test_make_with_pub... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add properties to MakeDeps generator
Changelog: Feature: MakeDeps generator generates make variables for dependencies and their components.
Docs: https://github.com/conan-io/docs/pull/3794
Fixes #16572
----------
</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/makedeps.py]
(definition of _makefy_properties:)
def _makefy_properties(properties: Optional[dict]) -> dict:
"""Convert property dictionary keys to Make-variable-friendly syntax
:param properties: The property dictionary to be converted (None is also accepted)
:return: Modified property dictionary with keys not including bad characters that are not parsed correctly"""
(definition of _check_property_value:)
def _check_property_value(name, value, output):
(definition of _filter_properties:)
def _filter_properties(properties: Optional[dict], output) -> dict:
"""Filter out properties whose values contain newlines, because they would break the generated makefile
:param properties: A property dictionary (None is also accepted)
:return: A property dictionary without the properties containing newlines """
[end of new definitions in conan/tools/gnu/makedeps.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>
[feature] Add properties to MakeDeps generator
### What is your suggestion?
I would like to access custom properties from GNU Make files generated by the MakeDeps generator. If the receipt defines custom properties in the `package_info()` method then those properties should appear as make variables, too. The pattern of the make variable would be
```
CONAN_PROPERTY_{dependency_name}_{property_name}
```
where both, `dependency_name` and `property_name` would be uppercase. Dots in `property_name` would be replaced by underscores.
Here is my first take: https://github.com/conan-io/conan/commit/19daca6aaebb3a4d4242e77686d1c2105ef04216
I am aware that in this implementation has the assumption that custom properties are always strings. Is there such a constraint. or can properties contain data of any type?
My questions:
- Would such kind of a merge request have any chance to be merged? (Of course with docs and tests etc.)
- Any ideas how to cope with non-string property values if they are allowed?
- Where should such a feature be documented?
- What kind of tests would make sense here?
### Have you read the CONTRIBUTING guide?
- [X] I've read the CONTRIBUTING guide
----------
On second thought I would drop the replacement of dots with underscores. Dots are valid charactes in GNU Make variable names.
Hi @vajdaz
Thanks for your suggestion
What would be exactly the use case? What kind of information are you propagating from dependencies to the consumers via properties?
The ``properties`` are intended to be mapped to somehow "native" things in the consumer build system. When a property like ``cmake_target_name`` is defined is because the CMake build system understand that thing.
I think this could be a valid request and probably can be moved forward, as it would be very low risk
> On second thought I would drop the replacement of dots with underscores. Dots are valid charactes in GNU Make variable names.
If there are other Make systems that this generator could be valid beyond GNU Make, then it might be worth using underscores.
Hi @memsharded ,
I have packages that contain more than one library files which have circular dependencies (let's imagine `liba.a` and `libb.a`). When you link such libraries, you must put them between appropriate linker options that make the linker iterate over them several times when the symbols are resolved. So instead of having the linking options
```
-L/my/lib/path -la -lb
```
you will have to use following linking options
```
-L/my/lib/path -Wl,--start-group -la -lb -Wl,--end-group
```
I signal this situation by means of a custom property. Currently I have a custom makefile generator that creates a makefile similar to what MakeDeps creates but additionally it creates variables for the custom properties. My build system integration receives the info about circular dependencies via this mechanism and can prepend/append the mentioned linker options.
In my current implementation I have a property for the linker options that should be prepended and appended. So in the receipt I have
```
def package_info(self):
# has circular dependencies
self.cpp_info.set_property("ldflags_prepend", "-Wl,--start-group")
self.cpp_info.set_property("ldflags_append", "-Wl,--end-group")
```
My generator creates the make variables `CONAN_PROPERTY_LDFLAGS_PREPEND_MYLIBNAME` and `CONAN_PROPERTY_LDFLAGS_APPEND_MYLIBNAME`. In the build system integration I use these variables to create the linker command (together with the well known other make variables, like `CONAN_LIB_DIRS_`, `CONAN_LIBS_`, etc.).
I am also aware that this is not very portable. I could abstract the linker options by having an abstract property
```
def package_info(self):
self.cpp_info.set_property("has_circular_dependencies", "True")
```
and let the build system decide what to do with this information.
But this details do not matter. The point is, I want to access custom property values set in the receipt in my GNU Make based build system to control linking behavior in special cases.
--------------------
</issues> | 4a5b19a75db9225316c8cb022a2dfb9705a2af34 | |
aws-cloudformation__cfn-lint-3464 | 3,464 | aws-cloudformation/cfn-lint | null | ee6271f76b681e64a97f02e28af4c514e1006a41 | 2024-07-04T17:00:21Z | diff --git a/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_cpu_memory.json b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_cpu_memory.json
new file mode 100644
index 0000000000..3fc18efad7
--- /dev/null
+++ b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_cpu_memory.json
@@ -0,0 +1,136 @@
+{
+ "if": {
+ "properties": {
+ "Cpu": {
+ "type": [
+ "string",
+ "integer"
+ ]
+ },
+ "Memory": {
+ "type": [
+ "string",
+ "integer"
+ ]
+ },
+ "RequiresCompatibilities": {
+ "contains": {
+ "enum": [
+ "FARGATE"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "RequiresCompatibilities",
+ "Cpu",
+ "Memory"
+ ]
+ },
+ "then": {
+ "anyOf": [
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "256"
+ ]
+ },
+ "Memory": {
+ "enum": [
+ "512",
+ "1024",
+ "2048"
+ ]
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "512"
+ ]
+ },
+ "Memory": {
+ "maximum": 4096,
+ "minimum": 1024,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "1024"
+ ]
+ },
+ "Memory": {
+ "maximum": 8192,
+ "minimum": 2048,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "2048"
+ ]
+ },
+ "Memory": {
+ "maximum": 16384,
+ "minimum": 4096,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "4096"
+ ]
+ },
+ "Memory": {
+ "maximum": 30720,
+ "minimum": 8192,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "8192"
+ ]
+ },
+ "Memory": {
+ "maximum": 61440,
+ "minimum": 16384,
+ "multipleOf": 4096
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "16384"
+ ]
+ },
+ "Memory": {
+ "maximum": 122880,
+ "minimum": 32768,
+ "multipleOf": 8192
+ }
+ }
+ }
+ ]
+ }
+}
diff --git a/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_properties.json b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_properties.json
new file mode 100644
index 0000000000..c590df4986
--- /dev/null
+++ b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_properties.json
@@ -0,0 +1,57 @@
+{
+ "if": {
+ "properties": {
+ "RequiresCompatibilities": {
+ "contains": {
+ "enum": [
+ "FARGATE"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "RequiresCompatibilities"
+ ]
+ },
+ "then": {
+ "if": {
+ "properties": {
+ "Cpu": {
+ "type": [
+ "string",
+ "integer"
+ ]
+ }
+ },
+ "required": [
+ "Cpu"
+ ]
+ },
+ "not": {
+ "required": [
+ "PlacementConstraints"
+ ]
+ },
+ "required": [
+ "Cpu",
+ "Memory"
+ ],
+ "then": {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "256",
+ "512",
+ "1024",
+ "2048",
+ "4096",
+ "8192",
+ "16384"
+ ]
+ }
+ }
+ }
+ }
+}
diff --git a/src/cfnlint/rules/resources/ecs/FargateCpuMemory.py b/src/cfnlint/rules/resources/ecs/FargateCpuMemory.py
new file mode 100644
index 0000000000..af5c7626c6
--- /dev/null
+++ b/src/cfnlint/rules/resources/ecs/FargateCpuMemory.py
@@ -0,0 +1,41 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import cfnlint.data.schemas.extensions.aws_ecs_taskdefinition
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.jsonschema.CfnLintJsonSchema import CfnLintJsonSchema, SchemaDetails
+
+
+class FargateCpuMemory(CfnLintJsonSchema):
+ id = "E3047"
+ shortdesc = (
+ "Validate ECS Fargate tasks have the right combination of CPU and memory"
+ )
+ description = (
+ "When using a ECS Fargate task there is a specfic combination "
+ "of memory and cpu that can be used"
+ )
+ source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-memory"
+ tags = ["properties", "ecs", "service", "container", "fargate"]
+
+ def __init__(self) -> None:
+ super().__init__(
+ keywords=["Resources/AWS::ECS::TaskDefinition/Properties"],
+ schema_details=SchemaDetails(
+ module=cfnlint.data.schemas.extensions.aws_ecs_taskdefinition,
+ filename="fargate_cpu_memory.json",
+ ),
+ )
+
+ def message(self, instance: Any, err: ValidationError) -> str:
+ return (
+ f"Cpu {instance.get('Cpu')!r} is not "
+ "compatible with memory "
+ f"{instance.get('Memory')!r}"
+ )
diff --git a/src/cfnlint/rules/resources/ecs/TaskFargateProperties.py b/src/cfnlint/rules/resources/ecs/TaskFargateProperties.py
new file mode 100644
index 0000000000..37cba5b5d7
--- /dev/null
+++ b/src/cfnlint/rules/resources/ecs/TaskFargateProperties.py
@@ -0,0 +1,46 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from typing import Any
+
+import cfnlint.data.schemas.extensions.aws_ecs_taskdefinition
+from cfnlint.jsonschema import ValidationResult
+from cfnlint.jsonschema.protocols import Validator
+from cfnlint.rules.jsonschema.CfnLintJsonSchema import CfnLintJsonSchema, SchemaDetails
+
+
+class TaskFargateProperties(CfnLintJsonSchema):
+ id = "E3048"
+ shortdesc = "Validate ECS Fargate tasks have required properties and values"
+ description = (
+ "When using a ECS Fargate task there is a specfic combination "
+ "of required properties and values"
+ )
+ source_url = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-memory"
+ tags = ["properties", "ecs", "service", "container", "fargate"]
+
+ def __init__(self) -> None:
+ super().__init__(
+ keywords=["Resources/AWS::ECS::TaskDefinition/Properties"],
+ schema_details=SchemaDetails(
+ module=cfnlint.data.schemas.extensions.aws_ecs_taskdefinition,
+ filename="fargate_properties.json",
+ ),
+ all_matches=True,
+ )
+
+ def validate(
+ self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any]
+ ) -> ValidationResult:
+ for err in super().validate(validator, keywords, instance, schema):
+ if err.validator == "not":
+ err.message = "'PlacementConstraints' isn't supported for Fargate tasks"
+ err.path = deque(["PlacementConstraints"])
+ yield err
+ continue
+ yield err
| diff --git a/test/unit/rules/resources/ecs/test_ecs_fargate_cpu_memory.py b/test/unit/rules/resources/ecs/test_ecs_fargate_cpu_memory.py
new file mode 100644
index 0000000000..7aacac0af5
--- /dev/null
+++ b/test/unit/rules/resources/ecs/test_ecs_fargate_cpu_memory.py
@@ -0,0 +1,132 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from collections import deque
+
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.resources.ecs.FargateCpuMemory import FargateCpuMemory
+
+
+@pytest.fixture(scope="module")
+def rule():
+ rule = FargateCpuMemory()
+ yield rule
+
+
+@pytest.mark.parametrize(
+ "instance,expected",
+ [
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 256,
+ "Memory": "512",
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": "512",
+ "Memory": 1024,
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": "1024",
+ "Memory": "2048",
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 2048,
+ "Memory": 4096,
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 4096,
+ "Memory": 30720,
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 8192,
+ "Memory": 16384,
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 16384,
+ "Memory": 122880,
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 16384,
+ "Memory": 123904,
+ },
+ [
+ ValidationError(
+ "Cpu 16384 is not compatible with memory 123904",
+ rule=FargateCpuMemory(),
+ path=deque([]),
+ validator="anyOf",
+ schema_path=deque(["then", "anyOf"]),
+ )
+ ],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE", "Foo"],
+ "Cpu": 4096,
+ "Memory": 512,
+ },
+ [
+ ValidationError(
+ "Cpu 4096 is not compatible with memory 512",
+ rule=FargateCpuMemory(),
+ path=deque([]),
+ validator="anyOf",
+ schema_path=deque(["then", "anyOf"]),
+ )
+ ],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE", "Foo"],
+ "Cpu": 4096,
+ "Memory": 16385,
+ },
+ [
+ ValidationError(
+ "Cpu 4096 is not compatible with memory 16385",
+ rule=FargateCpuMemory(),
+ path=deque([]),
+ validator="anyOf",
+ schema_path=deque(["then", "anyOf"]),
+ )
+ ],
+ ),
+ ],
+)
+def test_validate(instance, expected, rule, validator):
+ errs = list(rule.validate(validator, "", instance, {}))
+
+ assert errs == expected, f"Expected {expected} got {errs}"
diff --git a/test/unit/rules/resources/ecs/test_ecs_task_fargate_properties.py b/test/unit/rules/resources/ecs/test_ecs_task_fargate_properties.py
new file mode 100644
index 0000000000..846bd2c023
--- /dev/null
+++ b/test/unit/rules/resources/ecs/test_ecs_task_fargate_properties.py
@@ -0,0 +1,109 @@
+"""
+Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+SPDX-License-Identifier: MIT-0
+"""
+
+from collections import deque
+
+import pytest
+
+from cfnlint.jsonschema import ValidationError
+from cfnlint.rules.resources.ecs.TaskFargateProperties import TaskFargateProperties
+
+
+@pytest.fixture(scope="module")
+def rule():
+ rule = TaskFargateProperties()
+ yield rule
+
+
+@pytest.mark.parametrize(
+ "instance,expected",
+ [
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 256,
+ "Memory": "512",
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 16384,
+ },
+ [
+ ValidationError(
+ "'Memory' is a required property",
+ rule=TaskFargateProperties(),
+ path=deque([]),
+ validator="required",
+ schema_path=deque(["then", "required"]),
+ )
+ ],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Memory": "512",
+ },
+ [
+ ValidationError(
+ "'Cpu' is a required property",
+ rule=TaskFargateProperties(),
+ path=deque([]),
+ validator="required",
+ schema_path=deque(["then", "required"]),
+ )
+ ],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Memory": "512",
+ "Cpu": 256,
+ "PlacementConstraints": "foo",
+ },
+ [
+ ValidationError(
+ ("'PlacementConstraints' isn't supported for Fargate tasks"),
+ rule=TaskFargateProperties(),
+ path=deque(["PlacementConstraints"]),
+ validator="not",
+ schema_path=deque(["then", "not"]),
+ )
+ ],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": {"Ref": "MyParameter"},
+ "Memory": "512",
+ },
+ [],
+ ),
+ (
+ {
+ "RequiresCompatibilities": ["FARGATE"],
+ "Cpu": 128,
+ "Memory": "512",
+ },
+ [
+ ValidationError(
+ (
+ "128 is not one of ['256', '512', '1024', "
+ "'2048', '4096', '8192', '16384']"
+ ),
+ rule=TaskFargateProperties(),
+ path=deque(["Cpu"]),
+ validator="enum",
+ schema_path=deque(["then", "then", "properties", "Cpu", "enum"]),
+ )
+ ],
+ ),
+ ],
+)
+def test_validate(instance, expected, rule, validator):
+ errs = list(rule.validate(validator, "", instance, {}))
+ assert errs == expected, f"Expected {expected} got {errs}"
| diff --git a/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_cpu_memory.json b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_cpu_memory.json
new file mode 100644
index 0000000000..3fc18efad7
--- /dev/null
+++ b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_cpu_memory.json
@@ -0,0 +1,136 @@
+{
+ "if": {
+ "properties": {
+ "Cpu": {
+ "type": [
+ "string",
+ "integer"
+ ]
+ },
+ "Memory": {
+ "type": [
+ "string",
+ "integer"
+ ]
+ },
+ "RequiresCompatibilities": {
+ "contains": {
+ "enum": [
+ "FARGATE"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "RequiresCompatibilities",
+ "Cpu",
+ "Memory"
+ ]
+ },
+ "then": {
+ "anyOf": [
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "256"
+ ]
+ },
+ "Memory": {
+ "enum": [
+ "512",
+ "1024",
+ "2048"
+ ]
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "512"
+ ]
+ },
+ "Memory": {
+ "maximum": 4096,
+ "minimum": 1024,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "1024"
+ ]
+ },
+ "Memory": {
+ "maximum": 8192,
+ "minimum": 2048,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "2048"
+ ]
+ },
+ "Memory": {
+ "maximum": 16384,
+ "minimum": 4096,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "4096"
+ ]
+ },
+ "Memory": {
+ "maximum": 30720,
+ "minimum": 8192,
+ "multipleOf": 1024
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "8192"
+ ]
+ },
+ "Memory": {
+ "maximum": 61440,
+ "minimum": 16384,
+ "multipleOf": 4096
+ }
+ }
+ },
+ {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "16384"
+ ]
+ },
+ "Memory": {
+ "maximum": 122880,
+ "minimum": 32768,
+ "multipleOf": 8192
+ }
+ }
+ }
+ ]
+ }
+}
diff --git a/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_properties.json b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_properties.json
new file mode 100644
index 0000000000..c590df4986
--- /dev/null
+++ b/src/cfnlint/data/schemas/extensions/aws_ecs_taskdefinition/fargate_properties.json
@@ -0,0 +1,57 @@
+{
+ "if": {
+ "properties": {
+ "RequiresCompatibilities": {
+ "contains": {
+ "enum": [
+ "FARGATE"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "RequiresCompatibilities"
+ ]
+ },
+ "then": {
+ "if": {
+ "properties": {
+ "Cpu": {
+ "type": [
+ "string",
+ "integer"
+ ]
+ }
+ },
+ "required": [
+ "Cpu"
+ ]
+ },
+ "not": {
+ "required": [
+ "PlacementConstraints"
+ ]
+ },
+ "required": [
+ "Cpu",
+ "Memory"
+ ],
+ "then": {
+ "properties": {
+ "Cpu": {
+ "enum": [
+ "256",
+ "512",
+ "1024",
+ "2048",
+ "4096",
+ "8192",
+ "16384"
+ ]
+ }
+ }
+ }
+ }
+}
| [
{
"components": [
{
"doc": "",
"lines": [
15,
40
],
"name": "FargateCpuMemory",
"signature": "class FargateCpuMemory(CfnLintJsonSchema):",
"type": "class"
},
{
"doc": "",
"lines": [
27,
32
... | [
"test/unit/rules/resources/ecs/test_ecs_fargate_cpu_memory.py::test_validate[instance0-expected0]",
"test/unit/rules/resources/ecs/test_ecs_fargate_cpu_memory.py::test_validate[instance1-expected1]",
"test/unit/rules/resources/ecs/test_ecs_fargate_cpu_memory.py::test_validate[instance2-expected2]",
"test/unit... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add two new rules to validate fargate tasks
*Issue #, if available:*
#3453
*Description of changes:*
- Add rule E3047 to validate ECS Fargate cpu/memory on a task definition
- Add rule E3048 to validate ECS Fargate properties on a task definition
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
----------
</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/cfnlint/rules/resources/ecs/FargateCpuMemory.py]
(definition of FargateCpuMemory:)
class FargateCpuMemory(CfnLintJsonSchema):
(definition of FargateCpuMemory.__init__:)
def __init__(self) -> None:
(definition of FargateCpuMemory.message:)
def message(self, instance: Any, err: ValidationError) -> str:
[end of new definitions in src/cfnlint/rules/resources/ecs/FargateCpuMemory.py]
[start of new definitions in src/cfnlint/rules/resources/ecs/TaskFargateProperties.py]
(definition of TaskFargateProperties:)
class TaskFargateProperties(CfnLintJsonSchema):
(definition of TaskFargateProperties.__init__:)
def __init__(self) -> None:
(definition of TaskFargateProperties.validate:)
def validate( self, validator: Validator, keywords: Any, instance: Any, schema: dict[str, Any] ) -> ValidationResult:
[end of new definitions in src/cfnlint/rules/resources/ecs/TaskFargateProperties.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>> | 4b214774e419d871b7b498fb5256e2ed09393795 | |
conan-io__conan-16596 | 16,596 | conan-io/conan | null | a474e3d67c1a0acfc4f8fa7db2f71de4bd089466 | 2024-07-03T11:09:49Z | diff --git a/conan/tools/gnu/gnutoolchain.py b/conan/tools/gnu/gnutoolchain.py
index 9848e18fce5..d154f1cfbf7 100644
--- a/conan/tools/gnu/gnutoolchain.py
+++ b/conan/tools/gnu/gnutoolchain.py
@@ -1,3 +1,5 @@
+import os
+
from conan.internal import check_duplicated_generator
from conan.internal.internal_tools import raise_on_universal_arch
from conan.tools.apple.apple import is_apple_os, resolve_apple_flags
@@ -9,6 +11,7 @@
from conan.tools.env import Environment
from conan.tools.gnu.get_gnu_triplet import _get_gnu_triplet
from conan.tools.microsoft import VCVars, msvc_runtime_flag, unix_path, check_min_vs, is_msvc
+from conans.errors import ConanException
from conans.model.pkg_type import PackageType
@@ -18,6 +21,8 @@ class GnuToolchain:
Note: it's based on legacy AutotoolsToolchain but with a more modern and usable UX
"""
+ script_name = "conangnutoolchain"
+
def __init__(self, conanfile, namespace=None, prefix="/"):
"""
:param conanfile: The current recipe object. Always use ``self``.
@@ -63,8 +68,8 @@ def __init__(self, conanfile, namespace=None, prefix="/"):
"host": {"triplet": self._conanfile.conf.get("tools.gnu:host_triplet")},
"build": {"triplet": self._conanfile.conf.get("tools.gnu:build_triplet")}
}
- is_cross_building = cross_building(self._conanfile)
- if is_cross_building:
+ self._is_cross_building = cross_building(self._conanfile)
+ if self._is_cross_building:
compiler = self._conanfile.settings.get_safe("compiler")
# Host triplet
if not self.triplets_info["host"]["triplet"]:
@@ -88,7 +93,7 @@ def __init__(self, conanfile, namespace=None, prefix="/"):
self.configure_args.update(self._get_default_configure_install_flags())
self.configure_args.update(self._get_default_triplets())
# Apple stuff
- is_cross_building_osx = (is_cross_building
+ is_cross_building_osx = (self._is_cross_building
and conanfile.settings_build.get_safe('os') == "Macos"
and is_apple_os(conanfile))
min_flag, arch_flag, isysroot_flag = (
@@ -99,7 +104,7 @@ def __init__(self, conanfile, namespace=None, prefix="/"):
# -isysroot makes all includes for your library relative to the build directory
self.apple_isysroot_flag = isysroot_flag
self.apple_min_version_flag = min_flag
- # MSVC common stuff
+ # Default initial environment flags
self._initialize_default_extra_env()
def yes_no(self, option_name, default=None, negated=False):
@@ -116,31 +121,99 @@ def yes_no(self, option_name, default=None, negated=False):
option_value = not option_value if negated else option_value
return "yes" if option_value else "no"
- def _initialize_default_extra_env(self):
- """Initialize the default environment variables."""
- extra_env_vars = dict()
- # Normally, these are the most common default flags used by MSVC in Windows
- if is_msvc(self._conanfile):
- extra_env_vars = {"CC": "cl -nologo",
- "CXX": "cl -nologo",
- "NM": "dumpbin -symbols",
- "OBJDUMP": ":",
- "RANLIB": ":",
- "STRIP": ":"}
+ def _resolve_android_cross_compilation(self):
+ # Issue related: https://github.com/conan-io/conan/issues/13443
+ ret = {}
+ if not self._is_cross_building or not self._conanfile.settings.get_safe("os") == "Android":
+ return ret
+
+ ndk_path = self._conanfile.conf.get("tools.android:ndk_path", check_type=str)
+ if not ndk_path:
+ raise ConanException("You must provide a NDK path. Use 'tools.android:ndk_path' "
+ "configuration field.")
+
+ if ndk_path:
+ arch = self._conanfile.settings.get_safe("arch")
+ os_build = self._conanfile.settings_build.get_safe("os")
+ ndk_os_folder = {
+ 'Macos': 'darwin',
+ 'iOS': 'darwin',
+ 'watchOS': 'darwin',
+ 'tvOS': 'darwin',
+ 'visionOS': 'darwin',
+ 'FreeBSD': 'linux',
+ 'Linux': 'linux',
+ 'Windows': 'windows',
+ 'WindowsCE': 'windows',
+ 'WindowsStore': 'windows'
+ }.get(os_build, "linux")
+ ndk_bin = os.path.join(ndk_path, "toolchains", "llvm", "prebuilt",
+ f"{ndk_os_folder}-x86_64", "bin")
+ android_api_level = self._conanfile.settings.get_safe("os.api_level")
+ android_target = {'armv7': 'armv7a-linux-androideabi',
+ 'armv8': 'aarch64-linux-android',
+ 'x86': 'i686-linux-android',
+ 'x86_64': 'x86_64-linux-android'}.get(arch)
+ os_build = self._conanfile.settings_build.get_safe('os')
+ ext = ".cmd" if os_build == "Windows" else ""
+ ret = {
+ "CC": os.path.join(ndk_bin, f"{android_target}{android_api_level}-clang{ext}"),
+ "CXX": os.path.join(ndk_bin, f"{android_target}{android_api_level}-clang++{ext}"),
+ "LD": os.path.join(ndk_bin, "ld"),
+ "STRIP": os.path.join(ndk_bin, "llvm-strip"),
+ "RANLIB": os.path.join(ndk_bin, "llvm-ranlib"),
+ "AS": os.path.join(ndk_bin, f"{android_target}{android_api_level}-clang{ext}"),
+ "AR": os.path.join(ndk_bin, "llvm-ar"),
+ }
+ # Overriding host triplet
+ self.triplets_info["host"]["triplet"] = android_target
+ return ret
+
+ def _resolve_compilers_mapping_variables(self):
+ ret = {}
# Configuration map
compilers_mapping = {"c": "CC", "cpp": "CXX", "cuda": "NVCC", "fortran": "FC",
"rc": "RC", "nm": "NM", "ranlib": "RANLIB",
"objdump": "OBJDUMP", "strip": "STRIP"}
# Compiler definitions by conf
- compilers_by_conf = self._conanfile.conf.get("tools.build:compiler_executables", default={},
- check_type=dict)
+ compilers_by_conf = self._conanfile.conf.get("tools.build:compiler_executables",
+ default={}, check_type=dict)
if compilers_by_conf:
for comp, env_var in compilers_mapping.items():
if comp in compilers_by_conf:
compiler = compilers_by_conf[comp]
# https://github.com/conan-io/conan/issues/13780
compiler = unix_path(self._conanfile, compiler)
- extra_env_vars[env_var] = compiler # User/tools ones have precedence
+ ret[env_var] = compiler # User/tools ones have precedence
+ # Issue related: https://github.com/conan-io/conan/issues/15486
+ if self._is_cross_building and self._conanfile.conf_build:
+ compilers_build_mapping = (
+ self._conanfile.conf_build.get("tools.build:compiler_executables", default={},
+ check_type=dict)
+ )
+ if "c" in compilers_build_mapping:
+ ret["CC_FOR_BUILD"] = compilers_build_mapping["c"]
+ if "cpp" in compilers_build_mapping:
+ ret["CXX_FOR_BUILD"] = compilers_build_mapping["cpp"]
+ return ret
+
+ def _initialize_default_extra_env(self):
+ """Initialize the default environment variables."""
+ # If it's an Android cross-compilation
+ extra_env_vars = self._resolve_android_cross_compilation()
+ if not extra_env_vars:
+ # Normally, these are the most common default flags used by MSVC in Windows
+ if is_msvc(self._conanfile):
+ extra_env_vars = {"CC": "cl -nologo",
+ "CXX": "cl -nologo",
+ "LD": "link -nologo",
+ "AR": "lib",
+ "NM": "dumpbin -symbols",
+ "OBJDUMP": ":",
+ "RANLIB": ":",
+ "STRIP": ":"}
+ extra_env_vars.update(self._resolve_compilers_mapping_variables())
+
# Update the extra_env attribute with all the compiler values
for env_var, env_value in extra_env_vars.items():
self.extra_env.define(env_var, env_value)
@@ -252,7 +325,7 @@ def generate(self):
check_duplicated_generator(self, self._conanfile)
# Composing both environments. User extra_env definitions has precedence
env_vars = self._environment.vars(self._conanfile)
- env_vars.save_script("conanautotoolstoolchain")
+ env_vars.save_script(GnuToolchain.script_name)
# Converts all the arguments into strings
args = {
"configure_args": cmd_args_to_string(self._dict_to_list(self.configure_args)),
| diff --git a/test/functional/toolchains/gnu/autotools/test_android.py b/test/functional/toolchains/gnu/autotools/test_android.py
index dc0fc430800..665ece68406 100644
--- a/test/functional/toolchains/gnu/autotools/test_android.py
+++ b/test/functional/toolchains/gnu/autotools/test_android.py
@@ -4,7 +4,6 @@
import pytest
-from conan.test.assets.sources import gen_function_cpp, gen_function_h
from conan.test.utils.tools import TestClient
from test.conftest import tools_locations
@@ -17,7 +16,7 @@
@pytest.mark.tool("android_ndk")
@pytest.mark.tool("autotools")
@pytest.mark.skipif(platform.system() != "Darwin", reason="NDK only installed on MAC")
-def test_android_meson_toolchain_cross_compiling(arch, expected_arch):
+def test_android_autotools_toolchain_cross_compiling(arch, expected_arch):
profile_host = textwrap.dedent("""
include(default)
diff --git a/test/functional/toolchains/gnu/test_gnutoolchain_android.py b/test/functional/toolchains/gnu/test_gnutoolchain_android.py
new file mode 100644
index 00000000000..53f38407d68
--- /dev/null
+++ b/test/functional/toolchains/gnu/test_gnutoolchain_android.py
@@ -0,0 +1,49 @@
+import os
+import platform
+import textwrap
+
+import pytest
+
+from conan.test.utils.mocks import ConanFileMock
+from conan.test.utils.tools import TestClient
+from conan.tools.files import replace_in_file
+from test.conftest import tools_locations
+
+
+@pytest.mark.parametrize("arch, expected_arch", [('armv8', 'aarch64'),
+ ('armv7', 'arm'),
+ ('x86', 'i386'),
+ ('x86_64', 'x86_64')
+ ])
+@pytest.mark.tool("android_ndk")
+@pytest.mark.tool("autotools")
+@pytest.mark.skipif(platform.system() != "Darwin", reason="NDK only installed on MAC")
+def test_android_gnutoolchain_cross_compiling(arch, expected_arch):
+ profile_host = textwrap.dedent("""
+ include(default)
+
+ [settings]
+ os = Android
+ os.api_level = 21
+ arch = {arch}
+
+ [conf]
+ tools.android:ndk_path={ndk_path}
+ """)
+ ndk_path = tools_locations["android_ndk"]["system"]["path"][platform.system()]
+ profile_host = profile_host.format(
+ arch=arch,
+ ndk_path=ndk_path
+ )
+
+ client = TestClient(path_with_spaces=False)
+ # FIXME: Change this when we have gnu_lib as template in the new command
+ client.run("new autotools_lib -d name=hello -d version=1.0")
+ replace_in_file(ConanFileMock(), os.path.join(client.current_folder, "conanfile.py"),
+ "AutotoolsToolchain", "GnuToolchain")
+ client.save({"profile_host": profile_host})
+ client.run("build . --profile:build=default --profile:host=profile_host")
+ libhello = os.path.join("build-release", "src", ".libs", "libhello.a")
+ # Check binaries architecture
+ client.run_command('objdump -f "%s"' % libhello)
+ assert "architecture: %s" % expected_arch in client.out
diff --git a/test/integration/toolchains/gnu/test_gnutoolchain.py b/test/integration/toolchains/gnu/test_gnutoolchain.py
index d35d45b04fa..e93583ec5f3 100644
--- a/test/integration/toolchains/gnu/test_gnutoolchain.py
+++ b/test/integration/toolchains/gnu/test_gnutoolchain.py
@@ -37,7 +37,7 @@ def test_extra_flags_via_conf(os_):
"profile": profile})
client.run("install . --profile:build=profile --profile:host=profile")
toolchain = client.load(
- "conanautotoolstoolchain{}".format('.bat' if os_ == "Windows" else '.sh'))
+ "conangnutoolchain{}".format('.bat' if os_ == "Windows" else '.sh'))
if os_ == "Windows":
assert 'set "CPPFLAGS=%CPPFLAGS% -DNDEBUG -DDEF1 -DDEF2"' in toolchain
assert 'set "CXXFLAGS=%CXXFLAGS% -O3 --flag1 --flag2"' in toolchain
@@ -88,7 +88,7 @@ def generate(self):
client.save({"conanfile.py": conanfile, "profile": profile})
client.run('install . -pr=./profile')
toolchain = client.load(
- "conanautotoolstoolchain{}".format('.bat' if platform.system() == "Windows" else '.sh'))
+ "conangnutoolchain{}".format('.bat' if platform.system() == "Windows" else '.sh'))
assert '-Dextra_defines -Ddefines' in toolchain
assert 'extra_cxxflags cxxflags' in toolchain
@@ -113,7 +113,7 @@ def generate(self):
client.save({"conanfile.py": conanfile})
client.run("install . -s:b os=Linux -s:h os=Linux")
- content = load(os.path.join(client.current_folder, "conanautotoolstoolchain.sh"))
+ content = load(os.path.join(client.current_folder, "conangnutoolchain.sh"))
assert 'export FOO="BAR"' in content
@@ -141,7 +141,7 @@ def test_linker_scripts_via_conf(os_):
"profile": profile})
client.run("install . --profile:build=profile --profile:host=profile")
toolchain = client.load(
- "conanautotoolstoolchain{}".format('.bat' if os_ == "Windows" else '.sh'))
+ "conangnutoolchain{}".format('.bat' if os_ == "Windows" else '.sh'))
if os_ == "Windows":
assert 'set "LDFLAGS=%LDFLAGS% --flag5 --flag6 -T\'/linker/scripts/flash.ld\' -T\'/linker/scripts/extra_data.ld\'"' in toolchain
else:
@@ -255,7 +255,7 @@ class toolRecipe(ConanFile):
generators = "GnuToolchain"
def build(self):
- toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.sh")
+ toolchain = os.path.join(self.generators_folder, "conangnutoolchain.sh")
content = load(self, toolchain)
assert 'export CC="clang"' in content
assert 'export CXX="clang++"' in content
@@ -274,11 +274,14 @@ class consumerRecipe(ConanFile):
tool_requires = "tool/1.0"
def build(self):
- toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.sh")
+ toolchain = os.path.join(self.generators_folder, "conangnutoolchain.sh")
content = load(self, toolchain)
assert 'export CC="gcc"' in content
assert 'export CXX="g++"' in content
assert 'export RC="windres"' in content
+ # Issue: https://github.com/conan-io/conan/issues/15486
+ assert 'export CC_FOR_BUILD="clang"' in content
+ assert 'export CXX_FOR_BUILD="clang++"' in content
""")
client = TestClient()
client.save({
@@ -376,7 +379,7 @@ class consumerRecipe(ConanFile):
generators = "GnuToolchain"
def build(self):
- toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.bat")
+ toolchain = os.path.join(self.generators_folder, "conangnutoolchain.bat")
content = load(self, toolchain)
# Default values and conf ones
assert r'set "CC=clang"' in content # conf value has precedence
@@ -415,7 +418,7 @@ def generate(self):
tc.generate()
def build(self):
- toolchain = os.path.join(self.generators_folder, "conanautotoolstoolchain.bat")
+ toolchain = os.path.join(self.generators_folder, "conangnutoolchain.bat")
content = load(self, toolchain)
# Default values
assert r'set "CC=compile clang"' in content
| [
{
"components": [
{
"doc": "",
"lines": [
124,
170
],
"name": "GnuToolchain._resolve_android_cross_compilation",
"signature": "def _resolve_android_cross_compilation(self):",
"type": "function"
},
{
"doc": "",
... | [
"test/integration/toolchains/gnu/test_gnutoolchain.py::test_extra_flags_via_conf[Macos]",
"test/integration/toolchains/gnu/test_gnutoolchain.py::test_extra_flags_via_conf[Linux]",
"test/integration/toolchains/gnu/test_gnutoolchain.py::test_extra_flags_via_conf[Windows]",
"test/integration/toolchains/gnu/test_... | [
"test/integration/toolchains/gnu/test_gnutoolchain.py::test_not_none_values",
"test/integration/toolchains/gnu/test_gnutoolchain.py::test_set_prefix",
"test/integration/toolchains/gnu/test_gnutoolchain.py::test_unknown_compiler",
"test/integration/toolchains/gnu/test_gnutoolchain.py::test_autotools_crossbuild... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
[GnuToolchain] Update extra env flags (Android + `CC|CXX_FOR_BUILD`)
Changelog: Feature: Added `XXX_FOR_BUILD` flags and Android extra ones to `extra_env` attribute in `GnuToolchain`.
Docs: omit
Let's keep it up-to-date.
----------
</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/gnutoolchain.py]
(definition of GnuToolchain._resolve_android_cross_compilation:)
def _resolve_android_cross_compilation(self):
(definition of GnuToolchain._resolve_compilers_mapping_variables:)
def _resolve_compilers_mapping_variables(self):
[end of new definitions in conan/tools/gnu/gnutoolchain.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-3725 | 3,725 | tobymao/sqlglot | null | f4a28721fd33edb3178c1d99746209dadfbba487 | 2024-07-02T10:34:36Z | diff --git a/sqlglot/dialects/databricks.py b/sqlglot/dialects/databricks.py
index e2628dc957..00f6353253 100644
--- a/sqlglot/dialects/databricks.py
+++ b/sqlglot/dialects/databricks.py
@@ -43,7 +43,7 @@ class JSONPathTokenizer(jsonpath.JSONPathTokenizer):
class Parser(Spark.Parser):
LOG_DEFAULTS_TO_LN = True
STRICT_CAST = True
- COLON_IS_JSON_EXTRACT = True
+ COLON_IS_VARIANT_EXTRACT = True
FUNCTIONS = {
**Spark.Parser.FUNCTIONS,
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index 4c394be71d..da21286900 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -510,8 +510,28 @@ def get_or_raise(cls, dialect: DialectType) -> Dialect:
return dialect
if isinstance(dialect, str):
try:
- dialect_name, *kv_pairs = dialect.split(",")
- kwargs = {k.strip(): v.strip() for k, v in (kv.split("=") for kv in kv_pairs)}
+ dialect_name, *kv_strings = dialect.split(",")
+ kv_pairs = (kv.split("=") for kv in kv_strings)
+ kwargs = {}
+ for pair in kv_pairs:
+ key = pair[0].strip()
+ value: t.Union[bool | str | None] = None
+
+ if len(pair) == 1:
+ # Default initialize standalone settings to True
+ value = True
+ elif len(pair) == 2:
+ value = pair[1].strip()
+
+ # Coerce the value to boolean if it matches to the truthy/falsy values below
+ value_lower = value.lower()
+ if value_lower in ("true", "1"):
+ value = True
+ elif value_lower in ("false", "0"):
+ value = False
+
+ kwargs[key] = value
+
except ValueError:
raise ValueError(
f"Invalid dialect format: '{dialect}'. "
diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py
index 69c1fbec79..925af86262 100644
--- a/sqlglot/dialects/presto.py
+++ b/sqlglot/dialects/presto.py
@@ -173,6 +173,35 @@ def _unix_to_time_sql(self: Presto.Generator, expression: exp.UnixToTime) -> str
return f"FROM_UNIXTIME(CAST({timestamp} AS DOUBLE) / POW(10, {scale}))"
+def _jsonextract_sql(self: Presto.Generator, expression: exp.JSONExtract) -> str:
+ is_json_extract = self.dialect.settings.get("variant_extract_is_json_extract", True)
+
+ # Generate JSON_EXTRACT unless the user has configured that a Snowflake / Databricks
+ # VARIANT extract (e.g. col:x.y) should map to dot notation (i.e ROW access) in Presto/Trino
+ if not expression.args.get("variant_extract") or is_json_extract:
+ return self.func(
+ "JSON_EXTRACT", expression.this, expression.expression, *expression.expressions
+ )
+
+ this = self.sql(expression, "this")
+
+ # Convert the JSONPath extraction `JSON_EXTRACT(col, '$.x.y) to a ROW access col.x.y
+ segments = []
+ for path_key in expression.expression.expressions[1:]:
+ if not isinstance(path_key, exp.JSONPathKey):
+ # Cannot transpile subscripts, wildcards etc to dot notation
+ self.unsupported(f"Cannot transpile JSONPath segment '{path_key}' to ROW access")
+ continue
+ key = path_key.this
+ if not exp.SAFE_IDENTIFIER_RE.match(key):
+ key = f'"{key}"'
+ segments.append(f".{key}")
+
+ expr = "".join(segments)
+
+ return f"{this}{expr}"
+
+
def _to_int(expression: exp.Expression) -> exp.Expression:
if not expression.type:
from sqlglot.optimizer.annotate_types import annotate_types
@@ -390,6 +419,7 @@ class Generator(generator.Generator):
exp.If: if_sql(),
exp.ILike: no_ilike_sql,
exp.Initcap: _initcap_sql,
+ exp.JSONExtract: _jsonextract_sql,
exp.Last: _first_last_sql,
exp.LastValue: _first_last_sql,
exp.LastDay: lambda self, e: self.func("LAST_DAY_OF_MONTH", e.this),
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index c773380183..1eab756be5 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -241,7 +241,7 @@ def quote_identifier(self, expression: E, identify: bool = True) -> E:
class Parser(parser.Parser):
IDENTIFY_PIVOT_STRINGS = True
DEFAULT_SAMPLING_METHOD = "BERNOULLI"
- COLON_IS_JSON_EXTRACT = True
+ COLON_IS_VARIANT_EXTRACT = True
ID_VAR_TOKENS = {
*parser.Parser.ID_VAR_TOKENS,
diff --git a/sqlglot/executor/python.py b/sqlglot/executor/python.py
index 674ef78982..5988c4d94b 100644
--- a/sqlglot/executor/python.py
+++ b/sqlglot/executor/python.py
@@ -447,6 +447,7 @@ class Generator(generator.Generator):
exp.Is: lambda self, e: (
self.binary(e, "==") if isinstance(e.this, exp.Literal) else self.binary(e, "is")
),
+ exp.JSONExtract: lambda self, e: self.func(e.key, e.this, e.expression, *e.expressions),
exp.JSONPath: lambda self, e: f"[{','.join(self.sql(p) for p in e.expressions[1:])}]",
exp.JSONPathKey: lambda self, e: f"'{self.sql(e.this)}'",
exp.JSONPathSubscript: lambda self, e: f"'{e.this}'",
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index ce71213543..3aa45acf4b 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -5480,7 +5480,13 @@ class JSONBContains(Binary, Func):
class JSONExtract(Binary, Func):
- arg_types = {"this": True, "expression": True, "only_json_types": False, "expressions": False}
+ arg_types = {
+ "this": True,
+ "expression": True,
+ "only_json_types": False,
+ "expressions": False,
+ "variant_extract": False,
+ }
_sql_names = ["JSON_EXTRACT"]
is_var_len_args = True
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index e50abcc3ee..c622292650 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -1203,8 +1203,8 @@ class Parser(metaclass=_Parser):
# Whether the -> and ->> operators expect documents of type JSON (e.g. Postgres)
JSON_ARROWS_REQUIRE_JSON_TYPE = False
- # Whether the `:` operator is used to extract a value from a JSON document
- COLON_IS_JSON_EXTRACT = False
+ # Whether the `:` operator is used to extract a value from a VARIANT column
+ COLON_IS_VARIANT_EXTRACT = False
# Whether or not a VALUES keyword needs to be followed by '(' to form a VALUES clause.
# If this is True and '(' is not found, the keyword will be treated as an identifier
@@ -4552,7 +4552,7 @@ def _parse_column_reference(self) -> t.Optional[exp.Expression]:
return this
- def _parse_colon_as_json_extract(
+ def _parse_colon_as_variant_extract(
self, this: t.Optional[exp.Expression]
) -> t.Optional[exp.Expression]:
casts = []
@@ -4585,11 +4585,14 @@ def _parse_colon_as_json_extract(
if path:
json_path.append(self._find_sql(self._tokens[start_index], end_token))
+ # The VARIANT extract in Snowflake/Databricks is parsed as a JSONExtract; Snowflake uses the json_path in GET_PATH() while
+ # Databricks transforms it back to the colon/dot notation
if json_path:
this = self.expression(
exp.JSONExtract,
this=this,
expression=self.dialect.to_json_path(exp.Literal.string(".".join(json_path))),
+ variant_extract=True,
)
while casts:
@@ -4646,7 +4649,7 @@ def _parse_column_ops(self, this: t.Optional[exp.Expression]) -> t.Optional[exp.
this = self._parse_bracket(this)
- return self._parse_colon_as_json_extract(this) if self.COLON_IS_JSON_EXTRACT else this
+ return self._parse_colon_as_variant_extract(this) if self.COLON_IS_VARIANT_EXTRACT else this
def _parse_primary(self) -> t.Optional[exp.Expression]:
if self._match_set(self.PRIMARY_PARSERS):
| diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py
index be262d4aed..c0afb2f467 100644
--- a/tests/dialects/test_dialect.py
+++ b/tests/dialects/test_dialect.py
@@ -102,14 +102,10 @@ def test_get_or_raise(self):
lowercase_mysql = Dialect.get_or_raise("mysql, normalization_strategy = lowercase")
self.assertEqual(lowercase_mysql.normalization_strategy.value, "LOWERCASE")
- with self.assertRaises(ValueError) as cm:
+ with self.assertRaises(AttributeError) as cm:
Dialect.get_or_raise("mysql, normalization_strategy")
- self.assertEqual(
- str(cm.exception),
- "Invalid dialect format: 'mysql, normalization_strategy'. "
- "Please use the correct format: 'dialect [, k1 = v2 [, ...]]'.",
- )
+ self.assertEqual(str(cm.exception), "'bool' object has no attribute 'upper'")
with self.assertRaises(ValueError) as cm:
Dialect.get_or_raise("myqsl")
@@ -127,6 +123,12 @@ def test_get_or_raise(self):
self.assertEqual(oracle_with_settings.normalization_strategy.value, "LOWERCASE")
self.assertEqual(oracle_with_settings.settings, {"version": "19.5"})
+ bool_settings = Dialect.get_or_raise("oracle, s1=TruE, s2=1, s3=FaLse, s4=0, s5=nonbool")
+ self.assertEqual(
+ bool_settings.settings,
+ {"s1": True, "s2": True, "s3": False, "s4": False, "s5": "nonbool"},
+ )
+
def test_compare_dialects(self):
bigquery_class = Dialect["bigquery"]
bigquery_object = BigQuery()
diff --git a/tests/dialects/test_presto.py b/tests/dialects/test_presto.py
index ebb270ab8c..82b9d62605 100644
--- a/tests/dialects/test_presto.py
+++ b/tests/dialects/test_presto.py
@@ -1192,3 +1192,18 @@ def test_signum(self):
"starrocks": "SIGN(x)",
},
)
+
+ def test_json_vs_row_extract(self):
+ for dialect in ("trino", "presto"):
+ s = parse_one('SELECT col:x:y."special string"', read="snowflake")
+
+ dialect_json_extract_setting = f"{dialect}, variant_extract_is_json_extract=True"
+ dialect_row_access_setting = f"{dialect}, variant_extract_is_json_extract=False"
+
+ # By default, Snowflake VARIANT will generate JSON_EXTRACT() in Presto/Trino
+ json_extract_result = """SELECT JSON_EXTRACT(col, '$.x.y["special string"]')"""
+ self.assertEqual(s.sql(dialect), json_extract_result)
+ self.assertEqual(s.sql(dialect_json_extract_setting), json_extract_result)
+
+ # If the setting is overriden to False, then generate ROW access (dot notation)
+ self.assertEqual(s.sql(dialect_row_access_setting), 'SELECT col.x.y."special string"')
| [] | [
"tests/dialects/test_dialect.py::TestDialect::test_get_or_raise",
"tests/dialects/test_presto.py::TestPresto::test_json_vs_row_extract"
] | [
"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_defin... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(presto, trino): Configurable transpilation of Snowflake VARIANT
Fixes #3713
Both Snowflake and Databricks have a `VARIANT` type with similar extract notation e.g. `col:x.y` which can be used to store any data (most notably, semi-structured). Up until now, SQLGlot treated this notation as a JSON extraction which is not always correct; As the issue showcased, since Snowflake does not have a `STRUCT` data type, Iceberg represents it's `STRUCT` as a `VARIANT` column which should map to a `ROW` column in Presto/Trino instead of `JSON`.
This PR focuses on Snowflake -> Presto/Trino and attempts to lift off this restriction by introducing a new dialect setting which can make the `exp.JSONExtract` generation configurable such that it can either:
1. Generate `JSON_EXTRACT(col, '$.x.y')` for JSON data (as was before) or
2. Transform the JSONPath to the equivalent ROW access in dot notation `col.x.y`
Note that SQLGlot is unable to statically infer the _actual_ type of the data stored in a `VARIANT` column so transpilation to other dialects remains a best-effort attempt.
Documentation
---------------------
- [Snowflake VARIANT](https://docs.snowflake.com/en/sql-reference/data-types-semistructured#variant)
- [Snowflake VARIANT access](https://docs.snowflake.com/en/user-guide/querying-semistructured)
- [Iceberg - Snowflake STRUCT type](https://docs.snowflake.com/en/user-guide/tables-iceberg-data-types#other-data-types)
- [Databricks VARIANT](https://docs.databricks.com/en/semi-structured/variant.html)
----------
</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>
</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>
Snowflake nested fields are incorrectly translated using `JSON_EXTRACT`
**Before you file an issue**
- Make sure you specify the "read" dialect eg. `parse_one(sql, read="spark")`
- Make sure you specify the "write" dialect eg. `ast.sql(dialect="duckdb")`
- Check if the issue still exists on main
**Fully reproducible code snippet**
```
print(sqlglot.transpile("select payload:testField from snowflake_table;", read="snowflake", write="trino", pretty=True)[0])
```
*Output:*
```
SELECT
JSON_EXTRACT(payload, '$.testField')
FROM snowflake_table
```
*Expected output:*
```
SELECT
payload.testField
FROM snowflake_table
```
`payload:testField` is how nested fields of VARIANT type are accessed in Snowflake, they should be translated into `payload.testField` for Trino, since they would be or `row` type in Trino and not JSON.
**Official Documentation**
[Querying VARIANT nested fields in Snowflake](https://docs.snowflake.com/en/user-guide/querying-semistructured#traversing-semi-structured-data)
[Trino nested field query example](https://trino.io/blog/2020/08/14/dereference-pushdown.html#example)
----------
Hey @Leonti, thanks for reporting this. Right now, SQLGlot generates mostly JSONPath functions when parsing semi-structured accesses (e.g. `GET_PATH` for VARIANT in Snowflake) instead of preserving the colon/dot notation.
However, I think the `Snowflake -> Trino` transpilation is more nuanced and will probably require type inference to work properly, so the fix will be a best-effort attempt without a schema.
Quick follow up to gain more context, could you provide an example of how your data is structured in Snowflake and in what way would they be transformed to Trino's `ROW` type instead of `JSON`?
Hi @VaggelisD!
Thanks for looking into it so quickly!
I have an Iceberg table in S3 which is [integrated with Snowflake](https://docs.snowflake.com/en/user-guide/tables-iceberg).
The table has a couple of columns which are of type `STRUCT` in Iceberg, which translates into `VARIANT` when integrated with Snowflake. If I need to get access to nested fields using Snowflake I would do something like:
```
select payload:nestedField:nestedNestedField from iceberg_table;
```
because it's a `VARIANT` type.
Because fields are nested within a a `STRUCT` I've created a "convenience view" in snowflake that flattens the structure, something like this:
```
select
payload:nestedField:nestedNestedField as field,
payload:anotherField as field2,
-- and so on, potentially tens of fields
from iceberg_table;
```
Since it's an Iceberg table it can also be queried directly from Athena/Trino. In Trino Iceberg/Parquet `STRUCT` is represented as `ROW` type, and instead of using `:` one would use `.` notation to access nested fields.
Since I already have a bunch of "convenience views" for Snowflake, I was hoping to use `sqlglot` to convert them to query the Iceberg table using Athena/Trino instead of converting them by hand.
When using Iceberg or Parquet on S3 the `STRUCT` type gets converted into Snowflake's `VARIANT` or Trino's `ROW` directly, so JSON is not involved there at all.
Thanks for the detailed explanation! Did some research over the last days and came to the conclusion that there's ambiguity in transpiling Snowflake's `VARIANT` as it can store practically any data type. For example, it can store semi-structured objects such as `JSON` (in which case, the transpilation to Trino's `JSON_EXTRACT` is correct) or a structured `OBJECT` in the case of Iceberg's `STRUCT`, which should be transpiled as you've explained.
Since SQLGlot cannot analyze the data to infer what's stored under `VARIANT`, I'll attempt to make the transpilation configurable such that you can generate both versions (`JSON_EXTRACT` and dot notation, depending on the setting) on Snowflake -> Presto/Trino, hopefully that will help.
--------------------
</issues> | ceb42fabad60312699e4b15936aeebac00e22e4d | |
sphinx-doc__sphinx-12492 | 12,492 | sphinx-doc/sphinx | 7.4 | f0c51781760bdb5f28428412d09f63dd1d3d1037 | 2024-06-28T23:51:45Z | diff --git a/CHANGES.rst b/CHANGES.rst
index be3293da1e6..a59acdfdbce 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -34,6 +34,18 @@ Features added
Patch by James Addison.
* #12319: ``sphinx.ext.extlinks``: Add ``extlink-{name}`` CSS class to links.
Patch by Hugo van Kemenade.
+* Add helper methods for parsing reStructuredText content into nodes from
+ within a directive.
+
+ - :py:meth:`~sphinx.util.docutils.SphinxDirective.parse_content_to_nodes()`
+ parses the directive's content and returns a list of Docutils nodes.
+ - :py:meth:`~sphinx.util.docutils.SphinxDirective.parse_text_to_nodes()`
+ parses the provided text and returns a list of Docutils nodes.
+ - :py:meth:`~sphinx.util.docutils.SphinxDirective.parse_inline()`
+ parses the provided text into inline elements and text nodes.
+
+ Patch by Adam Turner.
+
Bugs fixed
----------
diff --git a/doc/conf.py b/doc/conf.py
index a8c1d32617c..040c13dde0d 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -186,6 +186,7 @@
('py:class', 'NullTranslations'), # gettext.NullTranslations
('py:class', 'RoleFunction'), # sphinx.domains.Domain
('py:class', 'Theme'), # sphinx.application.TemplateBridge
+ ('py:class', 'system_message'), # sphinx.utils.docutils
('py:class', 'TitleGetter'), # sphinx.domains.Domain
('py:class', 'XRefRole'), # sphinx.domains.Domain
('py:class', 'docutils.nodes.Element'),
diff --git a/doc/development/tutorials/examples/todo.py b/doc/development/tutorials/examples/todo.py
index 6daf103a274..4e9dc66855e 100644
--- a/doc/development/tutorials/examples/todo.py
+++ b/doc/development/tutorials/examples/todo.py
@@ -38,7 +38,7 @@ def run(self):
todo_node = todo('\n'.join(self.content))
todo_node += nodes.title(_('Todo'), _('Todo'))
- self.state.nested_parse(self.content, self.content_offset, todo_node)
+ todo_node += self.parse_content_to_nodes()
if not hasattr(self.env, 'todo_all_todos'):
self.env.todo_all_todos = []
diff --git a/sphinx/directives/__init__.py b/sphinx/directives/__init__.py
index 9e06a7a64b8..cf9b9d0f3e4 100644
--- a/sphinx/directives/__init__.py
+++ b/sphinx/directives/__init__.py
@@ -13,7 +13,6 @@
from sphinx.util import docutils
from sphinx.util.docfields import DocFieldTransformer, Field, TypedField
from sphinx.util.docutils import SphinxDirective
-from sphinx.util.nodes import nested_parse_with_titles
from sphinx.util.typing import ExtensionMetadata, OptionSpec # NoQA: TCH001
if TYPE_CHECKING:
@@ -127,7 +126,7 @@ def before_content(self) -> None:
"""
pass
- def transform_content(self, contentnode: addnodes.desc_content) -> None:
+ def transform_content(self, content_node: addnodes.desc_content) -> None:
"""
Called after creating the content through nested parsing,
but before the ``object-description-transform`` event is emitted,
@@ -275,18 +274,16 @@ def run(self) -> list[Node]:
# description of the object with this name in this desc block
self.add_target_and_index(name, sig, signode)
- contentnode = addnodes.desc_content()
- node.append(contentnode)
-
if self.names:
# needed for association of version{added,changed} directives
self.env.temp_data['object'] = self.names[0]
self.before_content()
- nested_parse_with_titles(self.state, self.content, contentnode, self.content_offset)
- self.transform_content(contentnode)
+ content_node = addnodes.desc_content('', *self.parse_content_to_nodes())
+ node.append(content_node)
+ self.transform_content(content_node)
self.env.app.emit('object-description-transform',
- self.domain, self.objtype, contentnode)
- DocFieldTransformer(self).transform_all(contentnode)
+ self.domain, self.objtype, content_node)
+ DocFieldTransformer(self).transform_all(content_node)
self.env.temp_data['object'] = None
self.after_content()
diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py
index 3cdc5c119e0..5dc42e5b744 100644
--- a/sphinx/directives/code.py
+++ b/sphinx/directives/code.py
@@ -7,7 +7,6 @@
from docutils import nodes
from docutils.parsers.rst import directives
-from docutils.statemachine import StringList
from sphinx import addnodes
from sphinx.directives import optional_int
@@ -75,15 +74,13 @@ def container_wrapper(
) -> nodes.container:
container_node = nodes.container('', literal_block=True,
classes=['literal-block-wrapper'])
- parsed = nodes.Element()
- directive.state.nested_parse(StringList([caption], source=''),
- directive.content_offset, parsed)
- if isinstance(parsed[0], nodes.system_message):
- msg = __('Invalid caption: %s' % parsed[0].astext())
+ parsed = directive.parse_text_to_nodes(caption, offset=directive.content_offset)
+ node = parsed[0]
+ if isinstance(node, nodes.system_message):
+ msg = __('Invalid caption: %s') % node.astext()
raise ValueError(msg)
- if isinstance(parsed[0], nodes.Element):
- caption_node = nodes.caption(parsed[0].rawsource, '',
- *parsed[0].children)
+ if isinstance(node, nodes.Element):
+ caption_node = nodes.caption(node.rawsource, '', *node.children)
caption_node.source = literal_node.source
caption_node.line = literal_node.line
container_node += caption_node
diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py
index 286db295579..7fa12f74ead 100644
--- a/sphinx/directives/other.py
+++ b/sphinx/directives/other.py
@@ -198,7 +198,7 @@ def run(self) -> list[Node]:
else:
text = _('Author: ')
emph += nodes.Text(text)
- inodes, messages = self.state.inline_text(self.arguments[0], self.lineno)
+ inodes, messages = self.parse_inline(self.arguments[0])
emph.extend(inodes)
ret: list[Node] = [para]
@@ -247,7 +247,7 @@ def run(self) -> list[Node]:
if not self.arguments:
return []
subnode: Element = addnodes.centered()
- inodes, messages = self.state.inline_text(self.arguments[0], self.lineno)
+ inodes, messages = self.parse_inline(self.arguments[0])
subnode.extend(inodes)
ret: list[Node] = [subnode]
@@ -267,15 +267,12 @@ class Acks(SphinxDirective):
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
- node = addnodes.acks()
- node.document = self.state.document
- self.state.nested_parse(self.content, self.content_offset, node)
- if len(node.children) != 1 or not isinstance(node.children[0],
- nodes.bullet_list):
+ children = self.parse_content_to_nodes()
+ if len(children) != 1 or not isinstance(children[0], nodes.bullet_list):
logger.warning(__('.. acks content is not a list'),
location=(self.env.docname, self.lineno))
return []
- return [node]
+ return [addnodes.acks('', *children)]
class HList(SphinxDirective):
@@ -293,15 +290,12 @@ class HList(SphinxDirective):
def run(self) -> list[Node]:
ncolumns = self.options.get('columns', 2)
- node = nodes.paragraph()
- node.document = self.state.document
- self.state.nested_parse(self.content, self.content_offset, node)
- if len(node.children) != 1 or not isinstance(node.children[0],
- nodes.bullet_list):
+ children = self.parse_content_to_nodes()
+ if len(children) != 1 or not isinstance(children[0], nodes.bullet_list):
logger.warning(__('.. hlist content is not a list'),
location=(self.env.docname, self.lineno))
return []
- fulllist = node.children[0]
+ fulllist = children[0]
# create a hlist node where the items are distributed
npercol, nmore = divmod(len(fulllist), ncolumns)
index = 0
diff --git a/sphinx/domains/changeset.py b/sphinx/domains/changeset.py
index 5ffabcf5044..762785d3160 100644
--- a/sphinx/domains/changeset.py
+++ b/sphinx/domains/changeset.py
@@ -62,15 +62,14 @@ def run(self) -> list[Node]:
node['version'] = self.arguments[0]
text = versionlabels[self.name] % self.arguments[0]
if len(self.arguments) == 2:
- inodes, messages = self.state.inline_text(self.arguments[1],
- self.lineno + 1)
+ inodes, messages = self.parse_inline(self.arguments[1], lineno=self.lineno + 1)
para = nodes.paragraph(self.arguments[1], '', *inodes, translatable=False)
self.set_source_info(para)
node.append(para)
else:
messages = []
if self.content:
- self.state.nested_parse(self.content, self.content_offset, node)
+ node += self.parse_content_to_nodes()
classes = ['versionmodified', versionlabel_classes[self.name]]
if len(node) > 0 and isinstance(node[0], nodes.paragraph):
# the contents start with a paragraph
diff --git a/sphinx/domains/cpp/__init__.py b/sphinx/domains/cpp/__init__.py
index f4cb052f228..feafcb70f88 100644
--- a/sphinx/domains/cpp/__init__.py
+++ b/sphinx/domains/cpp/__init__.py
@@ -763,10 +763,9 @@ def run(self) -> list[Node]:
for sig in signatures:
node.append(AliasNode(sig, aliasOptions, env=self.env))
- contentnode = addnodes.desc_content()
- node.append(contentnode)
self.before_content()
- self.state.nested_parse(self.content, self.content_offset, contentnode)
+ content_node = addnodes.desc_content('', *self.parse_content_to_nodes())
+ node.append(content_node)
self.env.temp_data['object'] = None
self.after_content()
return [node]
diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py
index 9b881f87f92..2e49461afc1 100644
--- a/sphinx/domains/javascript.py
+++ b/sphinx/domains/javascript.py
@@ -17,7 +17,7 @@
from sphinx.util import logging
from sphinx.util.docfields import Field, GroupedField, TypedField
from sphinx.util.docutils import SphinxDirective
-from sphinx.util.nodes import make_id, make_refnode, nested_parse_with_titles
+from sphinx.util.nodes import make_id, make_refnode
if TYPE_CHECKING:
from collections.abc import Iterator
@@ -311,10 +311,7 @@ def run(self) -> list[Node]:
self.env.ref_context['js:module'] = mod_name
no_index = 'no-index' in self.options or 'noindex' in self.options
- content_node: Element = nodes.section()
- # necessary so that the child nodes get the right source/line set
- content_node.document = self.state.document
- nested_parse_with_titles(self.state, self.content, content_node, self.content_offset)
+ content_nodes = self.parse_content_to_nodes()
ret: list[Node] = []
if not no_index:
@@ -334,7 +331,7 @@ def run(self) -> list[Node]:
target = nodes.target('', '', ids=[node_id], ismod=True)
self.state.document.note_explicit_target(target)
ret.append(target)
- ret.extend(content_node.children)
+ ret.extend(content_nodes)
return ret
diff --git a/sphinx/domains/python/__init__.py b/sphinx/domains/python/__init__.py
index ca3eec07dbc..22a23f226b5 100644
--- a/sphinx/domains/python/__init__.py
+++ b/sphinx/domains/python/__init__.py
@@ -22,7 +22,6 @@
find_pending_xref_condition,
make_id,
make_refnode,
- nested_parse_with_titles,
)
if TYPE_CHECKING:
@@ -417,10 +416,7 @@ def run(self) -> list[Node]:
no_index = 'no-index' in self.options or 'noindex' in self.options
self.env.ref_context['py:module'] = modname
- content_node: Element = nodes.section()
- # necessary so that the child nodes get the right source/line set
- content_node.document = self.state.document
- nested_parse_with_titles(self.state, self.content, content_node, self.content_offset)
+ content_nodes = self.parse_content_to_nodes()
ret: list[Node] = []
if not no_index:
@@ -444,7 +440,7 @@ def run(self) -> list[Node]:
# The node order is: index node first, then target node.
ret.append(inode)
ret.append(target)
- ret.extend(content_node.children)
+ ret.extend(content_nodes)
return ret
diff --git a/sphinx/domains/std/__init__.py b/sphinx/domains/std/__init__.py
index 14d259c30de..5ac6ae5acc8 100644
--- a/sphinx/domains/std/__init__.py
+++ b/sphinx/domains/std/__init__.py
@@ -20,6 +20,7 @@
from sphinx.util import docname_join, logging, ws_re
from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import clean_astext, make_id, make_refnode
+from sphinx.util.parsing import nested_parse_to_nodes
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
@@ -260,10 +261,15 @@ def process_link(self, env: BuildEnvironment, refnode: Element, has_explicit_tit
return title, target
-def split_term_classifiers(line: str) -> list[str | None]:
+_term_classifiers_re = re.compile(' +: +')
+
+
+def split_term_classifiers(line: str) -> tuple[str, str | None]:
# split line into a term and classifiers. if no classifier, None is used..
- parts: list[str | None] = [*re.split(' +: +', line), None]
- return parts
+ parts = _term_classifiers_re.split(line)
+ term = parts[0]
+ first_classifier = parts[1] if len(parts) >= 2 else None
+ return term, first_classifier
def make_glossary_term(env: BuildEnvironment, textnodes: Iterable[Node], index_key: str,
@@ -382,15 +388,14 @@ def run(self) -> list[Node]:
termnodes: list[Node] = []
system_messages: list[Node] = []
for line, source, lineno in terms:
- parts = split_term_classifiers(line)
+ term_, first_classifier = split_term_classifiers(line)
# parse the term with inline markup
# classifiers (parts[1:]) will not be shown on doctree
- textnodes, sysmsg = self.state.inline_text(parts[0],
- lineno)
+ textnodes, sysmsg = self.parse_inline(term_, lineno=lineno)
# use first classifier as a index key
term = make_glossary_term(self.env, textnodes,
- parts[1], source, lineno, # type: ignore[arg-type]
+ first_classifier, source, lineno, # type: ignore[arg-type]
node_id=None, document=self.state.document)
term.rawsource = line
system_messages.extend(sysmsg)
@@ -398,11 +403,12 @@ def run(self) -> list[Node]:
termnodes.extend(system_messages)
- defnode = nodes.definition()
if definition:
- self.state.nested_parse(definition, definition.items[0][1],
- defnode)
- termnodes.append(defnode)
+ offset = definition.items[0][1]
+ definition_nodes = nested_parse_to_nodes(self.state, definition, offset=offset)
+ else:
+ definition_nodes = []
+ termnodes.append(nodes.definition('', *definition_nodes))
items.append(nodes.definition_list_item('', *termnodes))
dlist = nodes.definition_list('', *items)
diff --git a/sphinx/ext/autodoc/directive.py b/sphinx/ext/autodoc/directive.py
index 8ee93ce1dcd..7741dcbdf0d 100644
--- a/sphinx/ext/autodoc/directive.py
+++ b/sphinx/ext/autodoc/directive.py
@@ -9,10 +9,10 @@
from sphinx.ext.autodoc import Documenter, Options
from sphinx.util import logging
from sphinx.util.docutils import SphinxDirective, switch_source_input
-from sphinx.util.nodes import nested_parse_with_titles
+from sphinx.util.parsing import nested_parse_to_nodes
if TYPE_CHECKING:
- from docutils.nodes import Element, Node
+ from docutils.nodes import Node
from docutils.parsers.rst.states import RSTState
from sphinx.config import Config
@@ -86,15 +86,12 @@ def parse_generated_content(state: RSTState, content: StringList, documenter: Do
"""Parse an item of content generated by Documenter."""
with switch_source_input(state, content):
if documenter.titles_allowed:
- node: Element = nodes.section()
- # necessary so that the child nodes get the right source/line set
- node.document = state.document
- nested_parse_with_titles(state, content, node)
- else:
- node = nodes.paragraph()
- node.document = state.document
- state.nested_parse(content, 0, node)
+ return nested_parse_to_nodes(state, content)
+ node = nodes.paragraph()
+ # necessary so that the child nodes get the right source/line set
+ node.document = state.document
+ state.nested_parse(content, 0, node, match_titles=False)
return node.children
diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py
index 7057f439b63..2d2d7f6de21 100644
--- a/sphinx/ext/autosummary/__init__.py
+++ b/sphinx/ext/autosummary/__init__.py
@@ -87,6 +87,7 @@
)
from sphinx.util.inspect import getmro, signature_from_str
from sphinx.util.matching import Matcher
+from sphinx.util.parsing import nested_parse_to_nodes
if TYPE_CHECKING:
from collections.abc import Sequence
@@ -406,16 +407,13 @@ def append_row(*column_texts: str) -> None:
row = nodes.row('')
source, line = self.state_machine.get_source_and_line()
for text in column_texts:
- node = nodes.paragraph('')
- vl = StringList()
- vl.append(text, '%s:%d:<autosummary>' % (source, line))
+ vl = StringList([text], f'{source}:{line}:<autosummary>')
with switch_source_input(self.state, vl):
- self.state.nested_parse(vl, 0, node)
- try:
- if isinstance(node[0], nodes.paragraph):
- node = node[0]
- except IndexError:
- pass
+ col_nodes = nested_parse_to_nodes(self.state, vl)
+ if col_nodes and isinstance(col_nodes[0], nodes.paragraph):
+ node = col_nodes[0]
+ else:
+ node = nodes.paragraph('')
row.append(nodes.entry('', node))
body.append(row)
diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py
index 9e6ce11a6b9..c2f008184b8 100644
--- a/sphinx/ext/graphviz.py
+++ b/sphinx/ext/graphviz.py
@@ -15,7 +15,7 @@
from urllib.parse import urlsplit, urlunsplit
from docutils import nodes
-from docutils.parsers.rst import Directive, directives
+from docutils.parsers.rst import directives
import sphinx
from sphinx.errors import SphinxError
@@ -91,12 +91,12 @@ class graphviz(nodes.General, nodes.Inline, nodes.Element):
pass
-def figure_wrapper(directive: Directive, node: graphviz, caption: str) -> nodes.figure:
+def figure_wrapper(directive: SphinxDirective, node: graphviz, caption: str) -> nodes.figure:
figure_node = nodes.figure('', node)
if 'align' in node:
figure_node['align'] = node.attributes.pop('align')
- inodes, messages = directive.state.inline_text(caption, directive.lineno)
+ inodes, messages = directive.parse_inline(caption)
caption_node = nodes.caption(caption, '', *inodes)
caption_node.extend(messages)
set_source_info(directive, caption_node)
diff --git a/sphinx/ext/ifconfig.py b/sphinx/ext/ifconfig.py
index 398d6699ff9..489920392a5 100644
--- a/sphinx/ext/ifconfig.py
+++ b/sphinx/ext/ifconfig.py
@@ -22,7 +22,6 @@
import sphinx
from sphinx.util.docutils import SphinxDirective
-from sphinx.util.nodes import nested_parse_with_titles
if TYPE_CHECKING:
from docutils.nodes import Node
@@ -48,7 +47,7 @@ def run(self) -> list[Node]:
node.document = self.state.document
self.set_source_info(node)
node['expr'] = self.arguments[0]
- nested_parse_with_titles(self.state, self.content, node, self.content_offset)
+ node += self.parse_content_to_nodes()
return [node]
diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py
index 6caf28ef658..c9fb4a25caf 100644
--- a/sphinx/transforms/i18n.py
+++ b/sphinx/transforms/i18n.py
@@ -406,12 +406,13 @@ def apply(self, **kwargs: Any) -> None:
# glossary terms update refid
if isinstance(node, nodes.term):
for _id in node['ids']:
- parts = split_term_classifiers(msgstr)
+ term, first_classifier = split_term_classifiers(msgstr)
patch = publish_msgstr(
- self.app, parts[0] or '', source, node.line, self.config, settings, # type: ignore[arg-type]
+ self.app, term or '', source, node.line, self.config, settings, # type: ignore[arg-type]
)
updater.patch = make_glossary_term(
- self.env, patch, parts[1] or '', source, node.line, _id, self.document, # type: ignore[arg-type]
+ self.env, patch, first_classifier or '',
+ source, node.line, _id, self.document, # type: ignore[arg-type]
)
processed = True
diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py
index 6a24d2e1114..bfdeeb362b1 100644
--- a/sphinx/util/docutils.py
+++ b/sphinx/util/docutils.py
@@ -22,6 +22,7 @@
from sphinx.errors import SphinxError
from sphinx.locale import _, __
from sphinx.util import logging
+from sphinx.util.parsing import inliner_parse_text, nested_parse_to_nodes
logger = logging.getLogger(__name__)
report_re = re.compile('^(.+?:(?:\\d+)?): \\((DEBUG|INFO|WARNING|ERROR|SEVERE)/(\\d+)?\\) ')
@@ -426,6 +427,40 @@ def get_location(self) -> str:
"""Get current location info for logging."""
return ':'.join(str(s) for s in self.get_source_info())
+ def parse_content_to_nodes(self) -> list[Node]:
+ """Parse the directive's content into nodes."""
+ return nested_parse_to_nodes(self.state, self.content, offset=self.content_offset)
+
+ def parse_text_to_nodes(self, text: str = '', /, *, offset: int = -1) -> list[Node]:
+ """Parse *text* into nodes.
+
+ :param text:
+ Text, in string form. ``StringList`` is also accepted.
+ :param offset:
+ The offset of the content.
+ """
+ if offset == -1:
+ offset = self.content_offset
+ return nested_parse_to_nodes(self.state, text, offset=offset)
+
+ def parse_inline(
+ self, text: str, *, lineno: int = -1,
+ ) -> tuple[list[Node], list[system_message]]:
+ """Parse *text* as inline elements.
+
+ :param text:
+ The text to parse, which should be a single line or paragraph.
+ This cannot contain any structural elements (headings,
+ transitions, directives, etc).
+ :param lineno:
+ The line number where the interpreted text begins.
+ :returns:
+ A list of nodes (text and inline elements) and a list of system_messages.
+ """
+ if lineno == -1:
+ lineno = self.lineno
+ return inliner_parse_text(text, state=self.state, lineno=lineno)
+
class SphinxRole:
"""A base class for Sphinx roles.
diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py
index bbc1f64e481..82672c2ff77 100644
--- a/sphinx/util/nodes.py
+++ b/sphinx/util/nodes.py
@@ -13,13 +13,14 @@
from sphinx import addnodes
from sphinx.locale import __
from sphinx.util import logging
+from sphinx.util.parsing import _fresh_title_style_context
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
from docutils.nodes import Element
from docutils.parsers.rst import Directive
- from docutils.parsers.rst.states import Inliner
+ from docutils.parsers.rst.states import Inliner, RSTState
from docutils.statemachine import StringList
from sphinx.builders import Builder
@@ -324,24 +325,20 @@ def traverse_translatable_index(
yield node, entries
-def nested_parse_with_titles(state: Any, content: StringList, node: Node,
+def nested_parse_with_titles(state: RSTState, content: StringList, node: Node,
content_offset: int = 0) -> str:
"""Version of state.nested_parse() that allows titles and does not require
titles to have the same decoration as the calling document.
This is useful when the parsed content comes from a completely different
context, such as docstrings.
+
+ This function is retained for compatability and will be deprecated in
+ Sphinx 8. Prefer ``parse_block_text()``.
"""
- # hack around title style bookkeeping
- surrounding_title_styles = state.memo.title_styles
- surrounding_section_level = state.memo.section_level
- state.memo.title_styles = []
- state.memo.section_level = 0
- try:
- return state.nested_parse(content, content_offset, node, match_titles=1)
- finally:
- state.memo.title_styles = surrounding_title_styles
- state.memo.section_level = surrounding_section_level
+ with _fresh_title_style_context(state):
+ ret = state.nested_parse(content, content_offset, node, match_titles=True)
+ return ret
def clean_astext(node: Element) -> str:
diff --git a/sphinx/util/parsing.py b/sphinx/util/parsing.py
new file mode 100644
index 00000000000..2cd39583534
--- /dev/null
+++ b/sphinx/util/parsing.py
@@ -0,0 +1,97 @@
+"""Docutils utility functions for parsing text."""
+
+from __future__ import annotations
+
+import contextlib
+from typing import TYPE_CHECKING
+
+from docutils import nodes
+from docutils.statemachine import StringList, string2lines
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+ from docutils.parsers.rst.states import Inliner, RSTState, Struct
+
+
+def nested_parse_to_nodes(
+ state: RSTState,
+ text: str | StringList,
+ *,
+ source: str = '<generated text>',
+ offset: int = 0,
+ keep_title_context: bool = False,
+) -> list[nodes.Node]: # Element | nodes.Text
+ """Parse *text* into nodes.
+
+ :param state:
+ The state machine state. Must be a subclass of ``RSTState``.
+ :param text:
+ Text, in string form. ``StringList`` is also accepted.
+ :param source:
+ The text's source, used when creating a new ``StringList``.
+ :param offset:
+ The offset of the content.
+ :param keep_title_context:
+ If this is False (the default), then *content* is parsed as if it were
+ an independent document, meaning that title decorations (e.g. underlines)
+ do not need to match the surrounding document.
+ This is useful when the parsed content comes from
+ a completely different context, such as docstrings.
+ If this is True, then title underlines must match those in
+ the surrounding document, otherwise errors will occur. TODO: check!
+ """
+ document = state.document
+ content = _text_to_string_list(
+ text, source=source, tab_width=document.settings.tab_width,
+ )
+ node = nodes.Element() # Anonymous container for parsing
+ node.document = document
+
+ if keep_title_context:
+ state.nested_parse(content, offset, node, match_titles=True)
+ else:
+ with _fresh_title_style_context(state):
+ state.nested_parse(content, offset, node, match_titles=True)
+ return node.children
+
+
+@contextlib.contextmanager
+def _fresh_title_style_context(state: RSTState) -> Iterator[None]:
+ # hack around title style bookkeeping
+ memo = state.memo
+ surrounding_title_styles: list[str | tuple[str, str]] = memo.title_styles
+ surrounding_section_level: int = memo.section_level
+ # clear current title styles
+ memo.title_styles = []
+ memo.section_level = 0
+ try:
+ yield
+ finally:
+ # reset title styles
+ memo.title_styles = surrounding_title_styles
+ memo.section_level = surrounding_section_level
+
+
+def inliner_parse_text(
+ text: str, *, state: RSTState, lineno: int = 1,
+) -> tuple[list[nodes.Node], list[nodes.system_message]]:
+ """Parse *text* as inline nodes.
+
+ The text cannot contain any structural elements (headings, transitions,
+ directives, etc), so should be a simple line or paragraph of text.
+ """
+ inliner: Inliner = state.inliner
+ memo: Struct = state.memo
+ parent: nodes.Element = state.parent
+ return inliner.parse(text, lineno, memo, parent)
+
+
+def _text_to_string_list(
+ text: str | StringList, /, *, source: str, tab_width: int,
+) -> StringList:
+ # Doesn't really belong in this module, but avoids circular imports.
+ if isinstance(text, StringList):
+ return text
+ content = string2lines(text, tab_width, convert_whitespace=True)
+ return StringList(content, source=source)
| diff --git a/tests/test_util/test_util_docutils_sphinx_directive.py b/tests/test_util/test_util_docutils_sphinx_directive.py
new file mode 100644
index 00000000000..281f61f6b9a
--- /dev/null
+++ b/tests/test_util/test_util_docutils_sphinx_directive.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from docutils import nodes
+from docutils.parsers.rst.languages import en as english # type: ignore[attr-defined]
+from docutils.parsers.rst.states import Inliner, RSTState, RSTStateMachine, state_classes
+from docutils.statemachine import StringList
+
+from sphinx.util.docutils import SphinxDirective, new_document
+
+
+def make_directive(*, env: SimpleNamespace, input_lines: StringList | None = None) -> SphinxDirective:
+ state, directive = make_directive_and_state(env=env, input_lines=input_lines)
+ return directive
+
+
+def make_directive_and_state(*, env: SimpleNamespace, input_lines: StringList | None = None) -> tuple[RSTState, SphinxDirective]:
+ sm = RSTStateMachine(state_classes, initial_state='Body')
+ sm.reporter = object()
+ if input_lines is not None:
+ sm.input_lines = input_lines
+ state = RSTState(sm)
+ state.document = new_document('<tests>')
+ state.document.settings.env = env
+ state.document.settings.tab_width = 4
+ state.document.settings.pep_references = None
+ state.document.settings.rfc_references = None
+ inliner = Inliner()
+ inliner.init_customizations(state.document.settings)
+ state.inliner = inliner
+ state.parent = None
+ state.memo = SimpleNamespace(
+ document=state.document,
+ language=english,
+ inliner=state.inliner,
+ reporter=state.document.reporter,
+ section_level=0,
+ title_styles=[],
+ )
+ directive = SphinxDirective(
+ name='test_directive',
+ arguments=[],
+ options={},
+ content=StringList(),
+ lineno=0,
+ content_offset=0,
+ block_text='',
+ state=state,
+ state_machine=state.state_machine,
+ )
+ return state, directive
+
+
+def test_sphinx_directive_env():
+ state, directive = make_directive_and_state(env=SimpleNamespace())
+
+ assert hasattr(directive, 'env')
+ assert directive.env is state.document.settings.env
+
+
+def test_sphinx_directive_config():
+ env = SimpleNamespace(config=object())
+ state, directive = make_directive_and_state(env=env)
+
+ assert hasattr(directive, 'config')
+ assert directive.config is directive.env.config
+ assert directive.config is state.document.settings.env.config
+
+
+def test_sphinx_directive_get_source_info():
+ env = SimpleNamespace()
+ input_lines = StringList(['spam'], source='<source>')
+ directive = make_directive(env=env, input_lines=input_lines)
+
+ assert directive.get_source_info() == ('<source>', 1)
+
+
+def test_sphinx_directive_set_source_info():
+ env = SimpleNamespace()
+ input_lines = StringList(['spam'], source='<source>')
+ directive = make_directive(env=env, input_lines=input_lines)
+
+ node = nodes.Element()
+ directive.set_source_info(node)
+ assert node.source == '<source>'
+ assert node.line == 1
+
+
+def test_sphinx_directive_get_location():
+ env = SimpleNamespace()
+ input_lines = StringList(['spam'], source='<source>')
+ directive = make_directive(env=env, input_lines=input_lines)
+
+ assert directive.get_location() == '<source>:1'
+
+
+def test_sphinx_directive_parse_content_to_nodes():
+ directive = make_directive(env=SimpleNamespace())
+ content = 'spam\n====\n\nEggs! *Lobster thermidor.*'
+ directive.content = StringList(content.split('\n'), source='<source>')
+
+ parsed = directive.parse_content_to_nodes()
+ assert len(parsed) == 1
+ node = parsed[0]
+ assert isinstance(node, nodes.section)
+ assert len(node.children) == 2
+ assert isinstance(node.children[0], nodes.title)
+ assert node.children[0].astext() == 'spam'
+ assert isinstance(node.children[1], nodes.paragraph)
+ assert node.children[1].astext() == 'Eggs! Lobster thermidor.'
+
+
+def test_sphinx_directive_parse_text_to_nodes():
+ directive = make_directive(env=SimpleNamespace())
+ content = 'spam\n====\n\nEggs! *Lobster thermidor.*'
+
+ parsed = directive.parse_text_to_nodes(content)
+ assert len(parsed) == 1
+ node = parsed[0]
+ assert isinstance(node, nodes.section)
+ assert len(node.children) == 2
+ assert isinstance(node.children[0], nodes.title)
+ assert node.children[0].astext() == 'spam'
+ assert isinstance(node.children[1], nodes.paragraph)
+ assert node.children[1].astext() == 'Eggs! Lobster thermidor.'
+
+
+def test_sphinx_directive_parse_inline():
+ directive = make_directive(env=SimpleNamespace())
+ content = 'Eggs! *Lobster thermidor.*'
+
+ parsed, messages = directive.parse_inline(content)
+ assert len(parsed) == 2
+ assert messages == []
+ assert parsed[0] == nodes.Text('Eggs! ')
+ assert isinstance(parsed[1], nodes.emphasis)
+ assert parsed[1].rawsource == '*Lobster thermidor.*'
+ assert parsed[1][0] == nodes.Text('Lobster thermidor.')
| diff --git a/CHANGES.rst b/CHANGES.rst
index be3293da1e6..a59acdfdbce 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -34,6 +34,18 @@ Features added
Patch by James Addison.
* #12319: ``sphinx.ext.extlinks``: Add ``extlink-{name}`` CSS class to links.
Patch by Hugo van Kemenade.
+* Add helper methods for parsing reStructuredText content into nodes from
+ within a directive.
+
+ - :py:meth:`~sphinx.util.docutils.SphinxDirective.parse_content_to_nodes()`
+ parses the directive's content and returns a list of Docutils nodes.
+ - :py:meth:`~sphinx.util.docutils.SphinxDirective.parse_text_to_nodes()`
+ parses the provided text and returns a list of Docutils nodes.
+ - :py:meth:`~sphinx.util.docutils.SphinxDirective.parse_inline()`
+ parses the provided text into inline elements and text nodes.
+
+ Patch by Adam Turner.
+
Bugs fixed
----------
| [
{
"components": [
{
"doc": "Parse the directive's content into nodes.",
"lines": [
430,
432
],
"name": "SphinxDirective.parse_content_to_nodes",
"signature": "def parse_content_to_nodes(self) -> list[Node]:",
"type": "function"
},
... | [
"tests/test_util/test_util_docutils_sphinx_directive.py::test_sphinx_directive_parse_content_to_nodes",
"tests/test_util/test_util_docutils_sphinx_directive.py::test_sphinx_directive_parse_text_to_nodes",
"tests/test_util/test_util_docutils_sphinx_directive.py::test_sphinx_directive_parse_inline"
] | [
"tests/test_util/test_util_docutils_sphinx_directive.py::test_sphinx_directive_env",
"tests/test_util/test_util_docutils_sphinx_directive.py::test_sphinx_directive_config",
"tests/test_util/test_util_docutils_sphinx_directive.py::test_sphinx_directive_get_source_info",
"tests/test_util/test_util_docutils_sphi... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add reStructuredText parsing functions to ``SphinxDirective``
As was colourfully espoused in #8039, it is harder than it ought to be to parse reStructuredText into nodes in a sphinx directive.
This PR adds three new functions:
* ``SphinxDirective.parse_content_to_nodes()``, to parse the entirety of ``SphinxDirective.content``
* ``SphinxDirective.parse_text_to_nodes()``, to parse a given string
* ``SphinxDirective.parse_inline()``, to parse a text that is inline-only
Yet to finish is documentation and tests, but I am opening now for early feedback.
A
----------
</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 sphinx/util/docutils.py]
(definition of SphinxDirective.parse_content_to_nodes:)
def parse_content_to_nodes(self) -> list[Node]:
"""Parse the directive's content into nodes."""
(definition of SphinxDirective.parse_text_to_nodes:)
def parse_text_to_nodes(self, text: str = '', /, *, offset: int = -1) -> list[Node]:
"""Parse *text* into nodes.
:param text:
Text, in string form. ``StringList`` is also accepted.
:param offset:
The offset of the content."""
(definition of SphinxDirective.parse_inline:)
def parse_inline( self, text: str, *, lineno: int = -1, ) -> tuple[list[Node], list[system_message]]:
"""Parse *text* as inline elements.
:param text:
The text to parse, which should be a single line or paragraph.
This cannot contain any structural elements (headings,
transitions, directives, etc).
:param lineno:
The line number where the interpreted text begins.
:returns:
A list of nodes (text and inline elements) and a list of system_messages."""
[end of new definitions in sphinx/util/docutils.py]
[start of new definitions in sphinx/util/parsing.py]
(definition of nested_parse_to_nodes:)
def nested_parse_to_nodes( state: RSTState, text: str | StringList, *, source: str = '<generated text>', offset: int = 0, keep_title_context: bool = False, ) -> list[nodes.Node]:
"""Parse *text* into nodes.
:param state:
The state machine state. Must be a subclass of ``RSTState``.
:param text:
Text, in string form. ``StringList`` is also accepted.
:param source:
The text's source, used when creating a new ``StringList``.
:param offset:
The offset of the content.
:param keep_title_context:
If this is False (the default), then *content* is parsed as if it were
an independent document, meaning that title decorations (e.g. underlines)
do not need to match the surrounding document.
This is useful when the parsed content comes from
a completely different context, such as docstrings.
If this is True, then title underlines must match those in
the surrounding document, otherwise errors will occur. TODO: check!"""
(definition of _fresh_title_style_context:)
def _fresh_title_style_context(state: RSTState) -> Iterator[None]:
(definition of inliner_parse_text:)
def inliner_parse_text( text: str, *, state: RSTState, lineno: int = 1, ) -> tuple[list[nodes.Node], list[nodes.system_message]]:
"""Parse *text* as inline nodes.
The text cannot contain any structural elements (headings, transitions,
directives, etc), so should be a simple line or paragraph of text."""
(definition of _text_to_string_list:)
def _text_to_string_list( text: str | StringList, /, *, source: str, tab_width: int, ) -> StringList:
[end of new definitions in sphinx/util/parsing.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>> | 35e7bfc347f845deff50787f0cd0340ea2ea0a5d | |
joke2k__faker-2068 | 2,068 | joke2k/faker | null | 554d1aa1ce75ff26cf36e35fa9aafb9f03d1e5f4 | 2024-06-28T19:05:15Z | diff --git a/faker/providers/person/sw/__init__.py b/faker/providers/person/sw/__init__.py
new file mode 100644
index 0000000000..6557496cb6
--- /dev/null
+++ b/faker/providers/person/sw/__init__.py
@@ -0,0 +1,409 @@
+from .. import Provider as PersonProvider
+
+
+class Provider(PersonProvider):
+ """
+ A Faker provider for generating fake Swahili.
+ """
+
+ formats = (
+ "{{first_name_male}} {{last_name_male}}",
+ "{{first_name_male}} {{last_name_male}}",
+ "{{first_name_male}} {{last_name_male}}",
+ "{{first_name_male}} {{last_name_male}}",
+ "{{first_name_male}} {{last_name_male}} {{last_name_male}}",
+ "{{first_name_female}} {{last_name_female}}",
+ "{{first_name_female}} {{last_name_female}}",
+ "{{first_name_female}} {{last_name_female}}",
+ "{{first_name_female}} {{last_name_female}}",
+ "{{first_name_female}} {{last_name_female}} {{last_name_female}}",
+ "{{prefix_male}} {{first_name_male}} {{last_name_male}}",
+ "{{prefix_female}} {{first_name_female}} {{last_name_female}}",
+ "{{prefix_male}} {{first_name_male}} {{last_name_male}}",
+ "{{prefix_female}} {{first_name_female}} {{last_name_female}}",
+ )
+
+ # first names sourced from:
+ # 1. https://www.behindthename.com/submit/names/gender/masculine/usage/swahili
+ # 2. https://github.com/faker-js/faker/blob/next/src/locales/yo_NG/person/male_first_name.ts
+
+ first_names_male = (
+ "Abdu",
+ "Aijuka",
+ "Amri",
+ "Andwele",
+ "Angalia",
+ "Angavu",
+ "Anoni",
+ "Asani",
+ "Asanti",
+ "Athumani",
+ "Azizi",
+ "Bahari",
+ "Bale",
+ "Balinda",
+ "Beshte",
+ "Bibuwa",
+ "Boma",
+ "Cheusi",
+ "Chuki",
+ "Dai",
+ "Daudi",
+ "Duma",
+ "Dunia",
+ "Ëakumbu",
+ "Ekundu",
+ "Eliakimu",
+ "Enzi",
+ "Evance",
+ "Fahari",
+ "Fanaka",
+ "Faraja",
+ "Hadithi",
+ "Hamis",
+ "Harambee",
+ "Hekima",
+ "Isaya",
+ "Issack",
+ "Ituri",
+ "Jalia",
+ "Jangwa",
+ "Jelani",
+ "Jua",
+ "Jumaane",
+ "Justiniani",
+ "Kaombwe",
+ "Kashangaki",
+ "Kenyangi",
+ "Khamani",
+ "Khamisi",
+ "Kiapo",
+ "Kiburi",
+ "Kijana",
+ "Kijani",
+ "Kimbilio",
+ "Kinubi",
+ "Kipenzi",
+ "Kiume",
+ "Kondo",
+ "Konradi",
+ "Kovu",
+ "Kurunzi",
+ "Kusiima",
+ "Makini",
+ "Makunga",
+ "Makuu",
+ "Matunda",
+ "Mavuno",
+ "Mohamedi",
+ "Mulele",
+ "Mwezi",
+ "Ngamia",
+ "Ngeni",
+ "Ntimi",
+ "Nuhu",
+ "Nuriat",
+ "Nwabudike",
+ "Osogo",
+ "Pambe",
+ "Pelaji",
+ "Popobawa",
+ "Pumbaa",
+ "Rashidi",
+ "Reshoni",
+ "Risasi",
+ "Rua",
+ "Rubani",
+ "Ruhiu",
+ "Rungo",
+ "Sabari",
+ "Sadaka",
+ "Sadiki",
+ "Safari",
+ "Samweli",
+ "Seif",
+ "Shida",
+ "Sifa",
+ "Siku",
+ "Takatifu",
+ "Thabiti",
+ "Tisa",
+ "Tufani",
+ "Tukufu",
+ "Ushindi",
+ "Usiku",
+ "Uzima",
+ "Wamwema",
+ "Yakobo",
+ "Yohana",
+ "Yohane",
+ "Zahur",
+ "Zende",
+ "Zuba",
+ "Zuhri",
+ "Zwatie",
+ )
+ first_names_female = (
+ "Abigaili",
+ "Adhra",
+ "Adia",
+ "Adimu",
+ "Akumu",
+ "Almasi",
+ "Amani",
+ "Amondi",
+ "Anasa",
+ "Angalia",
+ "Arusi",
+ "Asali",
+ "Asanti",
+ "Asatira",
+ "Asmini",
+ "Atiena",
+ "Bahari",
+ "Boma",
+ "Busara",
+ "Chaniya",
+ "Chausiki",
+ "Chipukizi",
+ "Chuki",
+ "Dainess",
+ "Dalili",
+ "Enzi",
+ "Evance",
+ "Fahari",
+ "Faisa",
+ "Fanaka",
+ "Faraja",
+ "Farhiya",
+ "Farijika",
+ "Gethera",
+ "Goma",
+ "Haiba",
+ "Halisi",
+ "Hanja",
+ "Hashiki",
+ "Hatima",
+ "Hawehindi",
+ "Hekima",
+ "Hidaya",
+ "Hodari",
+ "Humaiya",
+ "Imany",
+ "Imara",
+ "Itanya",
+ "Jahi",
+ "Jana",
+ "Jasiri",
+ "Jina",
+ "Jua",
+ "Kaluwa",
+ "Kaombwe",
+ "Karama",
+ "Kaskazi",
+ "Kiah",
+ "Kibafupia",
+ "Kibibi",
+ "Kiburi",
+ "Kijana",
+ "Kimya",
+ "Kinaya",
+ "Kiojah",
+ "Kipenzi",
+ "Kipepeo",
+ "Kisima",
+ "Kiwara",
+ "Kuchanua",
+ "Kweli",
+ "Lailati",
+ "Laini",
+ "Madaha",
+ "Madini",
+ "Madoa",
+ "Mahali",
+ "Maisha",
+ "Majani",
+ "Makini",
+ "Maliza",
+ "Marini",
+ "Marjani",
+ "Matunda",
+ "Maua",
+ "Misuli",
+ "Mkarkara",
+ "Mrihani",
+ "Muhima",
+ "Musila",
+ "Mwamini",
+ "Mwasaa",
+ "Najuma",
+ "Naki",
+ "Nashipie",
+ "Nasra",
+ "Nathari",
+ "Nayfa",
+ "Nelah",
+ "Niara",
+ "Nigesa",
+ "Njozi",
+ "Nula",
+ "Nyasi",
+ "Nyoka",
+ "Nyoni",
+ "Nyota",
+ "Nyuki",
+ "Opwonya",
+ "Panya",
+ "Paskalia",
+ "Reshoni",
+ "Rua",
+ "Sabari",
+ "Sadao",
+ "Safari",
+ "Safiri",
+ "Sarabi",
+ "Sarafina",
+ "Sauti",
+ "Serafina",
+ "Shani",
+ "Shawana",
+ "Shida",
+ "Sifa",
+ "Siku",
+ "Skolastika",
+ "Sungara",
+ "Swala",
+ "Tambika",
+ "Tamu",
+ "Ta-tanisha",
+ "Tisa",
+ "Tuere",
+ "Tufani",
+ "Udeera",
+ "Ujamaa",
+ "Umande",
+ "Umoja",
+ "Uzima",
+ "Waceera",
+ "Wamwema",
+ "Waridi",
+ "Waseme",
+ "Yasinta",
+ "Zahnya",
+ "Zaituni",
+ "Zumaridi",
+ "Zuwena",
+ )
+
+ first_names = first_names_male + first_names_female
+
+ # last names sourced from :
+ # 1.https://www.familyeducation.com/baby-names/surname/origin/kenyan
+ last_names_male = (
+ "Abwao",
+ "Adamu",
+ "Baharia",
+ "Dhadho",
+ "Fuli",
+ "Hassani",
+ "Juma",
+ "Kahinu",
+ "Kimachu",
+ "Kitumaini",
+ "Madhubuti",
+ "Magombo",
+ "Mathenge",
+ "Msuya",
+ "Naomi",
+ "Nazari",
+ "Rikke",
+ "Sayyid",
+ "Simba",
+ "Sinema",
+ "Wario",
+ "Yudas",
+ "Abdi",
+ "Ali",
+ "Akinyi",
+ "Anyango",
+ "Juma",
+ "Kamau",
+ "Kibet",
+ "Kimani",
+ "Maina",
+ "Mwangi",
+ "Obama",
+ "Ochieng",
+ "Onyango",
+ "Otieno",
+ "Mohamed",
+ "Hassan",
+ "Wafula",
+ "Wanjala",
+ "Atieno",
+ "Kariuki",
+ "Kimutai",
+ "Kipkorir",
+ "Kipkirui",
+ "Kipkemei",
+ "Kiplagat",
+ "Kiprono",
+ "Kipsang",
+ "Kiptoo",
+ "Kipruto",
+ "Mumbi",
+ "Muthoni",
+ "Njeri",
+ "Njoroge",
+ "Odhiambo",
+ "Omondi",
+ "Owuor",
+ "Wanijiku",
+ "Wambui",
+ "Abdullahi",
+ "Adan",
+ "Ahmed",
+ "Auma",
+ "Barasa",
+ "Hussein",
+ "Ibrahim",
+ "John",
+ "Mutai",
+ "Omar",
+ "Ouma",
+ "Waweru",
+ )
+
+ # last names are not sex dependant
+ last_names_female = last_names_male
+ last_names = last_names_male + last_names_female
+
+ prefixes_female = (
+ "Mrs.",
+ "Ms.",
+ "Dr.",
+ "Bi.",
+ "Mama",
+ "Bibi",
+ "Madam",
+ "Chief",
+ "Dkt.",
+ "Mheshimiwa",
+ "Mwalimu",
+ "Mtukufu",
+ "Malkia",
+ "Mwanamke",
+ )
+
+ prefixes_male = (
+ "Mr.",
+ "Dr.",
+ "Bwana",
+ "Mzee",
+ "Bw.",
+ "Dkt.",
+ "Mheshimiwa",
+ "Mwalimu",
+ "Mtukufu",
+ "Mfalme",
+ )
| diff --git a/tests/providers/test_person.py b/tests/providers/test_person.py
index ee5ac15720..5cece79ef7 100644
--- a/tests/providers/test_person.py
+++ b/tests/providers/test_person.py
@@ -32,6 +32,7 @@
from faker.providers.person.ru_RU import translit
from faker.providers.person.sk_SK import Provider as SkSKProvider
from faker.providers.person.sv_SE import Provider as SvSEProvider
+from faker.providers.person.sw import Provider as SwProvider
from faker.providers.person.ta_IN import Provider as TaINProvider
from faker.providers.person.th_TH import Provider as ThThProvider
from faker.providers.person.uk_UA import Provider as UkUAProvider
@@ -1477,6 +1478,85 @@ def test_full_name(self):
raise AssertionError("Invalid number of name parts. Expected 2 or 3.")
+class TestSw(unittest.TestCase):
+ def setUp(self):
+ self.fake = Faker("sw")
+ Faker.seed(0)
+
+ def test_last_name(self):
+ """
+ Test the generation of Swahili last names.
+ """
+ # There's no gender-specific last name in Swahili.
+ self.assertTrue(hasattr(SwProvider, "last_names_male"))
+ self.assertTrue(hasattr(SwProvider, "last_names_female"))
+
+ # All last names apply to all genders.
+ self.assertTrue(hasattr(SwProvider, "last_names"))
+
+ # General last name.
+ name = self.fake.last_name()
+ self.assertIsInstance(name, str)
+ self.assertIn(name, SwProvider.last_names)
+
+ # Females last name.
+ name = self.fake.last_name_female()
+ self.assertIsInstance(name, str)
+ self.assertIn(name, SwProvider.last_names)
+
+ # Male last name.
+ name = self.fake.last_name_male()
+ self.assertIsInstance(name, str)
+ self.assertIn(name, SwProvider.last_names)
+
+ def test_first_name(self):
+ """
+ Test the generation of Swahili first names.
+ """
+ # General first name.
+ name = self.fake.first_name()
+ self.assertIsInstance(name, str)
+ self.assertIn(name, SwProvider.first_names)
+
+ # Female first name.
+ name = self.fake.first_name_female()
+ self.assertIsInstance(name, str)
+ self.assertIn(name, SwProvider.first_names)
+ self.assertIn(name, SwProvider.first_names_female)
+
+ # Male first name.
+ name = self.fake.first_name_male()
+ self.assertIsInstance(name, str)
+ self.assertIn(name, SwProvider.first_names)
+ self.assertIn(name, SwProvider.first_names_male)
+
+ def test_full_name(self):
+ """
+ Test the generation of full Swahili names.
+ """
+ # Full name.
+ name = self.fake.name()
+ self.assertIsInstance(name, str)
+
+ full_name_parts = name.split()
+
+ if len(full_name_parts) == 2:
+ first_name = full_name_parts[0]
+ last_name = full_name_parts[1]
+ self.assertIn(first_name, SwProvider.first_names)
+ self.assertIn(last_name, SwProvider.last_names)
+ elif len(full_name_parts) == 3:
+ prefix = full_name_parts[0]
+ first_name = full_name_parts[1]
+ last_name = full_name_parts[2]
+
+ self.assertIn(prefix, SwProvider.prefixes_female + SwProvider.prefixes_male)
+ self.assertIn(first_name, SwProvider.first_names)
+ self.assertIn(last_name, SwProvider.last_names)
+ else:
+ raise AssertionError("Invalid number of name parts. Expected 2 or 3.")
+
+
class TestZuZa(unittest.TestCase):
def setUp(self):
self.fake = Faker("zu_ZA")
| [
{
"components": [
{
"doc": "A Faker provider for generating fake Swahili.",
"lines": [
4,
408
],
"name": "Provider",
"signature": "class Provider(PersonProvider):",
"type": "class"
}
],
"file": "faker/providers/person/sw/__i... | [
"tests/providers/test_person.py::TestAr::test_first_name",
"tests/providers/test_person.py::TestAr::test_last_name",
"tests/providers/test_person.py::TestAzAz::test_first_name",
"tests/providers/test_person.py::TestAzAz::test_last_name",
"tests/providers/test_person.py::TestNlBE::test_first_name",
"tests/... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Add Swahili provider for generating Swahili names.
{}
----------
</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/person/sw/__init__.py]
(definition of Provider:)
class Provider(PersonProvider):
"""A Faker provider for generating fake Swahili."""
[end of new definitions in faker/providers/person/sw/__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 | ||
tobymao__sqlglot-3708 | 3,708 | tobymao/sqlglot | null | adf3039e5b5f6c63a8e32312724a21c0cda307df | 2024-06-27T10:49:09Z | diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py
index ca7011398c..3422c13b6f 100644
--- a/sqlglot/dialects/bigquery.py
+++ b/sqlglot/dialects/bigquery.py
@@ -346,6 +346,7 @@ class Parser(parser.Parser):
"JSON_EXTRACT_SCALAR": lambda args: exp.JSONExtractScalar(
this=seq_get(args, 0), expression=seq_get(args, 1) or exp.Literal.string("$")
),
+ "LENGTH": lambda args: exp.Length(this=seq_get(args, 0), binary=True),
"MD5": exp.MD5Digest.from_arg_list,
"TO_HEX": _build_to_hex,
"PARSE_DATE": lambda args: build_formatted_time(exp.StrToDate, "bigquery")(
diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index 296405d381..575f2e3929 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -738,3 +738,33 @@ def withingroup_sql(self, expression: exp.WithinGroup) -> str:
this = self.sql(expression, "this").rstrip(")")
return f"{this}{expression_sql})"
+
+ def length_sql(self, expression: exp.Length) -> str:
+ arg = expression.this
+
+ # Dialects like BQ and Snowflake also accept binary values as args, so
+ # DDB will attempt to infer the type or resort to case/when resolution
+ if not expression.args.get("binary") or arg.is_string:
+ return self.func("LENGTH", arg)
+
+ if not arg.type:
+ from sqlglot.optimizer.annotate_types import annotate_types
+
+ arg = annotate_types(arg)
+
+ if arg.is_type(*exp.DataType.TEXT_TYPES):
+ return self.func("LENGTH", arg)
+
+ # We need these casts to make duckdb's static type checker happy
+ blob = exp.cast(arg, exp.DataType.Type.VARBINARY)
+ varchar = exp.cast(arg, exp.DataType.Type.VARCHAR)
+
+ case = (
+ exp.case(self.func("TYPEOF", arg))
+ .when(
+ "'VARCHAR'", exp.Anonymous(this="LENGTH", expressions=[varchar])
+ ) # anonymous to break length_sql recursion
+ .when("'BLOB'", self.func("OCTET_LENGTH", blob))
+ )
+
+ return self.sql(case)
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index 8bd1f77373..c773380183 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -282,6 +282,8 @@ class Parser(parser.Parser):
"LAST_DAY": lambda args: exp.LastDay(
this=seq_get(args, 0), unit=map_date_part(seq_get(args, 1))
),
+ "LEN": lambda args: exp.Length(this=seq_get(args, 0), binary=True),
+ "LENGTH": lambda args: exp.Length(this=seq_get(args, 0), binary=True),
"LISTAGG": exp.GroupConcat.from_arg_list,
"MEDIAN": lambda args: exp.PercentileCont(
this=seq_get(args, 0), expression=exp.Literal.number(0.5)
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 7d6d515110..9ed4a86edb 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -5524,6 +5524,7 @@ class Right(Func):
class Length(Func):
+ arg_types = {"this": True, "binary": False}
_sql_names = ["LENGTH", "LEN"]
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index ec99230e70..0491ec5b78 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -4005,3 +4005,6 @@ def parsejson_sql(self, expression: exp.ParseJSON) -> str:
return self.sql(expression.this)
return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
+
+ def length_sql(self, expression: exp.Length) -> str:
+ return self.func("LENGTH", expression.this)
| diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py
index d3307b8804..b8bc01f76c 100644
--- a/tests/dialects/test_bigquery.py
+++ b/tests/dialects/test_bigquery.py
@@ -1375,6 +1375,18 @@ def test_bigquery(self):
"bigquery": "SELECT DATETIME('2020-01-01', 'America/Los_Angeles')",
},
)
+ self.validate_all(
+ "SELECT LENGTH(foo)",
+ read={
+ "bigquery": "SELECT LENGTH(foo)",
+ "snowflake": "SELECT LENGTH(foo)",
+ },
+ write={
+ "duckdb": "SELECT CASE TYPEOF(foo) WHEN 'VARCHAR' THEN LENGTH(CAST(foo AS TEXT)) WHEN 'BLOB' THEN OCTET_LENGTH(CAST(foo AS BLOB)) END",
+ "snowflake": "SELECT LENGTH(foo)",
+ "": "SELECT LENGTH(foo)",
+ },
+ )
def test_errors(self):
with self.assertRaises(TokenError):
diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py
index 01a01167f1..12d6f4b2de 100644
--- a/tests/dialects/test_duckdb.py
+++ b/tests/dialects/test_duckdb.py
@@ -793,6 +793,8 @@ def test_duckdb(self):
},
)
+ self.validate_identity("SELECT LENGTH(foo)")
+
def test_array_index(self):
with self.assertLogs(helper_logger) as cm:
self.validate_all(
| [] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery"
] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_errors",
"tests/dialects/test_bigquery.py::TestBigQuery::test_gap_fill",
"tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat",
"tests/dialects/test_bigquery.py::TestBigQuery::test_json_object",
"tests/dialects/test_bigquery.py::TestBigQuery:... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(duckdb): Transpile exp.Length from other dialects
Add generation for `exp.Length` in DuckDB.
Dialects like Snowflake and BigQuery also use `LENGTH() / LEN()` for binary values, so this PR will generate `LENGTH(<expr>)` if the type can be inferred or a case/when with `LENGTH` for `VARCHAR` and `OCTET_LENGTH` for the binary (`BLOB`) value.
----------
</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>
</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 | ||
astropy__astropy-16620 | 16,620 | astropy/astropy | v5.3 | 9a7002fcf4de719116a6bf3b9752fcb41f5a44f2 | 2024-06-26T19:47:33Z | diff --git a/astropy/units/format/base.py b/astropy/units/format/base.py
index 1c417d92cd00..5644f115811a 100644
--- a/astropy/units/format/base.py
+++ b/astropy/units/format/base.py
@@ -4,10 +4,12 @@
from typing import TYPE_CHECKING
+from astropy.utils import classproperty
+
from . import utils
if TYPE_CHECKING:
- from collections.abc import Iterable
+ from collections.abc import Callable, Iterable
from typing import ClassVar, Literal
import numpy as np
@@ -42,6 +44,13 @@ def __init_subclass__(cls, **kwargs):
Base.registry[cls.name] = cls
super().__init_subclass__(**kwargs)
+ @classproperty(lazy=True)
+ def _fraction_formatters(cls) -> dict[bool | str, Callable[[str, str, str], str]]:
+ return {
+ True: cls._format_inline_fraction,
+ "inline": cls._format_inline_fraction,
+ }
+
@classmethod
def format_exponential_notation(
cls, val: float | np.number, format_spec: str = ".8g"
@@ -101,20 +110,9 @@ def _format_unit_list(cls, units: Iterable[tuple[NamedUnit, Real]]) -> str:
)
@classmethod
- def _format_fraction(
- cls,
- scale: str,
- numerator: str,
- denominator: str,
- *,
- fraction: Literal[True, "inline"] = "inline",
+ def _format_inline_fraction(
+ cls, scale: str, numerator: str, denominator: str
) -> str:
- if not (fraction is True or fraction == "inline"):
- raise ValueError(
- "format {cls.name!r} only supports inline fractions,"
- f"not fraction={fraction!r}."
- )
-
if cls._space in denominator:
denominator = f"({denominator})"
if scale and numerator == "1":
@@ -123,7 +121,7 @@ def _format_fraction(
@classmethod
def to_string(
- cls, unit: UnitBase, *, fraction: bool | Literal["inline", "multiline"] = True
+ cls, unit: UnitBase, *, fraction: bool | Literal["inline"] = True
) -> str:
"""Convert a unit to its string representation.
@@ -151,34 +149,44 @@ def to_string(
# First the scale. Normally unity, in which case we omit
# it, but non-unity scale can happen, e.g., in decompositions
# like u.Ry.decompose(), which gives "2.17987e-18 kg m2 / s2".
- if unit.scale == 1:
- s = ""
- else:
- s = cls.format_exponential_notation(unit.scale)
-
- # Now the unit baes, taking care that dimensionless does not have any
- # (but can have a scale; e.g., u.percent.decompose() gives "0.01").
- if len(unit.bases):
- if s:
- s += cls._scale_unit_separator
- if fraction:
- numerator, denominator = utils.get_grouped_by_powers(
- unit.bases, unit.powers
- )
- else:
- numerator = list(zip(unit.bases, unit.powers))
- denominator = []
- if len(denominator):
- if len(numerator):
- numerator = cls._format_unit_list(numerator)
- else:
- numerator = "1"
- denominator = cls._format_unit_list(denominator)
- s = cls._format_fraction(s, numerator, denominator, fraction=fraction)
+ s = "" if unit.scale == 1 else cls.format_exponential_notation(unit.scale)
+
+ # dimensionless does not have any bases, but can have a scale;
+ # e.g., u.percent.decompose() gives "0.01".
+ if not unit.bases:
+ return s
+
+ if s:
+ s += cls._scale_unit_separator
+ # Unit powers are monotonically decreasing
+ if not fraction or unit.powers[-1] > 0:
+ return s + cls._format_unit_list(zip(unit.bases, unit.powers, strict=True))
+
+ positive = []
+ negative = []
+ for base, power in zip(unit.bases, unit.powers, strict=True):
+ if power > 0:
+ positive.append((base, power))
else:
- s += cls._format_unit_list(numerator)
-
- return s
+ negative.append((base, -power))
+ try:
+ return cls._fraction_formatters[fraction](
+ s,
+ cls._format_unit_list(positive) or "1",
+ cls._format_unit_list(negative),
+ )
+ except KeyError:
+ # We accept Booleans, but don't advertise them in the error message
+ *all_but_last, last = (
+ repr(key) for key in cls._fraction_formatters if isinstance(key, str)
+ )
+ supported_formats = (
+ f"{', '.join(all_but_last)} or {last}" if all_but_last else last
+ )
+ raise ValueError(
+ f"{cls.name!r} format only supports {supported_formats} "
+ f"fractions, not {fraction=!r}."
+ ) from None
@classmethod
def parse(cls, s: str) -> UnitBase:
diff --git a/astropy/units/format/cds.py b/astropy/units/format/cds.py
index 8ba62f3d8f90..e92327fb2b99 100644
--- a/astropy/units/format/cds.py
+++ b/astropy/units/format/cds.py
@@ -299,7 +299,7 @@ def format_exponential_notation(
@classmethod
def to_string(
- cls, unit: UnitBase, fraction: bool | Literal["inline", "multiline"] = False
+ cls, unit: UnitBase, fraction: bool | Literal["inline"] = False
) -> str:
# Remove units that aren't known to the format
unit = utils.decompose_to_known_units(
diff --git a/astropy/units/format/console.py b/astropy/units/format/console.py
index b350d22dac9e..c3586a06e2f0 100644
--- a/astropy/units/format/console.py
+++ b/astropy/units/format/console.py
@@ -8,9 +8,12 @@
from typing import TYPE_CHECKING
+from astropy.utils import classproperty
+
from . import base
if TYPE_CHECKING:
+ from collections.abc import Callable
from typing import ClassVar, Literal
from astropy.units import UnitBase
@@ -37,24 +40,20 @@ class Console(base.Base):
_line: ClassVar[str] = "-"
_space: ClassVar[str] = " "
+ @classproperty(lazy=True)
+ def _fraction_formatters(cls) -> dict[bool | str, Callable[[str, str, str], str]]:
+ return super()._fraction_formatters | {
+ "multiline": cls._format_multiline_fraction
+ }
+
@classmethod
def _format_superscript(cls, number: str) -> str:
return f"^{number}"
@classmethod
- def _format_fraction(
- cls,
- scale: str,
- numerator: str,
- denominator: str,
- *,
- fraction: Literal[True, "inline", "multiline"] = "multiline",
+ def _format_multiline_fraction(
+ cls, scale: str, numerator: str, denominator: str
) -> str:
- if fraction != "multiline":
- return super()._format_fraction(
- scale, numerator, denominator, fraction=fraction
- )
-
fraclength = max(len(numerator), len(denominator))
f = f"{{0:<{len(scale)}s}}{{1:^{fraclength}s}}"
diff --git a/astropy/units/format/latex.py b/astropy/units/format/latex.py
index 500b39e9a1c6..13af2b8a8deb 100644
--- a/astropy/units/format/latex.py
+++ b/astropy/units/format/latex.py
@@ -57,19 +57,9 @@ def _format_unit_power(cls, unit: NamedUnit, power: Real = 1) -> str:
return name
@classmethod
- def _format_fraction(
- cls,
- scale: str,
- numerator: str,
- denominator: str,
- *,
- fraction: Literal[True, "inline", "multiline"] = "multiline",
+ def _format_multiline_fraction(
+ cls, scale: str, numerator: str, denominator: str
) -> str:
- if fraction != "multiline":
- return super()._format_fraction(
- scale, numerator, denominator, fraction=fraction
- )
-
return rf"{scale}\frac{{{numerator}}}{{{denominator}}}"
@classmethod
diff --git a/astropy/units/format/utils.py b/astropy/units/format/utils.py
index 156b4982b706..ecb63298cb1c 100644
--- a/astropy/units/format/utils.py
+++ b/astropy/units/format/utils.py
@@ -13,46 +13,10 @@
if TYPE_CHECKING:
from collections.abc import Callable, Generator, Iterable, Sequence
- from typing import TypeVar
from astropy.units import UnitBase
from astropy.units.typing import Real
- T = TypeVar("T")
-
-
-def get_grouped_by_powers(
- bases: Sequence[T], powers: Sequence[int]
-) -> tuple[list[tuple[T, int]], list[tuple[T, int]]]:
- """
- Groups the powers and bases in the given
- `~astropy.units.CompositeUnit` into positive powers and
- negative powers for easy display on either side of a solidus.
-
- Parameters
- ----------
- bases : list of `astropy.units.UnitBase` instances
-
- powers : list of int
-
- Returns
- -------
- positives, negatives : list of tuple of |Unit| and power
- Each element in each list is tuple of the form (*base*,
- *power*). The negatives have the sign of their power reversed
- (i.e. the powers are all positive).
- """
- positive = []
- negative = []
- for base, power in zip(bases, powers):
- if power < 0:
- negative.append((base, -power))
- elif power > 0:
- positive.append((base, power))
- else:
- raise ValueError("Unit with 0 power")
- return positive, negative
-
def decompose_to_known_units(
unit: UnitBase, func: Callable[[UnitBase], None]
diff --git a/astropy/units/format/vounit.py b/astropy/units/format/vounit.py
index f9ecc6a1abca..02cc22ed65f8 100644
--- a/astropy/units/format/vounit.py
+++ b/astropy/units/format/vounit.py
@@ -171,13 +171,9 @@ def format_exponential_notation(cls, val, format_spec=".8g"):
return super().format_exponential_notation(val, format_spec)
@classmethod
- def _format_fraction(cls, scale, numerator, denominator, *, fraction="inline"):
- if not (fraction is True or fraction == "inline"):
- raise ValueError(
- "format {cls.name!r} only supports inline fractions,"
- f"not fraction={fraction!r}."
- )
-
+ def _format_inline_fraction(
+ cls, scale: str, numerator: str, denominator: str
+ ) -> str:
if cls._space in denominator:
denominator = f"({denominator})"
if scale and numerator == "1":
| diff --git a/astropy/units/tests/test_format.py b/astropy/units/tests/test_format.py
index fef2c74ade3c..9434cf6084bb 100644
--- a/astropy/units/tests/test_format.py
+++ b/astropy/units/tests/test_format.py
@@ -569,17 +569,26 @@ def test_format_styles_non_default_fraction(format_spec, fraction, string, decom
@pytest.mark.parametrize("format_spec", ["generic", "cds", "fits", "ogip", "vounit"])
def test_no_multiline_fraction(format_spec):
fluxunit = u.W / u.m**2
- with pytest.raises(ValueError, match="only supports.*not fraction='multiline'"):
+ with pytest.raises(
+ ValueError,
+ match=(
+ f"^'{format_spec}' format only supports 'inline' fractions, "
+ r"not fraction='multiline'\.$"
+ ),
+ ):
fluxunit.to_string(format_spec, fraction="multiline")
-@pytest.mark.parametrize(
- "format_spec",
- ["generic", "cds", "fits", "ogip", "vounit", "latex", "console", "unicode"],
-)
+@pytest.mark.parametrize("format_spec", ["latex", "console", "unicode"])
def test_unknown_fraction_style(format_spec):
fluxunit = u.W / u.m**2
- with pytest.raises(ValueError, match="only supports.*parrot"):
+ with pytest.raises(
+ ValueError,
+ match=(
+ f"^'{format_spec}' format only supports 'inline' or 'multiline' fractions, "
+ r"not fraction='parrot'\.$"
+ ),
+ ):
fluxunit.to_string(format_spec, fraction="parrot")
| [
{
"components": [
{
"doc": "",
"lines": [
48,
51
],
"name": "Base._fraction_formatters",
"signature": "def _fraction_formatters(cls) -> dict[bool | str, Callable[[str, str, str], str]]:",
"type": "function"
},
{
"doc":... | [
"astropy/units/tests/test_format.py::test_no_multiline_fraction[generic]",
"astropy/units/tests/test_format.py::test_no_multiline_fraction[cds]",
"astropy/units/tests/test_format.py::test_no_multiline_fraction[fits]",
"astropy/units/tests/test_format.py::test_no_multiline_fraction[ogip]",
"astropy/units/tes... | [
"astropy/units/tests/test_format.py::test_unit_grammar[m",
"astropy/units/tests/test_format.py::test_unit_grammar[m*s]",
"astropy/units/tests/test_format.py::test_unit_grammar[m.s]",
"astropy/units/tests/test_format.py::test_unit_grammar[m/s]",
"astropy/units/tests/test_format.py::test_unit_grammar[m*s**-1]... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Refactor unit formatter `to_string()` workings
Currently `Base.to_string()` converts units to strings if there are no fractions to worry about and calls `cls._format_fraction()` to handle inline and optionally multiline fractions if needed. The updated code splits the previous `_format_fraction()` methods to `_format_inline_fraction()` and `_format_multiline_fraction()` methods and has `to_string()` decide which to call (if needed) based on the `fraction` argument and the new `_fraction_formatters` class property. The keys of the dictionary that the property returns are also used for creating the error message if an invalid `fraction` value is specified. The updates to the tests demonstrate that the current error messages can be misleading.
Because I was rewriting `Base.to_string()` anyways I also inlined `units.format.utils.get_grouped_by_powers()`, so the fourth commit closes #16424 (either we speed up the code now or we conclude that it's fast enough already).
- [x] 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.
----------
Thank you for your contribution to Astropy! 🌌 This checklist is meant to remind the package maintainers who will review this pull request of some common things to look for.
- [ ] 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)?
- [ ] Are tests added/updated as required? If so, do they follow the [Astropy testing guidelines](https://docs.astropy.org/en/latest/development/testguide.html)?
- [ ] 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)?
- [ ] Is rebase and/or squash necessary? If so, please provide the author with appropriate instructions. Also see instructions for [rebase](https://docs.astropy.org/en/latest/development/workflow/development_workflow.html#rebase-if-necessary) and [squash](https://docs.astropy.org/en/latest/development/workflow/development_workflow.html#squash-if-necessary).
- [ ] 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).
- [ ] 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.
- [ ] 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?
- [ ] 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.
When I last rebased this pull request I also edited the tests that are meant to check the errors that are raised if an incorrect `fraction` value is passed to the `to_string()` methods. The updates make it clear that even the formatters that support `fraction="multiline"` nonetheless say that they only support `fraction="inline"` in the error message, and that the updated code corrects that mistake. But this mistake is not simple to fix if `Console` inherits its `to_string()` from `Base` only changing the default `fraction` value, which means that the code duplication between the proposed `Base.to_string()` and `Console.to_string()` is less problematic than it first might have appeared to have been.
I do have an idea now how to avoid code duplication in the `Base.to_string()` and `Console.to_string()` methods, and if it works we wouldn't need `Base.to_string_fraction_helper()` as a separate method because the code could reside in `Base.to_string()`. I've converted this pull request to a draft while I'm working on that idea.
My new approach to minimize code duplication is to introduce the `_fraction_formatters` class property, which maps accepted `to_string()` `fraction` argument values to the corresponding formatter functions. The only downside is that the current implementation is just slightly too dynamic for static type checkers, but we are not type checking yet.
</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/format/base.py]
(definition of Base._fraction_formatters:)
def _fraction_formatters(cls) -> dict[bool | str, Callable[[str, str, str], str]]:
(definition of Base._format_inline_fraction:)
def _format_inline_fraction( cls, scale: str, numerator: str, denominator: str ) -> str:
[end of new definitions in astropy/units/format/base.py]
[start of new definitions in astropy/units/format/console.py]
(definition of Console._fraction_formatters:)
def _fraction_formatters(cls) -> dict[bool | str, Callable[[str, str, str], str]]:
(definition of Console._format_multiline_fraction:)
def _format_multiline_fraction( cls, scale: str, numerator: str, denominator: str ) -> str:
[end of new definitions in astropy/units/format/console.py]
[start of new definitions in astropy/units/format/latex.py]
(definition of Latex._format_multiline_fraction:)
def _format_multiline_fraction( cls, scale: str, numerator: str, denominator: str ) -> str:
[end of new definitions in astropy/units/format/latex.py]
[start of new definitions in astropy/units/format/vounit.py]
(definition of VOUnit._format_inline_fraction:)
def _format_inline_fraction( cls, scale: str, numerator: str, denominator: str ) -> str:
[end of new definitions in astropy/units/format/vounit.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>
Possible speed-ups for `get_grouped_by_powers`
This function uses `.append`. It looks like with a simple helper function (defined externally to this function) we could use a list comprehension instead. I wonder if that would be faster — `append` versus function call overhead.
_Originally posted by @nstarman in https://github.com/astropy/astropy/pull/16392#discussion_r1591049850_
`itertools` has a recipe for this type of dual-list creation loop. Doing two loops at the C-level might be faster than 1 loop with constant appending.
----------
So I did some ``timeit`` tests with the following function definitions:
```python
import itertools
# The original function
def loop_func(bases, powers):
positive = []
negative = []
for base, power in zip(bases, powers):
if power < 0:
negative.append((base, -power))
elif power > 0:
positive.append((base, power))
return positive, negative
# List comprehension
def list_comp_func(bases, powers):
num_bases = len(bases)
negative = [(bases[ii], -powers[ii]) for ii in range(num_bases) if powers[ii] < 0]
positive = [(bases[ii], powers[ii]) for ii in range(num_bases) if powers[ii] > 0]
return positive, negative
# Using itertools.tee
def itertools_func(bases, powers):
l1, l2 = itertools.tee((x > 0, x) for x in powers)
positive, negative = ([(x, z) for x, (y, z) in zip(bases, l1) if y],
[(x, -z) for x, (y, z) in zip(bases, l2) if not y])
return positive, negative
```
I then ran the following:
```python
from timeit import timeit
from astropy.units import *
bases = [m, s, kg, A, cd, rad, K, mol] # All the base SI units
powers = [1, -2, 1, 3, -2, 1, 4, 3] # Randomly selected powers
x = timeit(stmt=lambda: loop_func(bases, powers))
y = timeit(stmt=lambda: list_comp_func(bases, powers))
z = timeit(stmt=lambda: itertools_func(bases, powers))
```
and got ``x, y, z => 1.045156035979744, 1.1819853900233284, 2.542474016023334``
I've tried converting to numpy arrays, but at some point it still uses a list comprehension or zip, so they end up taking longer than these functions here.
It may be that the append approach might actually be the fastest method if using just python, probably because it's still looping through the arrays once. Even just replacing the ``zip`` in ``loop_func`` with a ``range`` approach
```python
def loop_range_func(bases, powers):
positive = []
negative = []
num_bases = len(bases)
for ii in range(num_bases):
base = bases[ii]
power = powers[ii]
if power < 0:
negative.append((base, -power))
elif power > 0:
positive.append((base, power))
return positive, negative
```
only results in a speed increase to ``0.9854398609895725``, which is not significant.
If someone can come up with a way to do this using a single list comprehension, that might be faster, but I'm unsure how to do that.
Thanks for looking into this!
@nstarman Hi there, I'm a first time contributor for astropy and would like to look into this if its still available?
Hi @julian-8897! Thanks for your interest in Astropy. While this Issue is still open, I would caution against taking it as a first issue. @goldenphoenix713 did a great job demonstrating why it would probably require some dark magic to make this meaningfully faster. If you're interested in other contributions I'd be happy to suggest open Issues, or new ideas, depending on what in Astropy you're interested in / what your technical background is!
Hi @nstarman , thanks for the quick response. Ah i see, I'm open to any suggestions actually! To be honest I haven't used astropy myself yet, but I'm generally interested in helping out with new features or even quality of life improvements. I'm currently an Astrophysics PhD , mostly working on machine learning problems , and previously did my degree in physics/CS. I do have minimal experience in open source contributions , as i helped out a bit with scikit-learn and im currently working on some minor contributions in pyro!
We don't currently have many integrations with scikit-learn. Integrative contributions would be very appreciated!
On pure astropy fronts `astropy.cosmology` has a mostly-broken integration with `astropy.modeling`.
Fixing, testing, and writing tutorials for this feature would be awesome. We aim to make these tutorials citable (https://github.com/astropy/astropy-tutorials/issues/158).
A related idea is an `astropy.cosmology` <-> `pyro` I/O.
QoL improvements could be adding type annotations (e.g. #16562).
Great, thanks for the suggestion! I'll probably start with something simple like type annotations/DOCs so I can learn how eg. `astropy.cosmology` , `asttropy.modeling` are structured. Would be very useful to have a nice integration with `pyro` or even `numpyro` to use their jax backend.
--------------------
</issues> | 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 c... | [
"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/com... | 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 | |
joke2k__faker-2066 | 2,066 | joke2k/faker | null | 8cee450e10463c0360e50e2b56da4ecfea1dd513 | 2024-06-26T04:42:53Z | diff --git a/faker/providers/passport/ru_RU/__init__.py b/faker/providers/passport/ru_RU/__init__.py
new file mode 100644
index 0000000000..e29ecad8fc
--- /dev/null
+++ b/faker/providers/passport/ru_RU/__init__.py
@@ -0,0 +1,11 @@
+from typing import Tuple
+
+from faker.typing import SexLiteral
+
+from .. import Provider as PassportProvider
+
+
+class Provider(PassportProvider):
+ def passport_owner(self, gender: SexLiteral = "M") -> Tuple[str, str]:
+ given_name, surname = super().passport_owner(gender)
+ return surname, given_name
| diff --git a/tests/providers/test_person.py b/tests/providers/test_person.py
index a8b1b4d07e..16bf309ecf 100644
--- a/tests/providers/test_person.py
+++ b/tests/providers/test_person.py
@@ -332,7 +332,6 @@ def test_last_name(self):
class TestEnPk(unittest.TestCase):
-
def setUp(self):
"""Set up the Faker instance with the Pakistani locale."""
self.fake = Faker("en_PK")
@@ -1215,6 +1214,11 @@ def test_language_name(self):
language_name = self.fake.language_name()
assert language_name in RuProvider.language_names
+ def test_passport_owner(self):
+ surname, given_name = self.fake.passport_owner()
+ assert surname in RuProvider.last_names
+ assert given_name in RuProvider.first_names
+
class TestSvSE(unittest.TestCase):
def setUp(self):
| [
{
"components": [
{
"doc": "",
"lines": [
8,
11
],
"name": "Provider",
"signature": "class Provider(PassportProvider):",
"type": "class"
},
{
"doc": "",
"lines": [
9,
11
],
"... | [
"tests/providers/test_person.py::TestRuRU::test_passport_owner"
] | [
"tests/providers/test_person.py::TestAr::test_first_name",
"tests/providers/test_person.py::TestAr::test_last_name",
"tests/providers/test_person.py::TestAzAz::test_first_name",
"tests/providers/test_person.py::TestAzAz::test_last_name",
"tests/providers/test_person.py::TestCsCZ::test_name_female",
"tests... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Added passport provider for ru_RU language
### What does this change
Added new passport provider for ru_RU language
### What was wrong
It looks like based on an issue https://github.com/joke2k/faker/issues/2061 for passport_owners we need to return first surname and then given_name
### How this fixes it
I created a new provider class in the path: faker/providers/passport/ru_RU/__init__.py and overloaded the function passport_owner
----------
</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/passport/ru_RU/__init__.py]
(definition of Provider:)
class Provider(PassportProvider):
(definition of Provider.passport_owner:)
def passport_owner(self, gender: SexLiteral = "M") -> Tuple[str, str]:
[end of new definitions in faker/providers/passport/ru_RU/__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 | ||
pydicom__pydicom-2082 | 2,082 | pydicom/pydicom | 2.4 | 0f4ed1e86315c9cd84c21ce42b47fb2d5a9bfa77 | 2024-06-25T23:41:03Z | diff --git a/doc/reference/pixels.rst b/doc/reference/pixels.rst
index 27811dbf8d..7e6bf7d426 100644
--- a/doc/reference/pixels.rst
+++ b/doc/reference/pixels.rst
@@ -34,6 +34,7 @@ Utility functions
iter_pixels
pack_bits
pixel_array
+ set_pixel_data
unpack_bits
diff --git a/doc/reference/pixels.utils.rst b/doc/reference/pixels.utils.rst
index 31b2b40ee2..0d13f7fb04 100644
--- a/doc/reference/pixels.utils.rst
+++ b/doc/reference/pixels.utils.rst
@@ -24,4 +24,5 @@ Pixel data related utility functions.
pixel_array
pixel_dtype
reshape_pixel_array
+ set_pixel_data
unpack_bits
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index 0e284dffb4..a0f8a30a07 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -62,6 +62,8 @@ Changes
``pyjpegls`` or ``pylibjpeg`` with ``pylibjpeg-libjpeg`` can be used instead (:issue:`2008`).
* Using Pillow with JPEG 2000 encoded > 8-bit multi-sample data (such as RGB) now raises an
exception as Pillow cannot decode such data correctly (:issue:`2006`)
+* An exception will now be raised if an :class:`~numpy.ndarray` is used to set
+ *Pixel Data* (:issue:`50`)
Removals
@@ -211,6 +213,10 @@ Enhancements
create the concepts dictionaries in :mod:`pydicom.sr` (:issue:`1021`)
* Refactored the interface for the concepts in :mod:`pydicom.sr` to simplify the access types
(:issue:`1454`)
+* Added the :meth:`Dataset.set_pixel_data()<pydicom.dataset.Dataset.set_pixel_data>` method
+ and :func:`~pydicom.pixels.set_pixel_data` function for automatically setting a
+ dataset's *Pixel Data* and related Image Pixel module elements using an
+ :class:`~numpy.ndarray` (:issue:`50`)
Fixes
diff --git a/src/pydicom/dataelem.py b/src/pydicom/dataelem.py
index 994c0ffaab..f96899d393 100644
--- a/src/pydicom/dataelem.py
+++ b/src/pydicom/dataelem.py
@@ -512,6 +512,17 @@ def _convert_value(self, val: Any) -> Any:
Uses the element's VR in order to determine the conversion method and
resulting type.
"""
+ if (
+ self.tag == 0x7FE00010
+ and config.have_numpy
+ and isinstance(val, numpy.ndarray)
+ ):
+ raise TypeError(
+ "The value for (7FE0,0010) 'Pixel Data' should be set using 'bytes' "
+ "not 'numpy.ndarray'. See the Dataset.set_pixel_data() method for "
+ "an alternative that supports ndarrays."
+ )
+
if self.VR == VR_.SQ: # a sequence - leave it alone
from pydicom.sequence import Sequence
diff --git a/src/pydicom/dataset.py b/src/pydicom/dataset.py
index 5a06cfec36..55900a1e57 100644
--- a/src/pydicom/dataset.py
+++ b/src/pydicom/dataset.py
@@ -66,7 +66,11 @@
from pydicom.fileutil import path_from_pathlike, PathType
from pydicom.misc import warn_and_log
from pydicom.pixels import compress, convert_color_space, decompress, pixel_array
-from pydicom.pixels.utils import reshape_pixel_array, get_image_pixel_ids
+from pydicom.pixels.utils import (
+ reshape_pixel_array,
+ get_image_pixel_ids,
+ set_pixel_data,
+)
from pydicom.tag import Tag, BaseTag, tag_in_exception, TagType, TAG_PIXREP
from pydicom.uid import PYDICOM_IMPLEMENTATION_UID, UID
from pydicom.valuerep import VR as VR_, AMBIGUOUS_VR
@@ -1851,7 +1855,7 @@ def compress(
encoding_plugin: str = "",
encapsulate_ext: bool = False,
*,
- new_instance_uid: bool = True,
+ generate_instance_uid: bool = True,
jls_error: int | None = None,
j2k_cr: list[float] | None = None,
j2k_psnr: list[float] | None = None,
@@ -1895,7 +1899,7 @@ def compress(
* (7FE0,0001) *Extended Offset Table*
* (7FE0,0002) *Extended Offset Table Lengths*
- If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
+ If `generate_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
Instance UID* value will be generated.
**Supported Transfer Syntax UIDs**
@@ -1920,7 +1924,7 @@ def compress(
.. versionchanged:: 3.0
- Added the `jls_error`, `j2k_cr`, `j2k_psnr` and `new_instance_uid`
+ Added the `jls_error`, `j2k_cr`, `j2k_psnr` and `generate_instance_uid`
keyword parameters.
Examples
@@ -1955,7 +1959,7 @@ def compress(
If ``False`` (default) then an extended offset table
will be added if needed for large amounts of compressed *Pixel
Data*, otherwise just the basic offset table will be used.
- new_instance_uid : bool, optional
+ generate_instance_uid : bool, optional
If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
keep the original value.
@@ -1988,7 +1992,7 @@ def compress(
arr,
encoding_plugin=encoding_plugin,
encapsulate_ext=encapsulate_ext,
- new_instance_uid=new_instance_uid,
+ generate_instance_uid=generate_instance_uid,
jls_error=jls_error,
j2k_cr=j2k_cr,
j2k_psnr=j2k_psnr,
@@ -2000,7 +2004,7 @@ def decompress(
handler_name: str = "",
*,
as_rgb: bool = True,
- new_instance_uid: bool = True,
+ generate_instance_uid: bool = True,
decoding_plugin: str = "",
**kwargs: Any,
) -> None:
@@ -2026,12 +2030,12 @@ def decompress(
*Pixel Data* element will be set to ``False``.
* Any :dcm:`image pixel<part03/sect_C.7.6.3.html>` module elements may be
modified as required to match the uncompressed *Pixel Data*.
- * If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
+ * If `generate_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
Instance UID* value will be generated.
.. versionchanged:: 3.0
- Added the `as_rgb` and `new_instance_uid` keyword parameters.
+ Added the `as_rgb` and `generate_instance_uid` keyword parameters.
.. deprecated:: 3.0
@@ -2046,7 +2050,7 @@ def decompress(
:mod:`~pydicom.pixels` **backend only.** If ``True`` (default) then
convert pixel data with a YCbCr :ref:`photometric interpretation
<photometric_interpretation>` such as ``"YBR_FULL_422"`` to RGB.
- new_instance_uid : bool, optional
+ generate_instance_uid : bool, optional
If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
keep the original value.
@@ -2085,7 +2089,7 @@ def decompress(
decompress(
self,
as_rgb=as_rgb,
- new_instance_uid=new_instance_uid,
+ generate_instance_uid=generate_instance_uid,
**opts,
)
@@ -2786,6 +2790,77 @@ def __setitem__(self, key: "slice | TagType", elem: _DatasetValue) -> None:
# dataset
self._set_pixel_representation(cast(DataElement, elem))
+ def set_pixel_data(
+ self,
+ arr: "numpy.ndarray",
+ photometric_interpretation: str,
+ bits_stored: int,
+ *,
+ generate_instance_uid: bool = True,
+ ) -> None:
+ """Use an :class:`~numpy.ndarray` to set the *Pixel Data* and related
+ Image Pixel module elements.
+
+ .. versionadded:: 3.0
+
+ The following :dcm:`Image Pixel<part03/sect_C.7.6.3.3.html#table_C.7-11c>`
+ module elements values will be added, updated or removed as necessary:
+
+ * (0028,0002) *Samples per Pixel* using a value corresponding to
+ `photometric_interpretation`.
+ * (0028,0104) *Photometric Interpretation* from `photometric_interpretation`.
+ * (0028,0006) *Planar Configuration* will be added and set to ``0`` if
+ *Samples per Pixel* is > 1, otherwise it will be removed.
+ * (0028,0008) *Number of Frames* from the array :attr:`~numpy.ndarray.shape`,
+ however it will be removed if `arr` only contains a single frame.
+ * (0028,0010) *Rows* and (0028,0011) *Columns* from the array
+ :attr:`~numpy.ndarray.shape`.
+ * (0028,0100) *Bits Allocated* from the array :class:`~numpy.dtype`.
+ * (0028,0101) *Bits Stored* and (0028,0102) *High Bit* from `bits_stored`.
+ * (0028,0103) *Pixel Representation* from the array :class:`~numpy.dtype`.
+
+ In addition:
+
+ * The *Transfer Syntax UID* will be set to *Explicit VR Little Endian* if
+ it doesn't already exist or uses a compressed (encapsulated) transfer syntax.
+ * If `generate_instance_uid` is ``True`` (default) then the *SOP Instance UID*
+ will be added or updated.
+
+ Parameters
+ ----------
+ arr : numpy.ndarray
+ An array with :class:`~numpy.dtype` uint8, uint16, int8 or int16. The
+ array must be shaped as one of the following:
+
+ * (rows, columns) for a single frame of grayscale data.
+ * (frames, rows, columns) for multi-frame grayscale data.
+ * (rows, columns, samples) for a single frame of multi-sample data
+ such as RGB.
+ * (frames, rows, columns, samples) for multi-frame, multi-sample data.
+ photometric_interpretation : str
+ The value to use for (0028,0004) *Photometric Interpretation*. Valid
+ values are ``"MONOCHROME1"``, ``"MONOCHROME2"``, ``"PALETTE COLOR"``,
+ ``"RGB"``, ``"YBR_FULL"``, ``"YBR_FULL_422"``.
+ bits_stored : int
+ The value to use for (0028,0101) *Bits Stored*. Must be no greater than
+ the number of bits used by the :attr:`~numpy.dtype.itemsize` of `arr`.
+ generate_instance_uid : bool, optional
+ If ``True`` (default) then add or update the (0008,0018) *SOP Instance
+ UID* element with a value generated using :func:`~pydicom.uid.generate_uid`.
+
+ Raises
+ ------
+ NotImplementedError
+ If the dataset has a big-endian *Transfer Syntax UID*.
+ """
+ set_pixel_data(
+ self,
+ arr,
+ photometric_interpretation,
+ bits_stored,
+ generate_instance_uid=generate_instance_uid,
+ )
+
def _set_pixel_representation(self, elem: DataElement) -> None:
"""Set the `_pixel_rep` attribute for the current dataset and child
datasets of the sequence element `elem`."""
diff --git a/src/pydicom/pixels/__init__.py b/src/pydicom/pixels/__init__.py
index 475cc5d17b..9be0156ac4 100644
--- a/src/pydicom/pixels/__init__.py
+++ b/src/pydicom/pixels/__init__.py
@@ -18,5 +18,6 @@
iter_pixels,
pack_bits,
pixel_array,
+ set_pixel_data,
unpack_bits,
)
diff --git a/src/pydicom/pixels/utils.py b/src/pydicom/pixels/utils.py
index 59a5fc0edd..52b88ae4a5 100644
--- a/src/pydicom/pixels/utils.py
+++ b/src/pydicom/pixels/utils.py
@@ -246,7 +246,7 @@ def compress(
*,
encoding_plugin: str = "",
encapsulate_ext: bool = False,
- new_instance_uid: bool = True,
+ generate_instance_uid: bool = True,
jls_error: int | None = None,
j2k_cr: list[float] | None = None,
j2k_psnr: list[float] | None = None,
@@ -290,7 +290,7 @@ def compress(
* (7FE0,0001) *Extended Offset Table*
* (7FE0,0002) *Extended Offset Table Lengths*
- If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
+ If `generate_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
Instance UID* value will be generated.
**Supported Transfer Syntax UIDs**
@@ -348,7 +348,7 @@ def compress(
If ``False`` (default) then an extended offset table
will be added if needed for large amounts of compressed *Pixel
Data*, otherwise just the basic offset table will be used.
- new_instance_uid : bool, optional
+ generate_instance_uid : bool, optional
If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
keep the original value.
@@ -458,7 +458,7 @@ def compress(
ds.file_meta.TransferSyntaxUID = uid
- if new_instance_uid:
+ if generate_instance_uid:
instance_uid = generate_uid()
ds.SOPInstanceUID = instance_uid
ds.file_meta.MediaStorageSOPInstanceUID = instance_uid
@@ -470,7 +470,7 @@ def decompress(
ds: "Dataset",
*,
as_rgb: bool = True,
- new_instance_uid: bool = True,
+ generate_instance_uid: bool = True,
decoding_plugin: str = "",
**kwargs: Any,
) -> "Dataset":
@@ -498,7 +498,7 @@ def decompress(
*Pixel Data* element will be set to ``False``.
* Any :dcm:`image pixel<part03/sect_C.7.6.3.html>` module elements may be
modified as required to match the uncompressed *Pixel Data*.
- * If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
+ * If `generate_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
Instance UID* value will be generated.
Parameters
@@ -512,7 +512,7 @@ def decompress(
if ``True`` (default) then convert pixel data with a YCbCr
:ref:`photometric interpretation<photometric_interpretation>` such as
``"YBR_FULL_422"`` to RGB.
- new_instance_uid : bool, optional
+ generate_instance_uid : bool, optional
If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
keep the original value.
@@ -600,7 +600,7 @@ def decompress(
# Update the transfer syntax
ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
- if new_instance_uid:
+ if generate_instance_uid:
instance_uid = generate_uid()
ds.SOPInstanceUID = instance_uid
ds.file_meta.MediaStorageSOPInstanceUID = instance_uid
@@ -1738,6 +1738,210 @@ def reshape_pixel_array(ds: "Dataset", arr: "np.ndarray") -> "np.ndarray":
return arr
+def set_pixel_data(
+ ds: "Dataset",
+ arr: "np.ndarray",
+ photometric_interpretation: str,
+ bits_stored: int,
+ *,
+ generate_instance_uid: bool = True,
+) -> None:
+ """Use an :class:`~numpy.ndarray` to set a dataset's *Pixel Data* and related
+ Image Pixel module elements.
+
+ .. versionadded:: 3.0
+
+ The following :dcm:`Image Pixel<part03/sect_C.7.6.3.3.html#table_C.7-11c>`
+ module elements values will be added, updated or removed as necessary:
+
+ * (0028,0002) *Samples per Pixel* using a value corresponding to
+ `photometric_interpretation`.
+ * (0028,0004) *Photometric Interpretation* from `photometric_interpretation`.
+ * (0028,0006) *Planar Configuration* will be added and set to ``0`` if
+ *Samples per Pixel* is > 1, otherwise it will be removed.
+ * (0028,0008) *Number of Frames* from the array :attr:`~numpy.ndarray.shape`,
+ however it will be removed if `arr` only contains a single frame.
+ * (0028,0010) *Rows* and (0028,0011) *Columns* from the array
+ :attr:`~numpy.ndarray.shape`.
+ * (0028,0100) *Bits Allocated* from the array :class:`~numpy.dtype`.
+ * (0028,0101) *Bits Stored* and (0028,0102) *High Bit* from `bits_stored`.
+ * (0028,0103) *Pixel Representation* from the array :class:`~numpy.dtype`.
+
+ In addition:
+
+ * The *Transfer Syntax UID* will be set to *Explicit VR Little
+ Endian* if it doesn't already exist or uses a compressed (encapsulated)
+ transfer syntax.
+ * If `generate_instance_uid` is ``True`` (default) then the *SOP Instance UID*
+ will be added or updated.
+
+ Parameters
+ ----------
+ ds : pydicom.dataset.Dataset
+ The little endian encoded dataset to be modified.
+ arr : np.ndarray
+ An array with :class:`~numpy.dtype` uint8, uint16, int8 or int16. The
+ array must be shaped as one of the following:
+
+ * (rows, columns) for a single frame of grayscale data.
+ * (frames, rows, columns) for multi-frame grayscale data.
+ * (rows, columns, samples) for a single frame of multi-sample data
+ such as RGB.
+ * (frames, rows, columns, samples) for multi-frame, multi-sample data.
+ photometric_interpretation : str
+ The value to use for (0028,0004) *Photometric Interpretation*. Valid values
+ are ``"MONOCHROME1"``, ``"MONOCHROME2"``, ``"PALETTE COLOR"``, ``"RGB"``,
+ ``"YBR_FULL"``, ``"YBR_FULL_422"``.
+ bits_stored : int
+ The value to use for (0028,0101) *Bits Stored*. Must be no greater than
+ the number of bits used by the :attr:`~numpy.dtype.itemsize` of `arr`.
+ generate_instance_uid : bool, optional
+ If ``True`` (default) then add or update the (0008,0018) *SOP Instance
+ UID* element with a value generated using :func:`~pydicom.uid.generate_uid`.
+ """
+ from pydicom.dataset import FileMetaDataset
+ from pydicom.pixels.common import PhotometricInterpretation as PI
+
+ if (elem := ds.get(0x7FE00008, None)) or (elem := ds.get(0x7FE00009, None)):
+ raise AttributeError(
+ f"The dataset has an existing {elem.tag} '{elem.name}' element which "
+ "indicates the (0008,0016) 'SOP Class UID' value is not suitable for a "
+ f"dataset with 'Pixel Data'. The '{elem.name}' element should be deleted "
+ "and the 'SOP Class UID' changed."
+ )
+
+ if not hasattr(ds, "file_meta"):
+ ds.file_meta = FileMetaDataset()
+
+ tsyntax = ds.file_meta.get("TransferSyntaxUID", None)
+ if tsyntax and not tsyntax.is_little_endian:
+ raise NotImplementedError(
+ f"The dataset's transfer syntax '{tsyntax.name}' is big-endian, "
+ "which is not supported"
+ )
+
+ # Make no changes to the dataset until after validation checks have passed!
+ changes: dict[str, tuple[str, Any]] = {}
+
+ shape, ndim, dtype = arr.shape, arr.ndim, arr.dtype
+ if dtype.kind not in ("u", "i") or dtype.itemsize not in (1, 2):
+ raise ValueError(
+ f"Unsupported ndarray dtype '{dtype}', must be int8, int16, uint8 or "
+ "uint16"
+ )
+
+ # Use `photometric_interpretation` to determine *Samples Per Pixel*
+ # Don't support retired (such as CMYK) or inappropriate values (such as YBR_RCT)
+ interpretations: dict[str, int] = {
+ PI.MONOCHROME1: 1,
+ PI.MONOCHROME2: 1,
+ PI.PALETTE_COLOR: 1,
+ PI.RGB: 3,
+ PI.YBR_FULL: 3,
+ PI.YBR_FULL_422: 3,
+ }
+ try:
+ nr_samples = interpretations[photometric_interpretation]
+ except KeyError:
+ raise ValueError(
+ "Unsupported 'photometric_interpretation' value "
+ f"'{photometric_interpretation}'"
+ )
+
+ if nr_samples == 1:
+ if ndim not in (2, 3):
+ raise ValueError(
+ f"An ndarray with '{photometric_interpretation}' data must have 2 or 3 "
+ f"dimensions, not {ndim}"
+ )
+
+ # ndim = 3 is (frames, rows, columns), else (rows, columns)
+ changes["NumberOfFrames"] = ("+", shape[0]) if ndim == 3 else ("-", None)
+ changes["Rows"] = ("+", shape[1] if ndim == 3 else shape[0])
+ changes["Columns"] = ("+", shape[2] if ndim == 3 else shape[1])
+ else:
+ if ndim not in (3, 4):
+ raise ValueError(
+ f"An ndarray with '{photometric_interpretation}' data must have 3 or 4 "
+ f"dimensions, not {ndim}"
+ )
+
+ if shape[-1] != nr_samples:
+ raise ValueError(
+ f"An ndarray with '{photometric_interpretation}' data must have shape "
+ f"(rows, columns, 3) or (frames, rows, columns, 3), not {shape}"
+ )
+
+ # ndim = 3 is (rows, columns, samples), else (frames, rows, columns, samples)
+ changes["NumberOfFrames"] = ("-", None) if ndim == 3 else ("+", shape[0])
+ changes["Rows"] = ("+", shape[0] if ndim == 3 else shape[1])
+ changes["Columns"] = ("+", shape[1] if ndim == 3 else shape[2])
+
+ if not 0 < bits_stored <= dtype.itemsize * 8:
+ raise ValueError(
+ f"Invalid 'bits_stored' value '{bits_stored}', must be greater than 0 and "
+ "less than or equal to the number of bits for the ndarray's itemsize "
+ f"'{arr.dtype.itemsize * 8}'"
+ )
+
+ # Check values in `arr` are in the range allowed by `bits_stored`
+ actual_min, actual_max = arr.min(), arr.max()
+ allowed_min = 0 if dtype.kind == "u" else -(2 ** (bits_stored - 1))
+ allowed_max = (
+ 2**bits_stored - 1 if dtype.kind == "u" else 2 ** (bits_stored - 1) - 1
+ )
+ if actual_min < allowed_min or actual_max > allowed_max:
+ raise ValueError(
+ f"The range of values in the ndarray [{actual_min}, {actual_max}] is "
+ f"greater than that allowed by the 'bits_stored' value [{allowed_min}, "
+ f"{allowed_max}]"
+ )
+
+ changes["SamplesPerPixel"] = ("+", nr_samples)
+ changes["PlanarConfiguration"] = ("+", 0) if nr_samples > 1 else ("-", None)
+ changes["PhotometricInterpretation"] = ("+", photometric_interpretation)
+ changes["BitsAllocated"] = ("+", dtype.itemsize * 8)
+ changes["BitsStored"] = ("+", bits_stored)
+ changes["HighBit"] = ("+", bits_stored - 1)
+ changes["PixelRepresentation"] = ("+", 0 if dtype.kind == "u" else 1)
+
+ # Update the Image Pixel module elements
+ for keyword, (operation, value) in changes.items():
+ if operation == "+":
+ setattr(ds, keyword, value)
+ elif operation == "-" and keyword in ds:
+ del ds[keyword]
+
+ # Part 3, C.7.6.3.1.2: YBR_FULL_422 data needs to be downsampled
+ if photometric_interpretation == PI.YBR_FULL_422:
+ # Y1 B1 R1 Y2 B1 R1 -> Y1 Y2 B1 R1
+ arr = arr.ravel()
+ out = np.empty(arr.size // 3 * 2, dtype=dtype)
+ out[::4] = arr[::6] # Y1
+ out[1::4] = arr[3::6] # Y2
+ out[2::4] = arr[1::6] # B
+ out[3::4] = arr[2::6] # R
+ arr = out
+
+ # Update the Pixel Data
+ data = arr.tobytes()
+ ds.PixelData = data if len(data) % 2 == 0 else b"".join((data, b"\x00"))
+ elem = ds["PixelData"]
+ elem.VR = VR.OB if ds.BitsAllocated <= 8 else VR.OW
+ elem.is_undefined_length = False
+
+ ds._pixel_array = None
+ ds._pixel_id = {}
+
+ if not tsyntax or tsyntax.is_compressed:
+ ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
+
+ if generate_instance_uid:
+ instance_uid = generate_uid()
+ ds.SOPInstanceUID = instance_uid
+ ds.file_meta.MediaStorageSOPInstanceUID = instance_uid
+
+
def unpack_bits(src: bytes, as_array: bool = True) -> "np.ndarray | bytes":
"""Unpack the bit-packed data in `src`.
| diff --git a/tests/pixels/test_utils.py b/tests/pixels/test_utils.py
index c1faf6298c..9841ebbb7c 100644
--- a/tests/pixels/test_utils.py
+++ b/tests/pixels/test_utils.py
@@ -34,6 +34,7 @@
get_j2k_parameters,
get_nr_frames,
pack_bits,
+ set_pixel_data,
unpack_bits,
expand_ybr422,
compress,
@@ -43,6 +44,7 @@
EnhancedMRImageStorage,
ExplicitVRLittleEndian,
ExplicitVRBigEndian,
+ ImplicitVRLittleEndian,
UncompressedTransferSyntaxes,
RLELossless,
JPEG2000Lossless,
@@ -1566,12 +1568,14 @@ def test_instance_uid(self):
ds = dcmread(EXPL_16_16_1F.path)
original = ds.SOPInstanceUID
- compress(ds, RLELossless, encoding_plugin="pydicom", new_instance_uid=True)
+ compress(ds, RLELossless, encoding_plugin="pydicom", generate_instance_uid=True)
assert ds.SOPInstanceUID != original
assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
ds = dcmread(EXPL_16_16_1F.path)
- compress(ds, RLELossless, encoding_plugin="pydicom", new_instance_uid=False)
+ compress(
+ ds, RLELossless, encoding_plugin="pydicom", generate_instance_uid=False
+ )
assert ds.SOPInstanceUID == original
assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
@@ -1882,11 +1886,436 @@ def test_instance_uid(self):
ds = dcmread(RLE_8_3_1F.path)
original = ds.SOPInstanceUID
- decompress(ds, decoding_plugin="pydicom", new_instance_uid=True)
+ decompress(ds, decoding_plugin="pydicom", generate_instance_uid=True)
assert ds.SOPInstanceUID != original
assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
ds = dcmread(RLE_8_3_1F.path)
- decompress(ds, decoding_plugin="pydicom", new_instance_uid=False)
+ decompress(ds, decoding_plugin="pydicom", generate_instance_uid=False)
assert ds.SOPInstanceUID == original
assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
+
+
+@pytest.mark.skipif(not HAVE_NP, reason="Numpy is not available")
+class TestSetPixelData:
+ """Tests for set_pixel_data()"""
+
+ def test_float_pixel_data_raises(self):
+ """Test exception raised if float pixel data elements present"""
+ ds = Dataset()
+ ds.FloatPixelData = b"\x00\x00"
+ arr = np.zeros((10, 10), dtype="uint8")
+
+ msg = (
+ r"The dataset has an existing \(7FE0,0008\) 'Float Pixel Data' element "
+ r"which indicates the \(0008,0016\) 'SOP Class UID' value is not suitable "
+ "for a dataset with 'Pixel Data'. The 'Float Pixel Data' element should "
+ "be deleted and the 'SOP Class UID' changed."
+ )
+ with pytest.raises(AttributeError, match=msg):
+ set_pixel_data(ds, arr, "MONOCHROME1", 8)
+
+ del ds.FloatPixelData
+ ds.DoubleFloatPixelData = b"\x00\x00"
+
+ msg = r"The dataset has an existing \(7FE0,0009\) 'Double Float Pixel Data'"
+ with pytest.raises(AttributeError, match=msg):
+ set_pixel_data(ds, arr, "MONOCHROME1", 8)
+
+ def test_unsupported_dtype_raises(self):
+ """Test exception raised if dtype is unsupported"""
+
+ msg = (
+ r"Unsupported ndarray dtype 'uint32', must be int8, int16, uint8 or uint16"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(
+ Dataset(), np.zeros((10, 10), dtype="uint32"), "MONOCHROME1", 8
+ )
+
+ msg = (
+ r"Unsupported ndarray dtype 'float32', must be int8, int16, uint8 or uint16"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(
+ Dataset(), np.zeros((10, 10), dtype="float32"), "MONOCHROME1", 8
+ )
+
+ def test_unsupported_photometric_interpretation_raises(self):
+ """Test exception raised if dtype is unsupported"""
+
+ msg = "Unsupported 'photometric_interpretation' value 'YBR_RCT'"
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), np.zeros((10, 10), dtype="int8"), "YBR_RCT", 8)
+
+ def test_unsupported_dimension_raises(self):
+ """Test exception raised if array dimensions are unsupported"""
+
+ msg = "An ndarray with 'MONOCHROME1' data must have 2 or 3 dimensions, not 4"
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(
+ Dataset(), np.zeros((2, 10, 10, 3), dtype="int8"), "MONOCHROME1", 8
+ )
+
+ msg = "An ndarray with 'RGB' data must have 3 or 4 dimensions, not 2"
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), np.zeros((10, 10), dtype="int8"), "RGB", 8)
+
+ def test_invalid_samples_raises(self):
+ """Test mismatch between array shape and photometric interpretation raises"""
+ msg = (
+ r"An ndarray with 'RGB' data must have shape \(rows, columns, 3\) or "
+ r"\(frames, rows, columns, 3\), not \(10, 10, 10\)"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), np.zeros((10, 10, 10), dtype="int8"), "RGB", 8)
+
+ def test_invalid_bits_stored_raises(self):
+ """Test bits_stored outside [1, 16] raises an exception"""
+ msg = (
+ "Invalid 'bits_stored' value '0', must be greater than 0 and "
+ "less than or equal to the number of bits for the ndarray's itemsize "
+ "'8'"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), np.ones((3, 3), dtype="u1"), "MONOCHROME1", 0)
+
+ msg = (
+ "Invalid 'bits_stored' value '9', must be greater than 0 and "
+ "less than or equal to the number of bits for the ndarray's itemsize "
+ "'8'"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), np.ones((3, 3), dtype="u1"), "MONOCHROME1", 9)
+
+ msg = (
+ "Invalid 'bits_stored' value '0', must be greater than 0 and "
+ "less than or equal to the number of bits for the ndarray's itemsize "
+ "'16'"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), np.ones((3, 3), dtype="u2"), "MONOCHROME1", 0)
+
+ msg = (
+ "Invalid 'bits_stored' value '17', must be greater than 0 and "
+ "less than or equal to the number of bits for the ndarray's itemsize "
+ "'16'"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), np.ones((3, 3), dtype="u2"), "MONOCHROME1", 17)
+
+ def test_invalid_arr_range_raises(self):
+ """Test the range of values in the array matches bits_stored"""
+ arr = np.zeros((10, 10), dtype="uint8")
+ # The array will overflow 256 -> 0 if bits_stored 8
+ for bits_stored in range(1, 8):
+ amin, amax = 0, 2**bits_stored - 1
+ arr[0, 0] = amax + 1
+
+ msg = (
+ rf"The range of values in the ndarray \[0, {amax + 1}\] is "
+ r"greater than that allowed by the 'bits_stored' value \[0, "
+ rf"{amax}\]"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), arr, "MONOCHROME1", bits_stored)
+
+ arr = np.zeros((10, 10), dtype="uint16")
+ for bits_stored in range(1, 16):
+ amin, amax = 0, 2**bits_stored - 1
+ arr[0, 0] = amax + 1
+
+ msg = (
+ rf"The range of values in the ndarray \[0, {amax + 1}\] is "
+ r"greater than that allowed by the 'bits_stored' value \[0, "
+ rf"{amax}\]"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), arr, "MONOCHROME1", bits_stored)
+
+ arr = np.zeros((10, 10), dtype="int8")
+ for bits_stored in range(1, 8):
+ amin, amax = -(2 ** (bits_stored - 1)), 2 ** (bits_stored - 1) - 1
+ arr[0, 0] = amax + 1
+ arr[0, 1] = amin - 1
+
+ msg = (
+ rf"The range of values in the ndarray \[{amin - 1}, {amax + 1}\] is "
+ rf"greater than that allowed by the 'bits_stored' value \[{amin}, "
+ rf"{amax}\]"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), arr, "MONOCHROME1", bits_stored)
+
+ arr = np.zeros((10, 10), dtype="int16")
+ for bits_stored in range(1, 16):
+ amin, amax = -(2 ** (bits_stored - 1)), 2 ** (bits_stored - 1) - 1
+ arr[0, 0] = amax + 1
+ arr[0, 1] = amin - 1
+
+ msg = (
+ rf"The range of values in the ndarray \[{amin - 1}, {amax + 1}\] is "
+ rf"greater than that allowed by the 'bits_stored' value \[{amin}, "
+ rf"{amax}\]"
+ )
+ with pytest.raises(ValueError, match=msg):
+ set_pixel_data(Dataset(), arr, "MONOCHROME1", bits_stored)
+
+ def test_big_endian_raises(self):
+ """Test exception raised if big endian transfer syntax"""
+ ds = Dataset()
+ ds.file_meta = FileMetaDataset()
+ ds.file_meta.TransferSyntaxUID = ExplicitVRBigEndian
+ arr = np.zeros((10, 10), dtype="uint8")
+
+ msg = (
+ "The dataset's transfer syntax 'Explicit VR Big Endian' is big-endian, "
+ "which is not supported"
+ )
+ with pytest.raises(NotImplementedError, match=msg):
+ set_pixel_data(ds, arr, "MONOCHROME1", 8)
+
+ def test_grayscale_8bit_unsigned(self):
+ """Test setting unsigned 8-bit grayscale pixel data"""
+ ds = Dataset()
+ ds.PlanarConfiguration = 1
+ ds.NumberOfFrames = 2
+
+ arr = np.zeros((3, 5), dtype="u1")
+ arr[0, 0] = 127
+ set_pixel_data(ds, arr, "MONOCHROME1", 7)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == 3
+ assert ds.Columns == 5
+ assert ds.SamplesPerPixel == 1
+ assert ds.PhotometricInterpretation == "MONOCHROME1"
+ assert ds.PixelRepresentation == 0
+ assert ds.BitsAllocated == 8
+ assert ds.BitsStored == 7
+ assert ds.HighBit == 6
+ assert "NumberOfFrames" not in ds
+ assert "PlanarConfiguration" not in ds
+
+ elem = ds["PixelData"]
+ assert elem.VR == "OB"
+ assert len(elem.value) == 16
+ assert elem.is_undefined_length is False
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ assert np.array_equal(ds.pixel_array, arr)
+
+ def test_grayscale_8bit_signed(self):
+ """Test setting signed 8-bit grayscale pixel data"""
+ ds = Dataset()
+ ds.PlanarConfiguration = 1
+ ds.NumberOfFrames = 2
+
+ arr = np.zeros((3, 5), dtype="i1")
+ arr[0, 0] = 127
+ arr[0, 1] = -128
+ set_pixel_data(ds, arr, "MONOCHROME1", 8)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == 3
+ assert ds.Columns == 5
+ assert ds.SamplesPerPixel == 1
+ assert ds.PhotometricInterpretation == "MONOCHROME1"
+ assert ds.PixelRepresentation == 1
+ assert ds.BitsAllocated == 8
+ assert ds.BitsStored == 8
+ assert ds.HighBit == 7
+
+ elem = ds["PixelData"]
+ assert elem.VR == "OB"
+ assert len(elem.value) == 16
+
+ assert np.array_equal(ds.pixel_array, arr)
+
+ def test_grayscale_16bit_unsigned(self):
+ """Test setting unsigned 16-bit grayscale pixel data"""
+ ds = Dataset()
+ ds.PlanarConfiguration = 1
+ ds.NumberOfFrames = 2
+
+ arr = np.zeros((3, 5), dtype="u2")
+ arr[0, 0] = 65535
+ set_pixel_data(ds, arr, "MONOCHROME1", 16)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == 3
+ assert ds.Columns == 5
+ assert ds.SamplesPerPixel == 1
+ assert ds.PhotometricInterpretation == "MONOCHROME1"
+ assert ds.PixelRepresentation == 0
+ assert ds.BitsAllocated == 16
+ assert ds.BitsStored == 16
+ assert ds.HighBit == 15
+
+ elem = ds["PixelData"]
+ assert elem.VR == "OW"
+ assert len(elem.value) == 30
+
+ assert np.array_equal(ds.pixel_array, arr)
+
+ def test_grayscale_16bit_signed(self):
+ """Test setting signed 16-bit grayscale pixel data"""
+ ds = Dataset()
+ ds.PlanarConfiguration = 1
+ ds.NumberOfFrames = 2
+
+ arr = np.zeros((3, 5), dtype="i2")
+ arr[0, 0] = 32767
+ arr[0, 1] = -32768
+ set_pixel_data(ds, arr, "MONOCHROME1", 16)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == 3
+ assert ds.Columns == 5
+ assert ds.SamplesPerPixel == 1
+ assert ds.PhotometricInterpretation == "MONOCHROME1"
+ assert ds.PixelRepresentation == 1
+ assert ds.BitsAllocated == 16
+ assert ds.BitsStored == 16
+ assert ds.HighBit == 15
+
+ elem = ds["PixelData"]
+ assert elem.VR == "OW"
+ assert len(elem.value) == 30
+
+ assert np.array_equal(ds.pixel_array, arr)
+
+ def test_grayscale_multiframe(self):
+ """Test setting multiframe pixel data"""
+ ds = Dataset()
+
+ arr = np.zeros((10, 3, 5), dtype="u1")
+ arr[0, 0, 0] = 127
+ arr[9, 0, 0] = 255
+ set_pixel_data(ds, arr, "MONOCHROME1", 8)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == 3
+ assert ds.Columns == 5
+ assert ds.SamplesPerPixel == 1
+ assert ds.PhotometricInterpretation == "MONOCHROME1"
+ assert ds.PixelRepresentation == 0
+ assert ds.BitsAllocated == 8
+ assert ds.BitsStored == 8
+ assert ds.HighBit == 7
+ assert ds.NumberOfFrames == 10
+ assert "PlanarConfiguration" not in ds
+
+ elem = ds["PixelData"]
+ assert elem.VR == "OB"
+ assert len(elem.value) == 150
+ assert elem.is_undefined_length is False
+
+ assert np.array_equal(ds.pixel_array, arr)
+
+ def test_rgb_8bit_unsigned(self):
+ """Test setting unsigned 8-bit RGB pixel data"""
+ ds = Dataset()
+ ds.NumberOfFrames = 2
+
+ arr = np.zeros((3, 5, 3), dtype="u1")
+ arr[0, 0] = [127, 255, 0]
+ set_pixel_data(ds, arr, "RGB", 8)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == 3
+ assert ds.Columns == 5
+ assert ds.SamplesPerPixel == 3
+ assert ds.PhotometricInterpretation == "RGB"
+ assert ds.PixelRepresentation == 0
+ assert ds.BitsAllocated == 8
+ assert ds.BitsStored == 8
+ assert ds.HighBit == 7
+ assert ds.PlanarConfiguration == 0
+ assert "NumberOfFrames" not in ds
+
+ elem = ds["PixelData"]
+ assert elem.VR == "OB"
+ assert len(elem.value) == 46
+
+ assert np.array_equal(ds.pixel_array, arr)
+
+ def test_rgb_YBR_FULL_422(self):
+ """Test setting multiframe pixel data"""
+ ref = dcmread(EXPL_8_3_1F_YBR422.path)
+ arr = pixel_array(ref, raw=True)
+
+ ds = Dataset()
+ set_pixel_data(ds, arr, "YBR_FULL_422", 8)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == ref.Rows
+ assert ds.Columns == ref.Columns
+ assert ds.SamplesPerPixel == ref.SamplesPerPixel
+ assert ds.PhotometricInterpretation == "YBR_FULL_422"
+ assert ds.PixelRepresentation == ref.PixelRepresentation
+ assert ds.BitsAllocated == ref.BitsAllocated
+ assert ds.BitsStored == ref.BitsStored
+ assert ds.HighBit == ref.HighBit
+ assert ds.PlanarConfiguration == ref.PlanarConfiguration
+
+ elem = ds["PixelData"]
+ assert elem.VR == "OB"
+ assert len(elem.value) == (
+ ds.Rows * ds.Columns * ds.BitsAllocated // 8 * ds.SamplesPerPixel // 3 * 2
+ )
+ assert elem.is_undefined_length is False
+
+ assert np.array_equal(pixel_array(ds, raw=True), arr)
+
+ def test_transfer_syntax(self):
+ """Test setting the transfer syntax"""
+ ds = Dataset()
+
+ set_pixel_data(ds, np.zeros((3, 5, 3), dtype="u1"), "RGB", 8)
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+
+ del ds.file_meta.TransferSyntaxUID
+
+ ds.file_meta.TransferSyntaxUID = ImplicitVRLittleEndian
+ set_pixel_data(ds, np.zeros((3, 5, 3), dtype="u1"), "RGB", 8)
+ assert ds.file_meta.TransferSyntaxUID == ImplicitVRLittleEndian
+
+ ds.file_meta.TransferSyntaxUID = JPEG2000Lossless
+ set_pixel_data(ds, np.zeros((3, 5, 3), dtype="u1"), "RGB", 8)
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+
+ def test_dataset_set_pixel_data(self):
+ """Functionality test for Dataset.set_pixel_data()"""
+ ref = dcmread(EXPL_8_3_1F_YBR422.path)
+ arr = ref.pixel_array
+
+ ds = Dataset()
+ ds.set_pixel_data(arr, "RGB", 8)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert ds.Rows == ref.Rows
+ assert ds.Columns == ref.Columns
+ assert ds.SamplesPerPixel == ref.SamplesPerPixel
+ assert ds.PhotometricInterpretation == "RGB"
+ assert ds.PixelRepresentation == ref.PixelRepresentation
+ assert ds.BitsAllocated == ref.BitsAllocated
+ assert ds.BitsStored == ref.BitsStored
+ assert ds.HighBit == ref.HighBit
+ assert ds.PlanarConfiguration == ref.PlanarConfiguration
+
+ assert np.array_equal(ds.pixel_array, arr)
+
+ def test_sop_instance(self):
+ """Test generate_instance_uid kwarg"""
+ ds = Dataset()
+ ds.SOPInstanceUID = "1.2.3.4"
+
+ set_pixel_data(ds, np.zeros((3, 5, 3), dtype="u1"), "RGB", 8)
+ uid = ds.SOPInstanceUID
+ assert uid != "1.2.3.4"
+ set_pixel_data(
+ ds, np.zeros((3, 5, 3), dtype="u1"), "RGB", 8, generate_instance_uid=False
+ )
+ assert ds.SOPInstanceUID == uid
diff --git a/tests/test_dataelem.py b/tests/test_dataelem.py
index 62a88bb8fe..3c96cecd93 100644
--- a/tests/test_dataelem.py
+++ b/tests/test_dataelem.py
@@ -1232,3 +1232,22 @@ def test_invalid_very_long_value_length(self, vr, value):
DataElement(0x00410001, vr, value, validation_mode=config.WARN)
with pytest.raises(ValueError, match=msg):
DataElement(0x00410001, vr, value, validation_mode=config.RAISE)
+
+ @pytest.mark.skipif(not config.have_numpy, reason="Numpy is not available")
+ def test_pixel_data_ndarray_raises(self):
+ """Test exception raised if setting PixelData using ndarray"""
+ import numpy as np
+
+ ds = Dataset()
+ ds.PixelData = b"\x00\x01"
+ assert ds.PixelData == b"\x00\x01"
+
+ msg = (
+ r"The value for \(7FE0,0010\) 'Pixel Data' should be set using 'bytes' "
+ r"not 'numpy.ndarray'. See the Dataset.set_pixel_data\(\) method for "
+ "an alternative that supports ndarrays."
+ )
+ with pytest.raises(TypeError, match=msg):
+ ds.PixelData = np.ones((3, 4), dtype="u1")
+
+ assert ds.PixelData == b"\x00\x01"
| diff --git a/doc/reference/pixels.rst b/doc/reference/pixels.rst
index 27811dbf8d..7e6bf7d426 100644
--- a/doc/reference/pixels.rst
+++ b/doc/reference/pixels.rst
@@ -34,6 +34,7 @@ Utility functions
iter_pixels
pack_bits
pixel_array
+ set_pixel_data
unpack_bits
diff --git a/doc/reference/pixels.utils.rst b/doc/reference/pixels.utils.rst
index 31b2b40ee2..0d13f7fb04 100644
--- a/doc/reference/pixels.utils.rst
+++ b/doc/reference/pixels.utils.rst
@@ -24,4 +24,5 @@ Pixel data related utility functions.
pixel_array
pixel_dtype
reshape_pixel_array
+ set_pixel_data
unpack_bits
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index 0e284dffb4..a0f8a30a07 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -62,6 +62,8 @@ Changes
``pyjpegls`` or ``pylibjpeg`` with ``pylibjpeg-libjpeg`` can be used instead (:issue:`2008`).
* Using Pillow with JPEG 2000 encoded > 8-bit multi-sample data (such as RGB) now raises an
exception as Pillow cannot decode such data correctly (:issue:`2006`)
+* An exception will now be raised if an :class:`~numpy.ndarray` is used to set
+ *Pixel Data* (:issue:`50`)
Removals
@@ -211,6 +213,10 @@ Enhancements
create the concepts dictionaries in :mod:`pydicom.sr` (:issue:`1021`)
* Refactored the interface for the concepts in :mod:`pydicom.sr` to simplify the access types
(:issue:`1454`)
+* Added the :meth:`Dataset.set_pixel_data()<pydicom.dataset.Dataset.set_pixel_data>` method
+ and :func:`~pydicom.pixels.set_pixel_data` function for automatically setting a
+ dataset's *Pixel Data* and related Image Pixel module elements using an
+ :class:`~numpy.ndarray` (:issue:`50`)
Fixes
| [
{
"components": [
{
"doc": "Use an :class:`~numpy.ndarray` to set the *Pixel Data* and related\nImage Pixel module elements.\n\n.. versionadded:: 3.0\n\nThe following :dcm:`Image Pixel<part03/sect_C.7.6.3.3.html#table_C.7-11c>`\nmodule elements values will be added, updated or removed as necessary... | [
"tests/pixels/test_utils.py::TestPixelArray::test_src",
"tests/pixels/test_utils.py::TestPixelArray::test_ds_out",
"tests/pixels/test_utils.py::TestPixelArray::test_specific_tags",
"tests/pixels/test_utils.py::TestPixelArray::test_index",
"tests/pixels/test_utils.py::TestPixelArray::test_raw",
"tests/pixe... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
[MRG] Add Dataset method and function to set Image Pixel elements using an ndarray
#### Describe the changes
* Adds `set_pixel_data()` which sets the Image Pixel module elements using an `ndarray`
* Adds `Dataset.set_pixel_data()` which wraps `set_pixel_data()`
* Adds an exception to DataElement if setting *Pixel Data* directly using an `ndarray`
Closes #50, finally :fireworks: :champagne: :pinata:
#### Tasks
- [x] Unit tests added that reproduce the issue or prove feature is working
- [x] Fix or feature added
- [x] Code typed and mypy shows no errors
- [x] Documentation updated (if relevant)
- [x] [Preview link](https://output.circle-artifacts.com/output/job/719e19d7-1963-4830-9478-0a43c4e3f84a/artifacts/0/doc/_build/html/index.html)
- [x] Unit tests passing and overall coverage the same or better
----------
</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/pydicom/dataset.py]
(definition of Dataset.set_pixel_data:)
def set_pixel_data( self, arr: "numpy.ndarray", photometric_interpretation: str, bits_stored: int, *, generate_instance_uid: bool = True, ) -> None:
"""Use an :class:`~numpy.ndarray` to set the *Pixel Data* and related
Image Pixel module elements.
.. versionadded:: 3.0
The following :dcm:`Image Pixel<part03/sect_C.7.6.3.3.html#table_C.7-11c>`
module elements values will be added, updated or removed as necessary:
* (0028,0002) *Samples per Pixel* using a value corresponding to
`photometric_interpretation`.
* (0028,0104) *Photometric Interpretation* from `photometric_interpretation`.
* (0028,0006) *Planar Configuration* will be added and set to ``0`` if
*Samples per Pixel* is > 1, otherwise it will be removed.
* (0028,0008) *Number of Frames* from the array :attr:`~numpy.ndarray.shape`,
however it will be removed if `arr` only contains a single frame.
* (0028,0010) *Rows* and (0028,0011) *Columns* from the array
:attr:`~numpy.ndarray.shape`.
* (0028,0100) *Bits Allocated* from the array :class:`~numpy.dtype`.
* (0028,0101) *Bits Stored* and (0028,0102) *High Bit* from `bits_stored`.
* (0028,0103) *Pixel Representation* from the array :class:`~numpy.dtype`.
In addition:
* The *Transfer Syntax UID* will be set to *Explicit VR Little Endian* if
it doesn't already exist or uses a compressed (encapsulated) transfer syntax.
* If `generate_instance_uid` is ``True`` (default) then the *SOP Instance UID*
will be added or updated.
Parameters
----------
arr : numpy.ndarray
An array with :class:`~numpy.dtype` uint8, uint16, int8 or int16. The
array must be shaped as one of the following:
* (rows, columns) for a single frame of grayscale data.
* (frames, rows, columns) for multi-frame grayscale data.
* (rows, columns, samples) for a single frame of multi-sample data
such as RGB.
* (frames, rows, columns, samples) for multi-frame, multi-sample data.
photometric_interpretation : str
The value to use for (0028,0004) *Photometric Interpretation*. Valid
values are ``"MONOCHROME1"``, ``"MONOCHROME2"``, ``"PALETTE COLOR"``,
``"RGB"``, ``"YBR_FULL"``, ``"YBR_FULL_422"``.
bits_stored : int
The value to use for (0028,0101) *Bits Stored*. Must be no greater than
the number of bits used by the :attr:`~numpy.dtype.itemsize` of `arr`.
generate_instance_uid : bool, optional
If ``True`` (default) then add or update the (0008,0018) *SOP Instance
UID* element with a value generated using :func:`~pydicom.uid.generate_uid`.
Raises
------
NotImplementedError
If the dataset has a big-endian *Transfer Syntax UID*."""
[end of new definitions in src/pydicom/dataset.py]
[start of new definitions in src/pydicom/pixels/utils.py]
(definition of set_pixel_data:)
def set_pixel_data( ds: "Dataset", arr: "np.ndarray", photometric_interpretation: str, bits_stored: int, *, generate_instance_uid: bool = True, ) -> None:
"""Use an :class:`~numpy.ndarray` to set a dataset's *Pixel Data* and related
Image Pixel module elements.
.. versionadded:: 3.0
The following :dcm:`Image Pixel<part03/sect_C.7.6.3.3.html#table_C.7-11c>`
module elements values will be added, updated or removed as necessary:
* (0028,0002) *Samples per Pixel* using a value corresponding to
`photometric_interpretation`.
* (0028,0004) *Photometric Interpretation* from `photometric_interpretation`.
* (0028,0006) *Planar Configuration* will be added and set to ``0`` if
*Samples per Pixel* is > 1, otherwise it will be removed.
* (0028,0008) *Number of Frames* from the array :attr:`~numpy.ndarray.shape`,
however it will be removed if `arr` only contains a single frame.
* (0028,0010) *Rows* and (0028,0011) *Columns* from the array
:attr:`~numpy.ndarray.shape`.
* (0028,0100) *Bits Allocated* from the array :class:`~numpy.dtype`.
* (0028,0101) *Bits Stored* and (0028,0102) *High Bit* from `bits_stored`.
* (0028,0103) *Pixel Representation* from the array :class:`~numpy.dtype`.
In addition:
* The *Transfer Syntax UID* will be set to *Explicit VR Little
Endian* if it doesn't already exist or uses a compressed (encapsulated)
transfer syntax.
* If `generate_instance_uid` is ``True`` (default) then the *SOP Instance UID*
will be added or updated.
Parameters
----------
ds : pydicom.dataset.Dataset
The little endian encoded dataset to be modified.
arr : np.ndarray
An array with :class:`~numpy.dtype` uint8, uint16, int8 or int16. The
array must be shaped as one of the following:
* (rows, columns) for a single frame of grayscale data.
* (frames, rows, columns) for multi-frame grayscale data.
* (rows, columns, samples) for a single frame of multi-sample data
such as RGB.
* (frames, rows, columns, samples) for multi-frame, multi-sample data.
photometric_interpretation : str
The value to use for (0028,0004) *Photometric Interpretation*. Valid values
are ``"MONOCHROME1"``, ``"MONOCHROME2"``, ``"PALETTE COLOR"``, ``"RGB"``,
``"YBR_FULL"``, ``"YBR_FULL_422"``.
bits_stored : int
The value to use for (0028,0101) *Bits Stored*. Must be no greater than
the number of bits used by the :attr:`~numpy.dtype.itemsize` of `arr`.
generate_instance_uid : bool, optional
If ``True`` (default) then add or update the (0008,0018) *SOP Instance
UID* element with a value generated using :func:`~pydicom.uid.generate_uid`."""
[end of new definitions in src/pydicom/pixels/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>> | Here is the discussion in the issues of the pull request.
<issues>
Harmonize pixel data representations
_From [darcymason@gmail.com](https://code.google.com/u/darcymason@gmail.com/) on May 27, 2009 22:58:02_
A pydicom "gotcha" comes from disconnect between Dataset.pixel_array
property and Dataset.PixelData. The latter is actually in the Dataset (a
dict), the former is created from it but changes are not written back
unless ds.PixelData is explicitly set with e.g. pixel_array.tostring().
Possible solutions:
- always require Numpy, always convert pixel data into numpy array. Problem
is this requires decompressing JPEG data (which is not available yet in
pydicom and would possibly waste time on a step that might never be used if
the code is not modifying pixels).
- link pixel_array and PixelData together. if pixel_array is asked for,
keep reference to it in dataset instance and automatically do tostring()
before data is written. But what if user modified pixel_array and modified
PixelData directly (current code would do that using the tostring() method
mentioned above). Could see which one was modified most recently and use
that as the definitive final value, or could throw an error or warning of
possible inconsistent pixel data changes.
This idea means PixelData probably needs to be redefined as a property so
can flag writes to it. That makes it 'special' and different than other
items in the Dataset dict, but perhaps that is necessary.
I like the second idea better, but am hoping someone can come up with an
even cleaner solution.
_Original issue: http://code.google.com/p/pydicom/issues/detail?id=49_
----------
_From [martin.s...@gmail.com](https://code.google.com/u/117165200637345497847/) on September 17, 2009 16:37:11_
The secound lazy approach sounds better to me too, however...
The modification of pixel_array may also effect; Rows, Columns, Bits Stored, Smallest
Image Pixel Value, Largest Image Pixel Value. Perhaps pixel_array should be a class
corresponding to an Image Pixel Module (PS 3.3 - 2008 C.7.6.3).
If the pixel_aray were requested, then the workflow could be to attempt to extract a
representation of an Image Pixel Module from a DICOM file, which could raise an
exception if there are problems with the tags.
To get around editing data in two places, and having it crash. In the case that
attempts were made to read one of these tags and the module had been changed, then
the module could write itself back to the tags. In the case that any attempts were
made to write, then the module could update itself or return to a state that it will
lazily evaluate itself again if required.
This concept could potentially be extended to other DICOM modules. With the various
modules extending from a common base.
_From [darcymason@gmail.com](https://code.google.com/u/darcymason@gmail.com/) on September 23, 2009 06:09:46_
Martin, you've given some good ideas here -- the idea of a Module object is very
interesting. Conceptually I've always thought of pydicom as a low-level library, just
reading files and giving back a bag of data elements, requiring the user code to
structure their meaning and make sure they are self-consistent. However, perhaps
there is room to add a Module layer on top. I'd like to see it be explicit (as per
the usual "Explicit is better than Implicit" python philosophy) -- in other words,
the user calls code that is clearly operating at the Module level. This could mean a
new "SmartDataset" object, say, or a dataset.modules object that calls are made to
when you want self-consistency to be enforced. To do it in a general way (not just
for Pixel data) would require some thought and a significant amount of new code (and
IOD definitions files). I've added a new issue ( issue 57 ) for this.
_From [darcymason@gmail.com](https://code.google.com/u/darcymason@gmail.com/) on December 23, 2011 19:30:33_
Changing status as this is not a priority for next release.
**Labels:** -Milestone-NextRelease Milestone-Release1.5
This was also raised in #178. As noted there, we need a setter for pixel_array (unless actually use a new backward-incompatible PixelData directly). Question is whether the setter also keeps track of and sets other data elements through the Module concept.
So, having read this discussion now, maybe we can work toward a solution. Darcy, I like your original ideas, particularly the second. I guess an executive decision needs to be made whether to link `PixelData` and `pixel_array`.
(P.S. I retract this solution but keep it for discussion's sake)
Perhaps we can make a solution that accommodates both...
We could leave the `pixel_array` property alone for backwards-compatibility, but push a getter and setter (`set_pixel_array()`, `get_pixel_array()`; an internal function already exists for the getter). With an explicit setter we could also pass a parameter, something like `propagate_changes` for lack of a better term. This boolean flag, if true, would write to `PixelData` and update the `Rows`, etc tags to be consistent. False would simply be current behavior. This all assumes that `pixel_array` and `PixelData` are separate entities.
As I reread this it seems like things might get complicated. What if a user sets the pixel array with the setter but without propagating changes. What would the user expect? Given that a user can change any other tag directly and it's saved, e.g. with `.save_as()`, upon writing, shouldn't the user expect the same from `pixel_array`? The `pixel_array` setter and getter would require Numpy, but `PixelData` could still be edited directly. Given that there is no current setter for `pixel_array` there's no backwards-compatible issues, yes?
"Could see which one was modified most recently and use that as the definitive final value" If they are linked (`pixel_array` assignments (the setter) write to `PixelData` and `pixel_array` (the getter) reads from `PixelData`) then the first issue seems to be negated. IDK how fast `.tostring()` is, so maybe it's a performance hit.
"or could throw an error or warning of possible inconsistent pixel data changes." This seems like a good idea no matter what and could be incorporated into the setter. It seems like a good idea still though to set other relevant tags with the setter as well.
My hat goes to linking them, but my hat's pretty small ;-)
I think the settable property is a no-go if you ever want to support any form of data compression. In order to map from `pixel_array` to `PixelData`, you will need to know the transfer syntax (ie the compression scheme), cols, rows, # bit used per pixel, etc.
Assuming you don't want to require the user to have set those on the data set in advance, something like this makes sense:
`dataset.set_image(pixel_array, rows, cols, transfer_syntax,...)` where those values are then all set on the underlying dataset.
@jrkerns, yes, there are a lot of complications to figure out. However, I think I may have found a potential way through all of it. See the [iod branch](https://github.com/darcymason/pydicom/commit/7ab8823039b0b30549e5e42c66eee4cd73cd9754) for a proof of principle start on this. The idea is that a "Module" defines a list of tags that it "owns". The modules register themselves with Dataset -- If any of the tags is called in the dataset, it is hooked into the module class to get or set them. This can preserve backwards compatibilty, because user code can simply turn off the module hooks to run old code. Still lots to work out here in terms of pixels. For example I'm fairly sure a numpy array of pixels by itself does not uniquely determine number of planes and colour planes vs gray scale etc. So we might be back to a set_image() type function as Alex has mentioned.
@cancan101, you make a good point about transfer syntax. However, I read that with the emphasis on the word "transfer", meaning the syntax can be whatever we want until communicating it to someone else. So it should be possible to leave the pixel data in whatever representation we want internally, until the point where it is written somewhere else. I would argue that after reading a file, regardless of transfer syntax, if someone tried to access the pixels they would want them decompressed or else they cannot be sensibly interpreted anyway. So the ImagePixel module would keep track of the original syntax, convert when pixels requested, and when writing, reconvert if pixels have been changed or if the transfer syntax was changed. It would require some internal flags, but i think it wouldn't be too bad.
There was a lot of discussion previously, now I'm trying to tidy this up for v1.0 release (or not).
Here is my 'gun to the head' gotta make a decision, quick solution:
- make `PixelData` gettable or settable as a numpy array
- `pixel_array` can stay as a 'getter', perhaps with DeprecationWarning, but is simply an alias for `PixelData`
- as now, setting pixel data is done without enforcing connection to Rows, Columns, planes and all that. Like all other data elements, consistency across data elements is up to the user code.
- notwithstanding the point above, we could warn on obvious inconsistencies
Explanation: Pydicom makes dicom file data element values available as the natural python type for that value. This proposal extends that to `PixelData`. The natural python type for that is a numpy array.
If that is the path, here are the implementation details:
- on writing `PixelData`, if it is a numpy array, it is converted to bytes for the file (i.e. `tostring()` is done for the user transparently).
- wherever `PixelData` has been used internally in pydicom (including unit tests), it will likely be need to be changed to `pixel_bytes()` or some name like that, that actually returns the raw bytes pydicom has previously expected.
- `pixel_array` coded as alias for `PixelData` getter, as mentioned above
- on setting `PixelData`, bytes are acceptable (for backwards compatibility), or a numpy array.
Compressed pixel data complicates this. For now we could just raise NotImplemented if the `Dataset` transfer syntax is a compressed one, i.e. the user is free to decompress and then write the file, but it is an error unless they change the transfer syntax to an uncompressed version.
Backwards-incompatibilty: with the above solution, `PixelData` no longer returns 1-D bytes, but a correctly dimensioned numpy array. If any old user code actually used the bytes directly, that code will probably break. I suspect this is very rare, as `pixel_array` would have been the natural way to
use pixel data.
I think this is a good solution all around. It minimizes backwards incompatibility, and is consistent with pydicom philosophy for other data types. I've also coded much of this before in test branches, so it can be implemented fairly quickly.
I disagree with the suggested changes. I think that `PixelData` should continue to return the raw bytes. This would be 1. consistent with previous behavior and 2. consistent with how the attr access works for all other dicom keywords. Further the idea of transparently calling `tostring` on the array when assigning is problematic. This works when creating uncompressed dicoms, but currently I am creating some compressed dicoms. this involves me creating the compressed binary representation and then assigning it to `PixelData`.
Further the "what" that is returned when accessing either of `pixel_array` or your new `PixelData` still seems somewhat ambiguous. There is the question as to whether you return the LUT value, the YBR value or the RGB value (see https://github.com/pydicom/pydicom/issues/273 and https://github.com/pydicom/pydicom/issues/263).
I think having variables that are named clearly based on what they return makes a lot of sense. pixel_data, as a naive person like me would understand it, is the data from the pixels in some format I can work pixel_bytes is the same data in bytes. I can think of use cases for wanting both -
the one that is strongest for my groups are just wanting to extract pixel data for image processing, in which case the numpy array is much preferable. I'm not sure about using tostring (when moving from bytes to string I usually use decode('utf0-8') or something like that, but I suspect this is different).
> I think that PixelData should continue to return the raw bytes. This would be 1. consistent with previous behavior and 2. consistent with how the attr access works for all other dicom keywords
Where are raw bytes returned for other DICOM keywords? Binary numbers, for example, are changed to int, float, etc. Multi-valued items are split by the slash and returned as python data types. RawDataElement's carry the raw bytes, but only until they are accessed, then they are converted.
> There is the question as to whether you return the LUT value, the YBR value or the RGB value (see #273 and #263).
Yes, this is an issue. But in any case we have a numpy array to return, whether it is called `PixelData` or `pixel_array`. Similarly if the user wants to modify it and write back to file, then we need a way to convert them to some binary representation. In any case, with my proposal, users would still be able to get the raw bytes (through `pixel_bytes`), and are able to write a bytes array to PixelData to have that control if they needed it.
I don't love the idea that depending on whether it is bytes or an array that is assigned to `PixelData`, the behavior is different.
There is some concern there, I suppose, but in line with python's 'We are all consenting adults' philosophy, I see it that if someone assigns bytes, then they have full control, we write what they set. If they assign a numpy array, we are going to convert it to bytes when it is written. If that isn't what they wanted then they must have assigned the wrong array anyway, or have not set the other image-related data elements for resolution, transfer syntax, etc. correctly.
One concern is that if the user sets `PixelData` with bytes, then accesses the value, it will trigger a conversion to a numpy array, which will depend on the other data elements. But we could also use @cancan101's convenience function from a comment further up this thread:
> dataset.set_image(pixel_array, rows, cols, transfer_syntax,...)
to help guide that down the right path. Maybe that should be the way that is documented as the 'correct' way to set a pixel array.
I would also prefer not to break existing code (meaning mine). I am used to the pixel_array/PixelData duality and I don't find it any worse than the horror that is character encodings in python 2.7. I like the idea that pydicom can read any tag right out of the box without needing numpy/scipy/pillow/etc.
Any change that breaks client code is a big step.
I appreciate everyone's comments. I'm certainly willing to keep things as they are, which is obviously much easier.
Interestingly, though, I just tried something:
```python
ds = pydicom.read_file("CT_small.dcm")
pix = ds.pixel_array
ds.PixelData = pix
ds.save_as("del_me.dcm")
```
And compared the output file with the original. Binary identical. So it seems that we can already set the PixelData to a numpy array and it seems to work fine. Reading on python's write() method, it can accept any "bytes-like object" supporting the 'Buffer Protocol' and a C-contiguous buffer. numpy seems to do C order by default, but there is also a [`ascontiguousarray()`](https://docs.scipy.org/doc//numpy/reference/generated/numpy.ascontiguousarray.html) method, which makes me think that my example got lucky, and for larger arrays that are not contiguous in memory, it might not work. Could try some kind of slicing example with a step, I guess, to try to show that. Even if it were needed, `ascontiguousarray()` could be called on writing the file.
Meanwhile, numpy's `tostring()` doc says it is a compatibility alias for `tobytes()`. It would make a lot of sense for us to adopt the latter for all future documentation.
Anyway, I'm wondering about putting together a dev branch to at least get rid of the 'tostring' requirement, let people run it and see if it breaks backwards compatibility. I think it can be done so that it doesn't. And I think it can be done so that numpy is only required if the bytes are accessed. As I said, I'm okay to drop this, but v1.0 is our best time to make a change like this so I want to make sure before I drop it.
@darcymason - is this still something that needs to be done, or is the current state sufficient? I got a bit lost in the discussion (vs the changes made lately in the implementation), not sure if this is still a valid issue.
> is this still something that needs to be done, or is the current state sufficient
Hmmm, I'd like to think about it a bit longer. Re-reading the discussion, my take-home is that at least part of this can be done without breaking backwards compatibility -- for example, assigning a numpy array to PixelData can just be handled the way the user currently does -- by converting it via `tobytes()`. That could save one step that is a little confusing for newcomers.
I would vote to avoid that sort of magic and keep pixeldata as the bytes for assignment and reading and use pixel array for handling numpy arrays.
I still dream of resolving this but have pushed back to v3.0. Reading through quickly again, there was lots of concern about breaking code, but I believe my branch code was showing that it can be done without breaking. But assigning v3.0 just in case...
I would like to add a use case to the discussion of writing to pixel_array / PixelData: changing the shape of pixel_array.
That is, I have a dicom file with multiple slices in it (pixel_array.shape is (10,128,128)) and I want to generate a dicom file whose pixel_array.shape is (1,128,128) and preserves all the metadata and other properties of the original dicom. The contents of the new file are a calculation based on the original 10-slice data.
Example code demonstrating that the setter `.PixelData` does not adjust all of the metadata to match the size/shape of the new data:
```python
my_dcm = pydicom.dcmread(my_dicom_path)
my_pixel_array = my_dcm.pixel_array[3,:,:] # an example calculation
my_dcm.PixelData = my_pixel_array.tostring()
rdpa = raw_dcm.pixel_array
raw_dcm.save_as(filename = denoised_dicom_path)
```
This results in a value error: "The length of the pixel data in the dataset (32768 bytes) doesn't match the expected length (327680 bytes)."
### Assigning PixelData using bytes
This will never be able to update the dataset's Image Pixel module elements:
```python
ds.PixelData = arr.tobytes()
```
At best all we can do is check that the number of bytes matches the dataset, which we already do on trying to write
### Assigning PixelData using ndarray
The following can theoretically update the Image Pixel elements in a (very) limited fashion:
```python
ds.PixelData = arr
```
* It can set (*Rows*, *Columns*) and *Samples per Pixel* for single frame, single sample arrays `(rows, cols)`
* It can probably set *Bits Allocated*?
* It can set *Pixel Representation*
It cannot do anything with `(frames, rows, cols)`, `(rows, cols, samples`) or `(frames, rows, cols, samples)` due to *Planar Configuration* and the inherent ambiguity in the first two shapes. It also cannot set *Bits Stored* in a conformant manner and simply doesn't have the information required to set *Photometric Interpretation*.
### Assigning PixelData using class method
The following would be required to set *Pixel Data* and the Image Pixel elements in a fully conformant manner (additional args/kwargs may be required)
```python
def set_pixel_data(
arr: np.ndarray,
bits_stored: int,
photometric_interpretation: str,
*,
rows: int | None = None,
columns: int | None = None,
number_of_frames: int | None = None,
bits_allocated: int | None = None, # maybe?
planar_configuration: int | None = None,
pack_bits: bool = False,
) -> None:
....
```
Which is not much better than setting the Image Pixel elements manually, but at least lets us add some validation checks.
So, as I see it, the choices to finally stake this issue through the heart and bury it at a crossroad are:
1. Do nothing, the user is responsible for setting the Image Pixel elements to match *Pixel Data*
2. Raise an exception for `ds.PixelData = arr` - nice and unambiguous!
3. Handle the `arr.tobytes()` conversion (but nothing else) - I don't really like this option, you risk this issue rising from the grave all to save users from typing `.tobytes()`
4. Add a `Dataset.set_pixel_data()` method
Or some combination thereof.
I would prefer an explicit `set_pixel_data` method - this would be documented, helps the not-so-DICOM-savvy user, and no magic is involved.
Also probably raising an exception on `ds.PixelData = arr` that points to `set_pixel_data` makes sense.
--------------------
</issues> | f57c7aceaeda48b60ef3d66fdb875db61e5b49a8 |
pydicom__pydicom-2080 | 2,080 | pydicom/pydicom | 2.4 | e91ef37213b023b80bfa7327eaac78df2a3509e7 | 2024-06-25T01:20:02Z | diff --git a/doc/reference/pixels.processing.rst b/doc/reference/pixels.processing.rst
index a5411a1b85..0797a3ebc3 100644
--- a/doc/reference/pixels.processing.rst
+++ b/doc/reference/pixels.processing.rst
@@ -13,6 +13,7 @@ Functions for applying image processing to pixel data.
apply_color_lut
apply_modality_lut
+ apply_presentation_lut
apply_rescale
apply_voi_lut
apply_voi
diff --git a/doc/reference/pixels.rst b/doc/reference/pixels.rst
index 7e6bf7d426..d4b5e6f89a 100644
--- a/doc/reference/pixels.rst
+++ b/doc/reference/pixels.rst
@@ -14,6 +14,7 @@ Image processing functions
apply_color_lut
apply_modality_lut
+ apply_presentation_lut
apply_rescale
apply_voi_lut
apply_voi
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index a0f8a30a07..c9d67b02e1 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -217,6 +217,8 @@ Enhancements
and :func:`~pydicom.pixels.set_pixel_data` function for automatically setting a
dataset's *Pixel Data* and related Image Pixel module elements using an
:class:`~numpy.ndarray` (:issue:`50`)
+* Added :func:`~pydicom.pixels.apply_presentation_lut` for applying a Presentation LUT
+ to an :class:`~numpy.ndarray` (:issue:`1265`)
Fixes
diff --git a/src/pydicom/pixels/__init__.py b/src/pydicom/pixels/__init__.py
index 9be0156ac4..8c9eed3e06 100644
--- a/src/pydicom/pixels/__init__.py
+++ b/src/pydicom/pixels/__init__.py
@@ -5,6 +5,7 @@
from pydicom.pixels.processing import (
apply_color_lut,
apply_modality_lut,
+ apply_presentation_lut,
apply_rescale,
apply_voi_lut,
apply_voi,
diff --git a/src/pydicom/pixels/processing.py b/src/pydicom/pixels/processing.py
index 00eeb0cc0e..8b948e8e31 100644
--- a/src/pydicom/pixels/processing.py
+++ b/src/pydicom/pixels/processing.py
@@ -297,6 +297,82 @@ def apply_modality_lut(arr: "np.ndarray", ds: "Dataset") -> "np.ndarray":
return arr
+def apply_presentation_lut(arr: "np.ndarray", ds: "Dataset") -> "np.ndarray":
+ """Apply a Presentation LUT to `arr` and return the P-values.
+
+ Parameters
+ ----------
+ arr : numpy.ndarray
+ The :class:`~numpy.ndarray` to apply the presentation LUT operation to.
+ ds : dataset.Dataset
+ A dataset containing :dcm:`Presentation LUT Module
+ <part03/sect_C.11.4.html>` elements.
+
+ Returns
+ -------
+ numpy.ndarray
+ If a Presentation LUT Module is present in `ds` then returns an array
+ of P-values, otherwise returns `arr` unchanged.
+
+ Notes
+ -----
+ If the dataset the *Pixel Data* originated from contains a Modality LUT
+ and/or VOI LUT then they must be applied before the Presentation LUT.
+
+ See Also
+ --------
+ :func:`~pydicom.pixels.processing.apply_modality_lut`
+ :func:`~pydicom.pixels.processing.apply_voi_lut`
+ """
+ if "PresentationLUTSequence" in ds:
+ item = ds.PresentationLUTSequence[0]
+ # nr_entries is the number of entries in the LUT
+ # first_map is the first input value mapped and shall always be 0
+ # bit_depth is number of bits for each entry, up to 16
+ nr_entries, first_map, bit_depth = item.LUTDescriptor
+ nr_entries = 2**16 if nr_entries == 0 else nr_entries
+
+ itemsize = 8 if bit_depth <= 8 else 16
+ nr_bytes = nr_entries * (itemsize // 8)
+
+ # P-values to be mapped to the input, always unsigned
+ # LUTData is (US or OW)
+ elem = item["LUTData"]
+ if elem.VR == VR.US:
+ lut = np.asarray(elem.value, dtype="u2")
+ else:
+ lut = np.frombuffer(item.LUTData[:nr_bytes], dtype=f"uint{itemsize}")
+
+ # Set any unused bits to an appropriate value
+ if bit_shift := itemsize - bit_depth:
+ if not lut.flags.writeable:
+ lut = lut.copy()
+
+ np.left_shift(lut, bit_shift, out=lut)
+ np.right_shift(lut, bit_shift, out=lut)
+
+ # Linearly scale `arr` to quantize it to `nr_entries` values
+ arr = arr.astype("float32")
+ arr -= arr.min()
+ arr /= arr.max() / (nr_entries - 1)
+ arr = arr.astype("uint16")
+
+ return lut[arr]
+
+ if "PresentationLUTShape" in ds:
+ transform = ds.PresentationLUTShape.strip().upper()
+ if transform not in ("IDENTITY", "INVERSE"):
+ raise NotImplementedError(
+ "A (2050,0020) 'Presentation LUT Shape' value of "
+ f"'{ds.PresentationLUTShape}' is not supported"
+ )
+
+ if transform == "INVERSE":
+ arr = arr.max() - arr
+
+ return arr
+
+
apply_rescale = apply_modality_lut
| diff --git a/tests/pixels/test_processing.py b/tests/pixels/test_processing.py
index 6556dc792a..e48f87e3c4 100644
--- a/tests/pixels/test_processing.py
+++ b/tests/pixels/test_processing.py
@@ -24,6 +24,7 @@
apply_voi_lut,
apply_voi,
apply_windowing,
+ apply_presentation_lut,
)
from pydicom.uid import ExplicitVRLittleEndian, ImplicitVRLittleEndian
@@ -1683,3 +1684,250 @@ def test_voi_windowing_empty(self):
ds.WindowWidth = None
out = apply_voi_lut(arr, ds)
assert [0, 1, 128, 254, 255] == out.tolist()
+
+
+@pytest.mark.skipif(not HAVE_NP, reason="Numpy is not available")
+class TestApplyPresentationLUT:
+ """Tests for apply_presentation_lut()"""
+
+ def test_shape(self):
+ """Test Presentation LUT Shape"""
+ ds = dcmread(VOI_08_1F)
+ ds.PresentationLUTShape = "IDENTITY"
+ arr = ds.pixel_array
+
+ out = apply_presentation_lut(arr, ds)
+ assert arr is out
+
+ ds.PresentationLUTShape = "INVERSE"
+ out = apply_presentation_lut(arr, ds)
+
+ arr = arr.max() - arr
+ assert np.array_equal(out, arr)
+
+ def test_shape_unknown_raises(self):
+ """Test an unknown Presentation LUT Shape raises an exception"""
+ ds = dcmread(VOI_08_1F)
+ ds.PresentationLUTShape = "FOO"
+
+ msg = (
+ r"A \(2050,0020\) 'Presentation LUT Shape' value of 'FOO' is not supported"
+ )
+ with pytest.raises(NotImplementedError, match=msg):
+ apply_presentation_lut(ds.pixel_array, ds)
+
+ def test_sequence_8bit_unsigned(self):
+ """Test Presentation LUT Sequence with 8-bit unsigned input"""
+ # 8 bit unsigned input
+ ds = dcmread(VOI_08_1F)
+ assert ds.BitsStored == 8
+ assert ds.PixelRepresentation == 0
+ ds.PresentationLUTSequence = [Dataset()]
+ seq = ds.PresentationLUTSequence
+
+ # 256 entries, 10 bit output
+ seq[0].LUTDescriptor = [256, 0, 10]
+ seq[0].LUTData = [int(round(x * (2**10 - 1) / 255, 0)) for x in range(0, 256)]
+ seq[0]["LUTData"].VR = "US"
+
+ arr = ds.pixel_array
+ assert (arr.min(), arr.max()) == (0, 255)
+
+ coords = [(335, 130), (285, 130), (235, 130), (185, 130), (185, 180)]
+ coords.extend(
+ [(185, 230), (185, 330), (185, 380), (235, 380), (285, 380), (335, 380)]
+ )
+
+ results = [0, 25, 51, 76, 102, 127, 153, 178, 204, 229, 255]
+ for (y, x), result in zip(coords, results):
+ assert arr[y, x] == result
+
+ out = apply_presentation_lut(arr, ds)
+ assert out.dtype == "uint16"
+ assert (out.min(), out.max()) == (0, 1023)
+
+ results = [0, 100, 205, 305, 409, 509, 614, 714, 818, 919, 1023]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # Reversed output
+ seq[0].LUTData.reverse()
+ out = apply_presentation_lut(arr, ds)
+ assert out.dtype == "uint16"
+ assert (out.min(), out.max()) == (0, 1023)
+
+ results = [1023, 923, 818, 718, 614, 514, 409, 309, 205, 104, 0]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # 4096 entries, 16-bit output
+ seq[0].LUTDescriptor = [4096, 0, 16]
+ seq[0].LUTData = [int(round(x * (2**16 - 1) / 4095, 0)) for x in range(0, 4096)]
+ out = apply_presentation_lut(arr, ds)
+ assert out.dtype == "uint16"
+ assert (out.min(), out.max()) == (0, 65535)
+
+ results = [
+ 0,
+ 6417,
+ 13107,
+ 19524,
+ 26214,
+ 32631,
+ 39321,
+ 45738,
+ 52428,
+ 58845,
+ 65535,
+ ]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # 4096 entries, 8-bit output
+ seq[0].LUTDescriptor = [4096, 0, 8]
+ seq[0].LUTData = [int(round(x * (2**8 - 1) / 4095, 0)) for x in range(0, 4096)]
+ out = apply_presentation_lut(arr, ds)
+
+ results = [0, 25, 51, 76, 102, 127, 153, 178, 204, 229, 255]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # 4096 entries, 8-bit output, LUTData as 8-bit bytes
+ seq[0].LUTDescriptor = [4096, 0, 8]
+ seq[0]["LUTData"].VR = "OW"
+ seq[0].LUTData = b"".join(
+ x.to_bytes(length=1, byteorder="little") for x in seq[0].LUTData
+ )
+ out = apply_presentation_lut(arr, ds)
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # 4096 entries, 8-bit output, LUTData as 16-bit bytes
+ seq[0].LUTDescriptor = [4096, 0, 16]
+ seq[0]["LUTData"].VR = "OW"
+ seq[0].LUTData = [int(round(x * (2**16 - 1) / 4095, 0)) for x in range(0, 4096)]
+ seq[0].LUTData = b"".join(
+ x.to_bytes(length=2, byteorder="little") for x in seq[0].LUTData
+ )
+ out = apply_presentation_lut(arr, ds)
+ results = [
+ 0,
+ 6417,
+ 13107,
+ 19524,
+ 26214,
+ 32631,
+ 39321,
+ 45738,
+ 52428,
+ 58845,
+ 65535,
+ ]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # 4096 entries, 8-bit output, LUTData ambiguous
+ seq[0]["LUTData"].VR = "US or OW"
+ out = apply_presentation_lut(arr, ds)
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ def test_sequence_12bit_signed(self):
+ """Test Presentation LUT Sequence with 12-bit signed input."""
+ ds = dcmread(MOD_16_SEQ)
+ assert ds.BitsStored == 12
+ assert ds.PixelRepresentation == 1
+ ds.PresentationLUTSequence = [Dataset()]
+ seq = ds.PresentationLUTSequence
+
+ # 256 entries, 10 bit output
+ seq[0].LUTDescriptor = [256, 0, 10]
+ seq[0].LUTData = [int(round(x * (2**10 - 1) / 255, 0)) for x in range(0, 256)]
+ seq[0]["LUTData"].VR = "US"
+
+ arr = ds.pixel_array
+ assert (arr.min(), arr.max()) == (-2048, 2047)
+
+ coords = [(335, 130), (285, 130), (235, 130), (185, 130), (185, 180)]
+ coords.extend(
+ [(185, 230), (185, 330), (185, 380), (235, 380), (285, 380), (335, 380)]
+ )
+
+ results = [-2048, -1639, -1229, -820, -410, -1, 409, 818, 1228, 1637, 2047]
+ for (y, x), result in zip(coords, results):
+ assert arr[y, x] == result
+
+ out = apply_presentation_lut(arr, ds)
+ assert out.dtype == "uint16"
+ assert (out.min(), out.max()) == (0, 1023)
+
+ results = [0, 100, 205, 305, 409, 509, 614, 714, 818, 919, 1023]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # Reversed output
+ seq[0].LUTData.reverse()
+ out = apply_presentation_lut(arr, ds)
+ assert out.dtype == "uint16"
+ assert (out.min(), out.max()) == (0, 1023)
+
+ results = [1023, 923, 818, 718, 614, 514, 409, 309, 205, 104, 0]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # 4096 entries, 16-bit output
+ seq[0].LUTDescriptor = [4096, 0, 16]
+ seq[0].LUTData = [int(round(x * (2**16 - 1) / 4095, 0)) for x in range(0, 4096)]
+ out = apply_presentation_lut(arr, ds)
+ assert out.dtype == "uint16"
+ assert (out.min(), out.max()) == (0, 65535)
+
+ results = [
+ 0,
+ 6545,
+ 13107,
+ 19652,
+ 26214,
+ 32759,
+ 39321,
+ 45866,
+ 52428,
+ 58973,
+ 65535,
+ ]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ # 4096 entries, 8-bit output
+ seq[0].LUTDescriptor = [4096, 0, 8]
+ seq[0].LUTData = [int(round(x * (2**8 - 1) / 4095, 0)) for x in range(0, 4096)]
+ out = apply_presentation_lut(arr, ds)
+
+ results = [0, 25, 51, 76, 102, 127, 153, 178, 204, 229, 255]
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
+
+ def test_sequence_bit_shift(self):
+ """Test bit shifting read-only LUTData"""
+ ds = dcmread(MOD_16_SEQ)
+ assert ds.BitsStored == 12
+ assert ds.PixelRepresentation == 1
+ ds.PresentationLUTSequence = [Dataset()]
+ seq = ds.PresentationLUTSequence
+
+ # 256 entries, 10 bit output
+ seq[0].LUTDescriptor = [256, 0, 10]
+ seq[0].LUTData = [int(round(x * (2**10 - 1) / 255, 0)) for x in range(0, 256)]
+ seq[0].LUTData = b"".join(
+ x.to_bytes(length=2, byteorder="little") for x in seq[0].LUTData
+ )
+ seq[0]["LUTData"].VR = "OW"
+
+ out = apply_presentation_lut(ds.pixel_array, ds)
+ results = [0, 100, 205, 305, 409, 509, 614, 714, 818, 919, 1023]
+ coords = [(335, 130), (285, 130), (235, 130), (185, 130), (185, 180)]
+ coords.extend(
+ [(185, 230), (185, 330), (185, 380), (235, 380), (285, 380), (335, 380)]
+ )
+ for (y, x), result in zip(coords, results):
+ assert out[y, x] == result
| diff --git a/doc/reference/pixels.processing.rst b/doc/reference/pixels.processing.rst
index a5411a1b85..0797a3ebc3 100644
--- a/doc/reference/pixels.processing.rst
+++ b/doc/reference/pixels.processing.rst
@@ -13,6 +13,7 @@ Functions for applying image processing to pixel data.
apply_color_lut
apply_modality_lut
+ apply_presentation_lut
apply_rescale
apply_voi_lut
apply_voi
diff --git a/doc/reference/pixels.rst b/doc/reference/pixels.rst
index 7e6bf7d426..d4b5e6f89a 100644
--- a/doc/reference/pixels.rst
+++ b/doc/reference/pixels.rst
@@ -14,6 +14,7 @@ Image processing functions
apply_color_lut
apply_modality_lut
+ apply_presentation_lut
apply_rescale
apply_voi_lut
apply_voi
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index a0f8a30a07..c9d67b02e1 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -217,6 +217,8 @@ Enhancements
and :func:`~pydicom.pixels.set_pixel_data` function for automatically setting a
dataset's *Pixel Data* and related Image Pixel module elements using an
:class:`~numpy.ndarray` (:issue:`50`)
+* Added :func:`~pydicom.pixels.apply_presentation_lut` for applying a Presentation LUT
+ to an :class:`~numpy.ndarray` (:issue:`1265`)
Fixes
| [
{
"components": [
{
"doc": "Apply a Presentation LUT to `arr` and return the P-values.\n\nParameters\n----------\narr : numpy.ndarray\n The :class:`~numpy.ndarray` to apply the presentation LUT operation to.\nds : dataset.Dataset\n A dataset containing :dcm:`Presentation LUT Module\n <par... | [
"tests/pixels/test_processing.py::TestConvertColourSpace::test_unknown_current_raises",
"tests/pixels/test_processing.py::TestConvertColourSpace::test_unknown_desired_raises",
"tests/pixels/test_processing.py::TestConvertColourSpace::test_current_is_desired[RGB-RGB]",
"tests/pixels/test_processing.py::TestCon... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
[MRG] Add function to apply presentation LUT
#### Describe the changes
* Adds a function for applying a Presentation LUT: `pixels.processing.apply_presentation_lut()`
* Closes #1265
#### References
https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.11.6.html
https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.11.4.html
#### Tasks
- [x] Unit tests added that reproduce the issue or prove feature is working
- [x] Fix or feature added
- [x] Code typed and mypy shows no errors
- [x] Documentation updated (if relevant)
- [x] [Preview link](https://output.circle-artifacts.com/output/job/9093f465-c0b8-4820-85ed-ce28e48969c7/artifacts/0/doc/_build/html/index.html)
- [x] Unit tests passing and overall coverage the same or better
----------
</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/pydicom/pixels/processing.py]
(definition of apply_presentation_lut:)
def apply_presentation_lut(arr: "np.ndarray", ds: "Dataset") -> "np.ndarray":
"""Apply a Presentation LUT to `arr` and return the P-values.
Parameters
----------
arr : numpy.ndarray
The :class:`~numpy.ndarray` to apply the presentation LUT operation to.
ds : dataset.Dataset
A dataset containing :dcm:`Presentation LUT Module
<part03/sect_C.11.4.html>` elements.
Returns
-------
numpy.ndarray
If a Presentation LUT Module is present in `ds` then returns an array
of P-values, otherwise returns `arr` unchanged.
Notes
-----
If the dataset the *Pixel Data* originated from contains a Modality LUT
and/or VOI LUT then they must be applied before the Presentation LUT.
See Also
--------
:func:`~pydicom.pixels.processing.apply_modality_lut`
:func:`~pydicom.pixels.processing.apply_voi_lut`"""
[end of new definitions in src/pydicom/pixels/processing.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>
Support for applying Presentation LUT and/or Presentation LUT Shape?
Hi all,
in pixel handlers util there's functionality to apply modality and voi transforms, but there isn't anything yet for handling final presentation transforms. That (as far as I can tell from the standard) means applying a presentation LUT or presentation LUT shape.
Any thoughts on supporting those as well?
---
I'm processing mammo images right now, which have Presentation LUT Shape specified (therefore no Presentation LUT), both IDENTITY and INVERSE. It's fairly easy to handle this myself - but I don't know how to go about implementing apply a presentation LUT if I run across some files that have those present.
thanks!
Richard
----------
We currently don't have such a function. In my understanding, a `Presentation LUT` is only provided in presentation states, and as this is a separate DICOM entity, it probably does not fit well into these utility functions. `Presentation LUT Shape` could be handled (if it is set to `INVERSE`), but as you wrote, this would be trivial, and I'm not sure if it is really needed. @scaramallion, what do you think?
I'm not against the idea, but I have no experience with them in practice so I've been reluctant to try and add something that may be wrong or just inconvenient to use.
Also, I usually have a hard time finding suitable test datasets for this kind of stuff.
Agree on handling Presentation LUT's - they are not that common, and
probably better implemented in a client, as the image is likely displayed
reasonably well without them.
But Presentation LUT Shape's are common in MG images, and I've seen them in
some DR's. The gotcha with these is that if you don't handle INVERSE, the
images will appear inverted (regardless of what you're doing prior to that
in the display pipeline).
So my thoughts would be if the library is going to provide any image
pipelining at all (ie handling modality LUT's/slope/intercept etc - like
got added) then it probably should check and handle Presentation LUT Shape
as well.
I'm thinking that if not, probably less DICOM savvy pydicom users who
haven't dug into all the display levels/tags and know you should check for
it manually will fire off issues/questions about why is their image
inverted.
On Sun, Apr 25, 2021 at 1:58 PM scaramallion ***@***.***>
wrote:
> I'm not against the idea, but I have no experience with them in practice
> so I've been reluctant to try and add something that may be wrong or just
> inconvenient to use.
>
> —
> You are receiving this because you authored the thread.
> Reply to this email directly, view it on GitHub
> <https://github.com/pydicom/pydicom/issues/1265#issuecomment-826388862>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AHX43QFR6EIZAHFX3IPBB3TTKR67RANCNFSM4UADGVEA>
> .
>
@richard-moss if you could provide some suitable test datasets it'd help a lot
...sure no prob - does PY have an anonomiser btw?
On Mon, Apr 26, 2021 at 1:38 PM scaramallion ***@***.***>
wrote:
> @richard-moss <https://github.com/richard-moss> if you could provide some
> suitable test datasets it'd help a lot
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/pydicom/pydicom/issues/1265#issuecomment-827131181>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AHX43QBARSESW6WD4VLAABDTKXFKXANCNFSM4UADGVEA>
> .
>
You can try [deid](https://github.com/pydicom/deid) for anonymisation.
The more variations you can get for *Bits Allocated*, *Bits Stored*, *Pixel Representation* and *Samples per Pixel* the better.
I've got a single set of QC Mammo images I've got that have a set with
IDENTITY and some with INVERSE. They're all 16 allocated, and the same
representation etc sorry.
...is this email public, or can I reply with a dropbox link here for you to
DL them?
On Mon, Apr 26, 2021 at 3:17 PM scaramallion ***@***.***>
wrote:
> You can try deid <https://github.com/pydicom/deid> for anonymisation.
>
> The more variations you can get for *Bits Allocated*, *Bits Stored*, *Pixel
> Representation* and *Samples per Pixel* the better.
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/pydicom/pydicom/issues/1265#issuecomment-827179217>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AHX43QEJDXIBO6Z35YGQ4TTTKXQ6ZANCNFSM4UADGVEA>
> .
>
> They're all 16 allocated, and the same representation etc sorry.
No problem, I know how hard it can be to get a good variation in datasets.
> Can I reply with a dropbox link here for you to DL them?
That'd be great, thanks
here you go...
https://www.dropbox.com/s/l6vridfotkrarfn/dicom.zip?dl=0
On Mon, Apr 26, 2021 at 5:29 PM scaramallion ***@***.***>
wrote:
> They're all 16 allocated, and the same representation etc sorry.
>
> No problem, I know how hard it can be to get a good variation in datasets.
>
> Can I reply with a dropbox link here for you to DL them?
>
> That'd be great, thanks
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/pydicom/pydicom/issues/1265#issuecomment-827224337>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AHX43QAXNDUU4I3ZVS7MNFTTKYANLANCNFSM4UADGVEA>
> .
>
Thanks! I'll take a look at adding the functionality eventually, but working on adding pixel data compression at the moment.
Sounds good!
> On Apr 27, 2021, at 1:42 PM, scaramallion ***@***.***> wrote:
>
>
> Thanks! I'll take a look at adding the functionality eventually, but working on adding pixel data compression at the moment.
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub, or unsubscribe.
`PhotometricInterpretation` in my dcm is `MONOCHROME1`, and I try to change it to `MONOCHROME2` but not working. Change `PresentationLUTShape` to `INVERSE` still not working. Here is my solution:
```python
img = ds.pixel_array
if ds["PhotometricInterpretation"] == "MONOCHROME1":
img = np.max(img) + np.min(img) - img
```
--------------------
</issues> | f57c7aceaeda48b60ef3d66fdb875db61e5b49a8 |
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 retur... | [
"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/c... | 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 | |
tobymao__sqlglot-3696 | 3,696 | tobymao/sqlglot | null | 442c61defe05f4c168a7909d0a5fc5c043a2d2b4 | 2024-06-24T14:14:36Z | diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index 102f3e3ac8..4db30b14ca 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -432,7 +432,6 @@ class Generator(generator.Generator):
exp.cast(e.expression, exp.DataType.Type.TIMESTAMP, copy=True),
exp.cast(e.this, exp.DataType.Type.TIMESTAMP, copy=True),
),
- exp.ParseJSON: rename_func("JSON"),
exp.PercentileCont: rename_func("QUANTILE_CONT"),
exp.PercentileDisc: rename_func("QUANTILE_DISC"),
# DuckDB doesn't allow qualified columns inside of PIVOT expressions.
@@ -612,6 +611,12 @@ class Generator(generator.Generator):
PROPERTIES_LOCATION[exp.LikeProperty] = exp.Properties.Location.POST_SCHEMA
PROPERTIES_LOCATION[exp.TemporaryProperty] = exp.Properties.Location.POST_CREATE
+ def parsejson_sql(self, expression: exp.ParseJSON) -> str:
+ arg = expression.this
+ if expression.args.get("safe"):
+ return self.sql(exp.case().when(exp.func("json_valid", arg), arg).else_(exp.null()))
+ return self.func("JSON", arg)
+
def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
nano = expression.args.get("nano")
if nano is not None:
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index 505fc42428..d8b0305514 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -298,6 +298,7 @@ class Parser(parser.Parser):
"TIMESTAMPDIFF": _build_datediff,
"TIMESTAMPFROMPARTS": build_timestamp_from_parts,
"TIMESTAMP_FROM_PARTS": build_timestamp_from_parts,
+ "TRY_PARSE_JSON": lambda args: exp.ParseJSON(this=seq_get(args, 0), safe=True),
"TRY_TO_DATE": _build_datetime("TRY_TO_DATE", exp.DataType.Type.DATE, safe=True),
"TO_DATE": _build_datetime("TO_DATE", exp.DataType.Type.DATE),
"TO_NUMBER": lambda args: exp.ToNumber(
@@ -752,6 +753,9 @@ class Generator(generator.Generator):
exp.Map: lambda self, e: var_map_sql(self, e, "OBJECT_CONSTRUCT"),
exp.Max: max_or_greatest,
exp.Min: min_or_least,
+ exp.ParseJSON: lambda self, e: self.func(
+ "TRY_PARSE_JSON" if e.args.get("safe") else "PARSE_JSON", e.this
+ ),
exp.PartitionedByProperty: lambda self, e: f"PARTITION BY {self.sql(e, 'this')}",
exp.PercentileCont: transforms.preprocess(
[transforms.add_within_group_for_percentiles]
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index c55aa62c34..b13d7ab9b4 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -5501,9 +5501,9 @@ class JSONArrayContains(Binary, Predicate, Func):
class ParseJSON(Func):
# BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
+ # Snowflake also has TRY_PARSE_JSON, which is represented using `safe`
_sql_names = ["PARSE_JSON", "JSON_PARSE"]
- arg_types = {"this": True, "expressions": False}
- is_var_len_args = True
+ arg_types = {"this": True, "expression": False, "safe": False}
class Least(Func):
| diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py
index 2bde478482..01a01167f1 100644
--- a/tests/dialects/test_duckdb.py
+++ b/tests/dialects/test_duckdb.py
@@ -18,6 +18,13 @@ def test_duckdb(self):
"WITH _data AS (SELECT [STRUCT(1 AS a, 2 AS b), STRUCT(2 AS a, 3 AS b)] AS col) SELECT col.b FROM _data, UNNEST(_data.col) AS col WHERE col.a = 1",
)
+ self.validate_all(
+ """SELECT CASE WHEN JSON_VALID('{"x: 1}') THEN '{"x: 1}' ELSE NULL END""",
+ read={
+ "duckdb": """SELECT CASE WHEN JSON_VALID('{"x: 1}') THEN '{"x: 1}' ELSE NULL END""",
+ "snowflake": """SELECT TRY_PARSE_JSON('{"x: 1}')""",
+ },
+ )
self.validate_all(
"SELECT straight_join",
write={
| [] | [
"tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"
] | [
"tests/dialects/test_duckdb.py::TestDuckDB::test_array",
"tests/dialects/test_duckdb.py::TestDuckDB::test_array_index",
"tests/dialects/test_duckdb.py::TestDuckDB::test_cast",
"tests/dialects/test_duckdb.py::TestDuckDB::test_encode_decode",
"tests/dialects/test_duckdb.py::TestDuckDB::test_isinf",
"tests/d... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Feat: transpile TRY_PARSE_JSON Snowflake -> DuckDB
Fixes #3690
References:
- https://docs.snowflake.com/en/sql-reference/functions/try_parse_json
- https://duckdb.org/docs/extensions/json.html
----------
</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>
</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>
Support for try_parse_json
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
I'm using sqlglot through sqlmesh and I have to use a macro for getting try_parse_json to work in duckdb.
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
I would like try_parse_json to be supported in sqlglot.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
I tried using check_json as well but it's not supported either.
I ended up writing a conditional macro in sqlmesh to change the code depending on the gateway/dialect.
@IF(
@gateway = /* duckdb doesn't have try_parse_json and it's not in sqlglot */ 'local',
CASE WHEN JSON_VALID(query_tag) THEN PARSE_JSON(query_tag) ELSE NULL END,
TRY_PARSE_JSON(query_tag)
) AS query_tag,
**Additional context**
Add any other context or screenshots about the feature request here.

----------
--------------------
</issues> | ceb42fabad60312699e4b15936aeebac00e22e4d | |
pydicom__pydicom-2079 | 2,079 | pydicom/pydicom | 2.4 | 974d4151299c5936078cd15a93b788d769794ceb | 2024-06-23T23:37:23Z | diff --git a/doc/reference/index.rst b/doc/reference/index.rst
index c1fd39db81..3fe27c4017 100644
--- a/doc/reference/index.rst
+++ b/doc/reference/index.rst
@@ -30,5 +30,6 @@ This API reference guide details the functions, modules and objects included in
misc
overlays
pixels
+ sr
waveforms
uid
diff --git a/doc/reference/sr.rst b/doc/reference/sr.rst
new file mode 100644
index 0000000000..98015398a7
--- /dev/null
+++ b/doc/reference/sr.rst
@@ -0,0 +1,35 @@
+
+Concepts and Context Groups (:mod:`pydicom.sr`)
+===============================================
+
+.. module:: pydicom.sr
+.. currentmodule:: pydicom.sr
+
+The ``sr`` module contains an interface for DICOM's :dcm:`CIDs<part16/chapter_B.html>`.
+
+
+.. autosummary::
+ :toctree: generated/
+
+ Collection
+ Concepts
+ Code
+
+
+Usage
+-----
+
+Individual :class:`~pydicom.sr.coding.Code` values can be accessed via either
+their scheme (such as SCT) or the DICOM CID::
+
+ >>> from pydicom.sr import codes
+ >>> codes.SCT.Transverse
+ Code(value='62824007', scheme_designator='SCT', meaning='Transverse', scheme_version=None)
+ >>> codes.CID4.Cornea
+ Code(value='28726007', scheme_designator='SCT', meaning='Cornea', scheme_version=None)
+
+A list of available attribute keywords for each scheme or CID is available via
+:meth:`~pydicom.sr.Collection.dir`::
+
+ >>> dir(codes.CID6)
+ ['Coronal', 'FiveChamber', 'FourChamber', ... ]
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index ba491a6aa6..0e284dffb4 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -208,7 +208,9 @@ Enhancements
(if present, although it's non-conformant for it to be) (:issue:`2073`)
* Added support for NumPy v2.0 (:issue:`2075`)
* Added ``pydicom.__concepts_version__`` attribute with the DICOM Standard version used to
- create the concepts dictionaries in ``pydicom.sr`` (:issue:`1021`)
+ create the concepts dictionaries in :mod:`pydicom.sr` (:issue:`1021`)
+* Refactored the interface for the concepts in :mod:`pydicom.sr` to simplify the access types
+ (:issue:`1454`)
Fixes
diff --git a/src/pydicom/sr/__init__.py b/src/pydicom/sr/__init__.py
index d55d83a286..9a48f704f5 100644
--- a/src/pydicom/sr/__init__.py
+++ b/src/pydicom/sr/__init__.py
@@ -1,1 +1,2 @@
-from pydicom.sr.codedict import codes
+from pydicom.sr.codedict import codes, Collection, Concepts
+from pydicom.sr.coding import Code
diff --git a/src/pydicom/sr/codedict.py b/src/pydicom/sr/codedict.py
index 0d6b6b8b14..275b631160 100644
--- a/src/pydicom/sr/codedict.py
+++ b/src/pydicom/sr/codedict.py
@@ -1,9 +1,9 @@
-# Copyright 2008-2019 pydicom authors. See LICENSE file for details.
+# Copyright 2008-2024 pydicom authors. See LICENSE file for details.
"""Access code dictionary information"""
from itertools import chain
import inspect
-from typing import cast, Union
+from typing import cast, Any
from collections.abc import KeysView, Iterable
from pydicom.sr.coding import Code
@@ -43,101 +43,88 @@ def _filtered(source: Iterable[str], filters: Iterable[str]) -> list[str]:
)
-ConceptsType = dict[str, dict[str, dict[str, tuple[str, list[int]]]]]
+CIDValueType = dict[str, tuple[str, list[int]]]
+ConceptsType = dict[str, CIDValueType]
SnomedMappingType = dict[str, dict[str, str]]
-class _CID_Dict:
- repr_format = "{} = {}"
- str_format = "{:20} {:12} {:8} {}\n"
-
- def __init__(self, cid: int) -> None:
- self.cid = cid
- self._concepts: dict[str, Code] = {}
-
- def __dir__(self) -> list[str]:
- """Gives a list of available SR identifiers.
-
- List of attributes is used, for example, in auto-completion in editors
- or command-line environments.
- """
- meths = {v[0] for v in inspect.getmembers(type(self), inspect.isroutine)}
- props = {v[0] for v in inspect.getmembers(type(self), inspect.isdatadescriptor)}
- sr_names = set(self.dir())
-
- return sorted(props | meths | sr_names)
+class Collection:
+ """Interface for a collection of concepts, such as SNOMED-CT, or a DICOM CID.
- def __getattr__(self, name: str) -> Code:
- """Return the ``Code`` for class attribute `name`."""
- matches = [
- scheme
- for scheme, keywords in CID_CONCEPTS[self.cid].items()
- if name in keywords
- ]
+ .. versionadded:: 3.0
+ """
- if not matches:
- raise AttributeError(f"'{name}' not found in CID {self.cid}")
+ repr_format = "{} = {}"
- if len(matches) > 1:
- # Should never happen, but just in case
- raise AttributeError(
- f"Multiple schemes found for '{name}' in CID {self.cid}: "
- f"{', '.join(matches)}"
- )
+ def __init__(self, name: str) -> None:
+ """Create a new collection.
- scheme = matches[0]
- identifiers = cast(dict[str, tuple[str, list[int]]], CONCEPTS[scheme][name])
- # Almost always only one code per identifier
- if len(identifiers) == 1:
- code, val = list(identifiers.items())[0]
+ Parameters
+ ----------
+ name : str
+ The name of the collection, should either be a key in the
+ ``sr._concepts_dict.concepts`` :class:`dict` or a CID name for
+ a CID in ``sr._cid_dict.cid_concepts`` such as ``"CID1234"``.
+ """
+ if not name.upper().startswith("CID"):
+ self._name = name
+ # dict[str, dict[str, tuple(str, list[int])]]
+ # {'ACEInhibitor': {'41549009': ('ACE inhibitor', [3760])},
+ self._scheme_data = CONCEPTS[name]
else:
- _matches = [
- (code, val) for code, val in identifiers.items() if self.cid in val[1]
- ]
- if len(_matches) > 1:
- # Multiple codes shouldn't have the same keyword, but just in case
- codes = ", ".join([f"'{v[0]}'" for v in _matches])
- raise AttributeError(
- f"'{name}' has multiple code matches in CID {self.cid}: {codes}"
- )
+ self._name = f"CID{name[3:]}"
+ # dict[str, list[str]]
+ # {'SCT': ['Pericardium', 'Pleura', 'LeftPleura', 'RightPleura']}
+ self._cid_data = CID_CONCEPTS[int(name[3:])]
- code, val = _matches[0]
-
- return Code(value=code, meaning=val[0], scheme_designator=scheme)
+ self._concepts: dict[str, Code] = {}
@property
def concepts(self) -> dict[str, Code]:
- """Return a dict of {SR identifiers: codes}"""
+ """Return a :class:`dict` of {SR identifiers: codes}"""
if not self._concepts:
self._concepts = {name: getattr(self, name) for name in self.dir()}
return self._concepts
- def __repr__(self) -> str:
- concepts = [
- self.repr_format.format(name, concept)
- for name, concept in self.concepts.items()
- ]
+ def __contains__(self, item: str | Code) -> bool:
+ """Checks whether a given code is a member of the collection.
+
+ Parameters
+ ----------
+ item : pydicom.sr.coding.Code | str
+ The code to check for as either the code or the corresponding
+ keyword.
- return f"CID {self.cid}\n" + "\n".join(concepts)
+ Returns
+ -------
+ bool
+ Whether the collection contains the `code`
+ """
+ if isinstance(item, str):
+ try:
+ code = getattr(self, item)
+ except AttributeError:
+ return False
+ else:
+ code = item
- def __str__(self) -> str:
- """Return a str representation of the instance."""
- s = [f"CID {self.cid} ({name_for_cid[self.cid]})"]
- s.append(self.str_format.format("Attribute", "Code value", "Scheme", "Meaning"))
- s.append(self.str_format.format("---------", "----------", "------", "-------"))
- s.append(
- "\n".join(
- self.str_format.format(name, *concept)
- for name, concept in self.concepts.items()
- )
- )
+ return code in self.concepts.values()
- return "\n".join(s)
+ def __dir__(self) -> list[str]:
+ """Return a list of available concept keywords.
+
+ List of attributes is used, for example, in auto-completion in editors
+ or command-line environments.
+ """
+ meths = {v[0] for v in inspect.getmembers(type(self), inspect.isroutine)}
+ props = {v[0] for v in inspect.getmembers(type(self), inspect.isdatadescriptor)}
+ sr_names = set(self.dir())
+
+ return sorted(props | meths | sr_names)
def dir(self, *filters: str) -> list[str]:
- """Return an sorted list of SR identifiers based on a partial
- match.
+ """Return an sorted list of concept keywords based on a partial match.
Parameters
----------
@@ -148,177 +135,214 @@ def dir(self, *filters: str) -> list[str]:
Returns
-------
list of str
- The matching SR keywords. If no `filters` are used then all
+ The matching keywords. If no `filters` are used then all
keywords are returned.
"""
# CID_CONCEPTS: Dict[int, Dict[str, List[str]]]
- return _filtered(
- chain.from_iterable(CID_CONCEPTS[self.cid].values()),
- filters,
- )
+ if self.is_cid:
+ return _filtered(chain.from_iterable(self._cid_data.values()), filters)
- def __contains__(self, code: Code) -> bool:
- """Checks whether a given code is a member of the context group.
+ return _filtered(self._scheme_data, filters)
+
+ def __getattr__(self, name: str) -> Code:
+ """Return the :class:`~pydicom.sr.Code` corresponding to `name`.
Parameters
----------
- code: pydicom.sr.coding.Code | pydicom.sr.coding.CodedConcept
- coded concept
+ name : str
+ A camel case version of the concept's code meaning, such as
+ ``"FontanelOfSkull" in the SCT coding scheme.
Returns
-------
- bool
- whether CID contains `code`
- """
- return any([concept == code for concept in self.concepts.values()])
-
- def trait_names(self) -> list[str]:
- """Returns a list of valid names for auto-completion code.
- Used in IPython, so that data element names can be found and offered
- for autocompletion on the IPython command line.
+ pydicom.sr.Code
+ The :class:`~pydicom.sr.Code` corresponding to `name`.
"""
- return dir(self)
-
+ if self.name.startswith("CID"):
+ # Try DICOM's CID collections
+ matches = [
+ scheme
+ for scheme, keywords in self._cid_data.items()
+ if name in keywords
+ ]
+ if not matches:
+ raise AttributeError(
+ f"No matching code for keyword '{name}' in {self.name}"
+ )
-class _CodesDict:
- """Interface for a concepts dictionary.
-
- Examples
- --------
- >>> from pydicom.sr import codes
- >>> code = codes.SCT.Deep
- >>> code.value
- '795002'
- >>> code.meaning
- 'Deep'
- >>> code == codes.CID2.Deep # Or use the CID instead
- True
- >>> code = codes.SCT.FontanelOfSkull
- >>> code.value
- '79361005'
- >>> code.meaning
- 'Fontanel of skull'
- """
+ if len(matches) > 1:
+ # Shouldn't happen, but just in case
+ raise RuntimeError(
+ f"Multiple schemes found to contain the keyword '{name}' in "
+ f"{self.name}: {', '.join(matches)}"
+ )
- def __init__(self, scheme: str | None = None) -> None:
- """Create a new CodesDict.
+ scheme = matches[0]
+ identifiers = cast(CIDValueType, CONCEPTS[scheme][name])
+
+ if len(identifiers) == 1:
+ code, val = list(identifiers.items())[0]
+ else:
+ cid = int(self.name[3:])
+ _matches = [
+ (code, val) for code, val in identifiers.items() if cid in val[1]
+ ]
+ if len(_matches) > 1:
+ # Shouldn't happen, but just in case
+ codes = ", ".join(v[0] for v in _matches)
+ raise RuntimeError(
+ f"Multiple codes found for keyword '{name}' in {self.name}: "
+ f"{codes}"
+ )
+
+ code, val = _matches[0]
+
+ return Code(value=code, meaning=val[0], scheme_designator=scheme)
+
+ # Try concept collections such as SCT, DCM, etc
+ try:
+ entries = cast(CIDValueType, self._scheme_data[name])
+ except KeyError:
+ raise AttributeError(
+ f"No matching code for keyword '{name}' in scheme '{self.name}'"
+ )
- Parameters
- ----------
- scheme : str, optional
- The if used, then the scheme designator for the concepts
- dictionary.
- """
- self.scheme = scheme
- self._dict = {scheme: CONCEPTS[scheme]} if scheme else CONCEPTS
+ if len(entries) > 1:
+ # val is {"code": ("meaning", [cid1, cid2, ...], "code": ...}
+ code_values = ", ".join(entries.keys())
+ raise RuntimeError(
+ f"Multiple codes found for keyword '{name}' in scheme '{self.name}': "
+ f"{code_values}"
+ )
- def __dir__(self) -> list[str]:
- """Gives a list of available SR identifiers.
+ code = list(entries.keys())[0] # get first and only
+ meaning, cids = entries[code]
- List of attributes is used, for example, in auto-completion in editors
- or command-line environments.
- """
- meths = {v[0] for v in inspect.getmembers(type(self), inspect.isroutine)}
- props = {v[0] for v in inspect.getmembers(type(self), inspect.isdatadescriptor)}
- sr_names = set(self.dir())
+ return Code(value=code, meaning=meaning, scheme_designator=self.name)
- return sorted(props | meths | sr_names)
+ @property
+ def is_cid(self) -> bool:
+ """Return ``True`` if the collection is one of the DICOM CIDs"""
+ return self.name.startswith("CID")
- def __getattr__(self, name: str) -> Union["_CodesDict", _CID_Dict, Code]:
- """Return either a ``_CodesDict``, ``_CID_Dict`` or ``Code`` depending
- on the `name`.
+ @property
+ def name(self) -> str:
+ """Return the name of the collection."""
+ return self._name
- Parameters
- ----------
- name : str
- One of the following:
+ def __repr__(self) -> str:
+ """Return a representation of the collection."""
+ concepts = [
+ self.repr_format.format(name, concept)
+ for name, concept in self.concepts.items()
+ ]
- * A coding scheme designator such as ``"SCT"``.
- * A concept ID such as ``"CID2"``.
- * If ``_CodesDict.scheme`` is not ``None``, a camel case version
- of the concept's code meaning, such as ``"FontanelOfSkull" in
- the SCT coding scheme.
+ return f"{self.name}\n" + "\n".join(concepts)
- Returns
- -------
- pydicom.sr._CodesDict, pydicom.sr._CID_Dict or pydicom.sr.Code
-
- * If `name` is a concept ID then the ``_CID_Dict`` for the
- corresponding CID.
- * If `name` is a coding scheme designator then the ``_CodesDict``
- instance for the corresponding scheme.
- * If ``_CodesDict.scheme`` is not ``None`` then the ``Code``
- corresponding to `name`.
- """
- # for codes.X, X must be a CID or a scheme designator
- if name.startswith("cid"):
- if not self.scheme:
- return _CID_Dict(int(name[3:]))
+ @property
+ def scheme_designator(self) -> str:
+ """Return the scheme designator for the collection."""
+ return self.name
- raise AttributeError("Cannot use a CID with a scheme dictionary")
+ def __str__(self) -> str:
+ """Return a string representation of the collection."""
+ len_names = max(len(n) for n in self.concepts.keys()) + 2
+ len_codes = max(len(c[0]) for c in self.concepts.values()) + 2
+ len_schemes = max(len(c[1]) for c in self.concepts.values()) + 2
+
+ # Ensure each column is at least X characters wide
+ len_names = max(len_names, 11)
+ len_codes = max(len_codes, 6)
+ len_schemes = max(len_schemes, 8)
+
+ if self.is_cid:
+ fmt = f"{{:{len_names}}} {{:{len_codes}}} {{:{len_schemes}}} {{}}"
+
+ s = [self.name]
+ s.append(fmt.format("Attribute", "Code", "Scheme", "Meaning"))
+ s.append(fmt.format("---------", "----", "------", "-------"))
+ s.append(
+ "\n".join(
+ fmt.format(name, *concept)
+ for name, concept in self.concepts.items()
+ )
+ )
+ else:
+ fmt = f"{{:{len_names}}} {{:{len_codes}}} {{}}"
- if name in self._dict.keys():
- # Return concepts limited only the specified scheme designator
- return _CodesDict(scheme=name)
+ s = [f"Scheme: {self.name}"]
+ s.append(fmt.format("Attribute", "Code", "Meaning"))
+ s.append(fmt.format("---------", "----", "-------"))
- # If not already narrowed to a particular scheme, is an error
- if not self.scheme:
- raise AttributeError(
- f"'{name}' not recognized as a CID or scheme designator"
+ s.append(
+ "\n".join(
+ fmt.format(name, concept[0], concept[2])
+ for name, concept in self.concepts.items()
+ )
)
- # else try to find in this scheme
- try:
- val = cast(dict[str, tuple[str, list[int]]], self._dict[self.scheme][name])
- except KeyError:
- raise AttributeError(
- f"Unknown code name '{name}' for scheme '{self.scheme}'"
- )
+ return "\n".join(s)
- if len(val) > 1:
- # val is {code value: (meaning, cid_list}, code_value: ...}
- code_values = ", ".join(val.keys())
- raise RuntimeError(
- f"Multiple code values for '{name}' found: {code_values}"
- )
+ def trait_names(self) -> list[str]:
+ """Return a list of valid names for auto-completion code.
- code = list(val.keys())[0] # get first and only
- meaning, cids = val[code]
+ Used in IPython, so that data element names can be found and offered
+ for autocompletion on the IPython command line.
+ """
+ return dir(self)
- return Code(value=code, meaning=meaning, scheme_designator=self.scheme)
- def dir(self, *filters: str) -> list[str]:
- """Returns an alphabetical list of SR identifiers based on a partial
- match.
+class Concepts:
+ """Management class for the available concept collections.
+
+ .. versionadded:: 3.0
+ """
- Intended mainly for use in interactive Python sessions.
+ def __init__(self, collections: list[Collection]) -> None:
+ """Create a new concepts management class instance.
Parameters
----------
- filters : str
- Zero or more string arguments to the function. Used for
- case-insensitive match to any part of the SR keyword.
+ collections : list[Collection]
+ A list of the available concept collections.
+ """
+ self._collections = {c.name: c for c in collections}
- Returns
- -------
- list of str
- The matching SR keywords. If no filters are
- used then all keywords are returned.
+ @property
+ def collections(self) -> KeysView[str]:
+ """Return the names of the available concept collections."""
+ return self._collections.keys()
+ def __getattr__(self, name: str) -> Any:
+ """Return the concept collection corresponding to `name`.
+
+ Parameters
+ ----------
+ name : str
+ The scheme designator or CID name for the collection to be returned.
"""
- return _filtered(chain.from_iterable(self._dict.values()), filters)
+ if name.upper().startswith("CID"):
+ name = f"CID{name[3:]}"
- def schemes(self) -> KeysView[str]:
- return self._dict.keys()
+ if name in self._collections:
+ return self._collections[name]
- def trait_names(self) -> list[str]:
- """Returns a list of valid names for auto-completion code.
+ raise AttributeError(
+ f"'{type(self).__name__}' object has no attribute '{name}'"
+ )
- Used in IPython, so that data element names can be found and offered
- for autocompletion on the IPython command line.
+ def schemes(self) -> list[str]:
+ """Return a list of available scheme designations."""
+ return [c for c in self._collections.keys() if not c.startswith("CID")]
+
+ def CIDs(self) -> list[str]:
+ """Return a list of available CID names."""
+ return [c for c in self._collections.keys() if c.startswith("CID")]
- """
- return dir(self)
+# Named concept collections like SNOMED-CT, etc
+_collections = [Collection(designator) for designator in CONCEPTS]
+# DICOM CIDs
+_collections.extend(Collection(f"CID{cid}") for cid in name_for_cid)
-codes = _CodesDict()
+codes = Concepts(_collections)
| diff --git a/tests/test_codes.py b/tests/test_codes.py
index 53254a68d1..a9c6a14eb0 100644
--- a/tests/test_codes.py
+++ b/tests/test_codes.py
@@ -6,7 +6,11 @@
)
from pydicom.sr._concepts_dict import concepts as CONCEPTS
from pydicom.sr.coding import Code
-from pydicom.sr.codedict import codes, _CID_Dict, _CodesDict
+from pydicom.sr.codedict import (
+ codes,
+ Collection,
+ Concepts,
+)
@pytest.fixture()
@@ -44,6 +48,23 @@ def add_nonunique_cid():
del name_for_cid[99999999999]
+@pytest.fixture()
+def add_multiple_cid():
+ """Add multiple codes for a keyword, but with different CIDs"""
+ CONCEPTS["TEST"] = {
+ "Foo": {
+ "BAR": ("Test A", [99999999999]),
+ "BAZ": ("Test B", [99999999998]),
+ },
+ }
+ CID_CONCEPTS[99999999999] = {"TEST": ["Foo"]}
+ name_for_cid[99999999999] = "Test"
+ yield
+ del CONCEPTS["TEST"]
+ del CID_CONCEPTS[99999999999]
+ del name_for_cid[99999999999]
+
+
class TestCode:
def setup_method(self):
self._value = "373098007"
@@ -126,289 +147,181 @@ def test_equal_not_in_snomed_mapping(self):
assert c2 != c1
-class TestCodesDict:
- def test_dcm_1(self):
- assert codes.DCM.Modality == Code(
- value="121139", scheme_designator="DCM", meaning="Modality"
- )
-
- def test_dcm_2(self):
- assert codes.DCM.ProcedureReported == Code(
- value="121058",
- scheme_designator="DCM",
- meaning="Procedure Reported",
- )
+class TestCollection:
+ """Tests for Collection"""
- def test_dcm_3(self):
- assert codes.DCM.ImagingStartDatetime == Code(
- value="122712",
- scheme_designator="DCM",
- meaning="Imaging Start DateTime",
- )
+ def test_init(self):
+ """Test creation of new collections"""
+ coll = Collection("SCT")
+ assert coll.name == "SCT"
+ assert coll.scheme_designator == "SCT"
+ assert coll.is_cid is False
- def test_sct_1(self):
- assert codes.SCT._1SigmaLowerValueOfPopulation == Code(
- value="371919006",
- scheme_designator="SCT",
- meaning="1 Sigma Lower Value of Populuation",
- )
+ coll = Collection("CID2")
+ assert coll.name == "CID2"
+ assert coll.scheme_designator == "CID2"
+ assert coll.is_cid is True
- def test_sct_2(self):
- assert codes.SCT.FindingSite == Code(
- value="363698007", scheme_designator="SCT", meaning="Finding Site"
- )
-
- def test_cid250(self):
- assert codes.cid250.Positive == Code(
- value="10828004", scheme_designator="SCT", meaning="Positive"
- )
-
- def test_cid300(self):
- assert codes.cid300.NickelCobaltChromium == Code(
- value="261249004",
- scheme_designator="SCT",
- meaning="Nickel cobalt chromium",
- )
-
- def test_cid301(self):
- assert codes.cid301.MilligramsPerCubicCentimeter == Code(
- value="mg/cm3", scheme_designator="UCUM", meaning="mg/cm^3"
- )
-
- def test_cid402(self):
- assert codes.cid402.DestinationRoleID == Code(
- value="110152",
- scheme_designator="DCM",
- meaning="Destination Role ID",
- )
-
- def test_cid405(self):
- assert codes.cid405.MultiMediaCard == Code(
- value="110035", scheme_designator="DCM", meaning="Multi-media Card"
+ def test_concepts(self):
+ """Test Collection.concepts"""
+ coll = Collection("UCUM")
+ assert coll._concepts == {}
+ concepts = coll.concepts
+ assert coll._concepts != {}
+ assert concepts["Second"] == Code(
+ "s", scheme_designator="UCUM", meaning="second"
)
- def test_cid610(self):
- assert codes.cid610.ReverseOsmosisPurifiedHclAcidifiedWater == Code(
- value="127291",
- scheme_designator="DCM",
- meaning="Reverse osmosis purified, HCl acidified water",
+ coll = Collection("CID2")
+ assert coll.concepts["Transverse"] == Code(
+ "62824007", scheme_designator="SCT", meaning="Transverse"
)
- def test_cid612(self):
- assert codes.cid612.MonitoredAnesthesiaCareMAC == Code(
- value="398239001",
- scheme_designator="SCT",
- meaning="Monitored Anesthesia Care (MAC)",
- )
+ def test_contains(self):
+ """Test the in operator"""
+ coll = Collection("UCUM")
+ assert "Second" in coll
+ assert "Foo" not in coll
- def test_cid622(self):
- assert codes.cid622.NeuromuscularBlockingNMBNonDepolarizing == Code(
- value="372790002",
- scheme_designator="SCT",
- meaning="NeuroMuscular Blocking (NMB) - non depolarizing",
- )
+ coll = Collection("CID2")
+ assert "Transverse" in coll
+ assert "Foo" not in coll
- def test_cid630(self):
- assert codes.cid630.LidocainePrilocaine == Code(
- value="346553009",
- scheme_designator="SCT",
- meaning="Lidocaine + Prilocaine",
- )
+ c = Code("24028007", "SCT", "Right")
+ assert c in codes.CID244
+ assert c in codes.SCT
- def test_cid643(self):
- assert codes.cid643._6Hydroxydopamine == Code(
- value="4624",
- scheme_designator="PUBCHEM_CID",
- meaning="6-Hydroxydopamine",
- )
+ def test_dir(self):
+ """Test dir()"""
+ coll = Collection("UCUM")
+ assert "Second" in dir(coll)
+ assert "Foo" not in dir(coll)
+
+ coll = Collection("CID2")
+ assert "Transverse" in dir(coll)
+ assert "Foo" not in dir(coll)
+
+ coll = Collection("CID4")
+ matches = coll.dir("Thoracic")
+ assert "CervicoThoracicSpine" in matches
+ assert "IntraThoracic" in matches
+ assert "StructureOfDescendingThoracicAorta" in matches
+ assert "ThoracicSpine" in matches
+
+ # Check None_
+ coll = Collection("CID606")
+ assert "None_" in coll
+ assert "None_" in dir(coll)
+
+ # Check _125Iodine
+ coll = Collection("CID18")
+ assert "_125Iodine" in coll
+ assert "_125Iodine" in dir(coll)
+
+ def test_getattr(self):
+ """Test Collection.Foo"""
+ coll = Collection("UCUM")
+ assert coll.Second == Code("s", scheme_designator="UCUM", meaning="second")
+ msg = "No matching code for keyword 'Foo' in scheme 'UCUM'"
+ with pytest.raises(AttributeError, match=msg):
+ coll.Foo
- def test_cid646(self):
- assert codes.cid646.SPECTCTOfWholeBody == Code(
- value="127902",
- scheme_designator="DCM",
- meaning="SPECT CT of Whole Body",
+ coll = Collection("CID2")
+ assert coll.Transverse == Code(
+ "62824007", scheme_designator="SCT", meaning="Transverse"
)
- def test_cid1003(self):
- assert codes.cid1003.LevelOfT11T12IntervertebralDisc == Code(
- value="243918001",
- scheme_designator="SCT",
- meaning="Level of T11/T12 intervertebral disc",
- )
+ msg = "No matching code for keyword 'Foo' in CID2"
+ with pytest.raises(AttributeError, match=msg):
+ coll.Foo
- def test_cid3000(self):
- assert codes.cid3000.OperatorNarrative == Code(
- value="109111",
- scheme_designator="DCM",
- meaning="Operator's Narrative",
- )
+ coll.foo = None
+ assert coll.foo is None
- def test_cid3001_1(self):
- assert codes.cid3001.Avr == Code(
- value="2:65", scheme_designator="MDC", meaning="-aVR"
- )
+ def test_getattr_multiple_cid(self, add_multiple_cid):
+ """Test Collection.Foo for a CID"""
+ coll = Collection("CID99999999999")
+ assert coll.Foo == Code("BAR", scheme_designator="TEST", meaning="Test A")
- def test_cid3001_2(self):
- assert codes.cid3001.NegativeLowRightScapulaLead == Code(
- value="2:124",
- scheme_designator="MDC",
- meaning="negative: low right scapula Lead",
- )
+ def test_getattr_multiple_raises(self, add_nonunique):
+ """Test non-unique results for the keyword"""
+ coll = Collection("TEST")
+ msg = "Multiple codes found for keyword 'Foo' in scheme 'TEST': BAR, BAZ"
+ with pytest.raises(RuntimeError, match=msg):
+ coll.Foo
- def test_cid3107(self):
- assert codes.cid3107._13Nitrogen == Code(
- value="21576001", scheme_designator="SCT", meaning="^13^Nitrogen"
- )
+ def test_getattr_multiple_raises_cid(self, add_nonunique_cid):
+ """Test non-unique results for the keyword"""
+ coll = Collection("CID99999999999")
+ msg = "Multiple codes found for keyword 'Foo' in CID99999999999: BAR, BAZ"
+ with pytest.raises(RuntimeError, match=msg):
+ coll.Foo
- def test_cid3111(self):
- assert codes.cid3111.Tc99mTetrofosmin == Code(
- value="424118002",
- scheme_designator="SCT",
- meaning="Tc-99m tetrofosmin",
+ coll._cid_data["TEST2"] = ["Foo"]
+ msg = (
+ "Multiple schemes found to contain the keyword 'Foo' in CID99999999999: "
+ "TEST, TEST2"
)
+ with pytest.raises(RuntimeError, match=msg):
+ coll.Foo
- def test_cid3263(self):
- meaning = "12-lead from EASI leads (ES, AS, AI) by Dower/EASI transformation"
+ def test_repr(self):
+ """Test repr()"""
+ coll = Collection("UCUM")
assert (
- codes.cid3263._12LeadFromEASILeadsESASAIByDowerEASITransformation
- == Code(
- value="10:11284",
- scheme_designator="MDC",
- meaning=meaning,
- )
- )
-
- def test_cid3335(self):
- assert codes.cid3335.PWaveSecondDeflectionInPWave == Code(
- value="10:320",
- scheme_designator="MDC",
- meaning="P' wave (second deflection in P wave)",
- )
-
- def test_contained(self):
- c = Code("24028007", "SCT", "Right")
- assert c in codes.cid244
+ "Second = Code(value='s', scheme_designator='UCUM', meaning='second', "
+ "scheme_version=None)"
+ ) in repr(coll)
- def test_not_contained(self):
- c = Code("130290", "DCM", "Median")
- assert c not in codes.cid244
+ coll = Collection("CID2")
+ assert (
+ "Transverse = Code(value='62824007', scheme_designator='SCT', "
+ "meaning='Transverse', scheme_version=None)"
+ ) in repr(coll)
- def test_dunder_dir(self):
- d = _CodesDict("UCUM")
- assert "ArbitraryUnit" in dir(d)
- assert "Year" in dir(d)
- assert "__delattr__" in dir(d)
- assert "trait_names" in dir(d)
- assert isinstance(dir(d), list)
+ def test_str(self):
+ """Test str()"""
+ coll = Collection("UCUM")
+ assert (
+ "Second s "
+ " second\n"
+ ) in str(coll)
- def test_dir(self):
- d = _CodesDict("UCUM")
- assert isinstance(d.dir(), list)
- assert "ArbitraryUnit" in d.dir()
- assert "Year" in d.dir()
- assert d.dir("xyz") == []
- assert "Radian" in d.dir("ia")
-
- def test_schemes(self):
- d = _CodesDict("UCUM")
- assert "UCUM" in list(d.schemes())
- schemes = list(codes.schemes())
- assert "UCUM" in schemes
- assert "DCM" in schemes
- assert "SCT" in schemes
+ coll = Collection("CID2")
+ assert "Transverse 62824007 SCT Transverse\n" in str(coll)
def test_trait_names(self):
- d = _CodesDict("UCUM")
- assert "ArbitraryUnit" in d.trait_names()
- assert "Year" in d.trait_names()
- assert "__delattr__" in d.trait_names()
- assert "trait_names" in d.trait_names()
-
- def test_getattr_CID_with_scheme_raises(self):
- msg = "Cannot use a CID with a scheme dictionary"
- with pytest.raises(AttributeError, match=msg):
- _CodesDict("UCUM").cid2
-
- def test_getattr_unknown_attr_raises(self):
- msg = "Unknown code name 'bar' for scheme 'UCUM'"
- with pytest.raises(AttributeError, match=msg):
- _CodesDict("UCUM").bar
-
- def test_getattr_nonunique_attr_raises(self, add_nonunique):
- msg = "Multiple code values for 'Foo' found: BAR, BAZ"
- with pytest.raises(RuntimeError, match=msg):
- _CodesDict("TEST").Foo
+ """Test trait_names()"""
+ traits = Collection("UCUM").trait_names()
+ assert "Second" in traits
+ assert "Foo" not in traits
+ traits = Collection("CID2").trait_names()
+ assert "Transverse" in traits
+ assert "Foo" not in traits
-class TestCIDDict:
- def test_concepts(self):
- d = _CID_Dict(2)
- assert "Afferent" in d.concepts
- code = d.concepts["Afferent"]
- assert isinstance(code, Code)
- assert code.value == "49530007"
-
- def test_dunder_dir(self):
- d = _CID_Dict(2)
- assert "Afferent" in dir(d)
- assert "Vertical" in dir(d)
- assert "__contains__" in dir(d)
- assert "trait_names" in dir(d)
- assert isinstance(dir(d), list)
- def test_dir(self):
- d = _CID_Dict(2)
- assert isinstance(d.dir(), list)
- assert "Afferent" in d.dir()
- assert "Vertical" in d.dir()
+class TestConcepts:
+ """Tests for Concepts"""
- assert d.dir("xyz") == []
- assert "Axial" in d.dir("ia")
- assert "Superficial" in d.dir("ia")
- assert "Axial" in d.dir("IA")
- assert "Superficial" in d.dir("IA")
+ def test_init(self):
+ """Test creating a new instance"""
+ colls = Concepts([Collection("SCT"), Collection("CID2")])
- def test_trait_names(self):
- d = _CID_Dict(2)
- assert isinstance(d.trait_names(), list)
- assert "Afferent" in d.trait_names()
- assert "Vertical" in d.trait_names()
+ assert list(colls.collections) == ["SCT", "CID2"]
+ assert colls.schemes() == ["SCT"]
+ assert colls.CIDs() == ["CID2"]
- def test_str(self):
- d = _CID_Dict(2)
- s = str(d)
- assert "CID 2 (AnatomicModifier)" in s
- assert "Afferent 49530007 SCT Afferent" in s
- assert "Vertical 33096000 SCT Vertical" in s
+ def test_getattr(self):
+ """Test Concepts.Foo"""
+ colls = Concepts([Collection("SCT"), Collection("CID2")])
- def test_repr(self):
- d = _CID_Dict(2)
- r = repr(d)
- assert "CID 2" in r
- assert "Afferent = Code(value='49530007'" in r
- assert "Vertical = Code(value='33096000'" in r
-
- def test_getattr_match(self):
- d = _CID_Dict(2)
- code = d.Afferent
- assert isinstance(code, Code)
- assert code.value == "49530007"
-
- def test_getattr_no_match_raises(self):
- d = _CID_Dict(2)
- msg = r"'XYZ' not found in CID 2"
- with pytest.raises(AttributeError, match=msg):
- d.XYZ
+ assert isinstance(colls.SCT, Collection)
+ assert isinstance(colls.CID2, Collection)
- def test_getattr_match_multiple_codes_raises(self, add_nonunique_cid):
- # Same attribute for multiple codes
- d = _CID_Dict(99999999999)
- msg = r"'Foo' has multiple code matches in CID 99999999999: 'BAR', 'BAZ'"
- with pytest.raises(AttributeError, match=msg):
- d.Foo
+ colls.foo = None
+ assert colls.foo is None
- def test_getattr_ambiguous_attr_raises(self, ambiguous_scheme):
- attr, cid = ambiguous_scheme
- msg = f"Multiple schemes found for '{attr}' in CID 6129: SCT, FOO"
+ msg = "'Concepts' object has no attribute 'Foo'"
with pytest.raises(AttributeError, match=msg):
- getattr(_CID_Dict(cid), attr)
+ colls.Foo
| diff --git a/doc/reference/index.rst b/doc/reference/index.rst
index c1fd39db81..3fe27c4017 100644
--- a/doc/reference/index.rst
+++ b/doc/reference/index.rst
@@ -30,5 +30,6 @@ This API reference guide details the functions, modules and objects included in
misc
overlays
pixels
+ sr
waveforms
uid
diff --git a/doc/reference/sr.rst b/doc/reference/sr.rst
new file mode 100644
index 0000000000..98015398a7
--- /dev/null
+++ b/doc/reference/sr.rst
@@ -0,0 +1,35 @@
+
+Concepts and Context Groups (:mod:`pydicom.sr`)
+===============================================
+
+.. module:: pydicom.sr
+.. currentmodule:: pydicom.sr
+
+The ``sr`` module contains an interface for DICOM's :dcm:`CIDs<part16/chapter_B.html>`.
+
+
+.. autosummary::
+ :toctree: generated/
+
+ Collection
+ Concepts
+ Code
+
+
+Usage
+-----
+
+Individual :class:`~pydicom.sr.coding.Code` values can be accessed via either
+their scheme (such as SCT) or the DICOM CID::
+
+ >>> from pydicom.sr import codes
+ >>> codes.SCT.Transverse
+ Code(value='62824007', scheme_designator='SCT', meaning='Transverse', scheme_version=None)
+ >>> codes.CID4.Cornea
+ Code(value='28726007', scheme_designator='SCT', meaning='Cornea', scheme_version=None)
+
+A list of available attribute keywords for each scheme or CID is available via
+:meth:`~pydicom.sr.Collection.dir`::
+
+ >>> dir(codes.CID6)
+ ['Coronal', 'FiveChamber', 'FourChamber', ... ]
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index ba491a6aa6..0e284dffb4 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -208,7 +208,9 @@ Enhancements
(if present, although it's non-conformant for it to be) (:issue:`2073`)
* Added support for NumPy v2.0 (:issue:`2075`)
* Added ``pydicom.__concepts_version__`` attribute with the DICOM Standard version used to
- create the concepts dictionaries in ``pydicom.sr`` (:issue:`1021`)
+ create the concepts dictionaries in :mod:`pydicom.sr` (:issue:`1021`)
+* Refactored the interface for the concepts in :mod:`pydicom.sr` to simplify the access types
+ (:issue:`1454`)
Fixes
| [
{
"components": [
{
"doc": "Interface for a collection of concepts, such as SNOMED-CT, or a DICOM CID.\n\n.. versionadded:: 3.0",
"lines": [
51,
292
],
"name": "Collection",
"signature": "class Collection:",
"type": "class"
},
... | [
"tests/test_codes.py::TestCode::test_construction_kwargs",
"tests/test_codes.py::TestCode::test_use_as_dictionary_key",
"tests/test_codes.py::TestCode::test_construction_kwargs_optional",
"tests/test_codes.py::TestCode::test_construction_args",
"tests/test_codes.py::TestCode::test_construction_args_optional... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
[MRG] Refactor concepts interface
#### Describe the changes
* Refactors the `pydicom.sr` interface to simplify the access types and to make public
* Adds `sr` module to reference API docs
Closes #1454
#### Tasks
- [x] Unit tests added that reproduce the issue or prove feature is working
- [x] Fix or feature added
- [x] Code typed and mypy shows no errors
- [x] Documentation updated (if relevant)
- [x] [Preview link](https://output.circle-artifacts.com/output/job/aef0a300-0384-4417-ae35-b59da04f7c88/artifacts/0/doc/_build/html/index.html)
- [x] Unit tests passing and overall coverage the same or better
----------
</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/pydicom/sr/codedict.py]
(definition of Collection:)
class Collection:
"""Interface for a collection of concepts, such as SNOMED-CT, or a DICOM CID.
.. versionadded:: 3.0"""
(definition of Collection.__init__:)
def __init__(self, name: str) -> None:
"""Create a new collection.
Parameters
----------
name : str
The name of the collection, should either be a key in the
``sr._concepts_dict.concepts`` :class:`dict` or a CID name for
a CID in ``sr._cid_dict.cid_concepts`` such as ``"CID1234"``."""
(definition of Collection.concepts:)
def concepts(self) -> dict[str, Code]:
"""Return a :class:`dict` of {SR identifiers: codes}"""
(definition of Collection.__contains__:)
def __contains__(self, item: str | Code) -> bool:
"""Checks whether a given code is a member of the collection.
Parameters
----------
item : pydicom.sr.coding.Code | str
The code to check for as either the code or the corresponding
keyword.
Returns
-------
bool
Whether the collection contains the `code`"""
(definition of Collection.__dir__:)
def __dir__(self) -> list[str]:
"""Return a list of available concept keywords.
List of attributes is used, for example, in auto-completion in editors
or command-line environments."""
(definition of Collection.dir:)
def dir(self, *filters: str) -> list[str]:
"""Return an sorted list of concept keywords based on a partial match.
Parameters
----------
filters : str
Zero or more string arguments to the function. Used for
case-insensitive match to any part of the SR keyword.
Returns
-------
list of str
The matching keywords. If no `filters` are used then all
keywords are returned."""
(definition of Collection.__getattr__:)
def __getattr__(self, name: str) -> Code:
"""Return the :class:`~pydicom.sr.Code` corresponding to `name`.
Parameters
----------
name : str
A camel case version of the concept's code meaning, such as
``"FontanelOfSkull" in the SCT coding scheme.
Returns
-------
pydicom.sr.Code
The :class:`~pydicom.sr.Code` corresponding to `name`."""
(definition of Collection.is_cid:)
def is_cid(self) -> bool:
"""Return ``True`` if the collection is one of the DICOM CIDs"""
(definition of Collection.name:)
def name(self) -> str:
"""Return the name of the collection."""
(definition of Collection.__repr__:)
def __repr__(self) -> str:
"""Return a representation of the collection."""
(definition of Collection.scheme_designator:)
def scheme_designator(self) -> str:
"""Return the scheme designator for the collection."""
(definition of Collection.__str__:)
def __str__(self) -> str:
"""Return a string representation of the collection."""
(definition of Collection.trait_names:)
def trait_names(self) -> list[str]:
"""Return a list of valid names for auto-completion code.
Used in IPython, so that data element names can be found and offered
for autocompletion on the IPython command line."""
(definition of Concepts:)
class Concepts:
"""Management class for the available concept collections.
.. versionadded:: 3.0"""
(definition of Concepts.__init__:)
def __init__(self, collections: list[Collection]) -> None:
"""Create a new concepts management class instance.
Parameters
----------
collections : list[Collection]
A list of the available concept collections."""
(definition of Concepts.collections:)
def collections(self) -> KeysView[str]:
"""Return the names of the available concept collections."""
(definition of Concepts.__getattr__:)
def __getattr__(self, name: str) -> Any:
"""Return the concept collection corresponding to `name`.
Parameters
----------
name : str
The scheme designator or CID name for the collection to be returned."""
(definition of Concepts.schemes:)
def schemes(self) -> list[str]:
"""Return a list of available scheme designations."""
(definition of Concepts.CIDs:)
def CIDs(self) -> list[str]:
"""Return a list of available CID names."""
[end of new definitions in src/pydicom/sr/codedict.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>
Mypy: Item "Code" of "Union[_CodesDict, _CID_Dict, Code]" has no attribute "XXX"
When running *mypy* on the codes provided via `pydicom.sr.codedict.codes`, I get the following error:
```None
mypy -c 'from pydicom.sr.codedict import codes; codes.SCT.Tissue'
<string>:1: error: Item "Code" of "Union[_CodesDict, _CID_Dict, Code]" has no attribute "Tissue"
```
Since the attributes are dynamically fetched from the underlying dict via [_CodesDict.__getattr__()](https://github.com/pydicom/pydicom/blob/8da0b9b215ebfad5756051c891def88e426787e7/pydicom/sr/codedict.py#L78), *mypy* doesn't know about the individual attributes.
In addition, the type annotation `Union[_CodesDict, _CID_Dict, Code]` causes several other issues in application code. I tend argue that the type of `codes.SCT.Tissue` should just be `Code` rather than a complex `Union`.
Related to #1251.
----------
The return type is correct, that method is really dynamic, unfortunately. It's probably a sign that it needs to be refactored.
```python
>>> from pydicom.sr import codes
>>> type(codes)
<class 'pydicom.sr.codedict._CodesDict'>
>>> type(codes.SCT)
<class 'pydicom.sr.codedict._CodesDict'>
>>> type(codes.SCT.Tissue)
<class 'pydicom.sr.coding.Code'>
>>> type(codes.cid2)
<class 'pydicom.sr.codedict._CID_Dict'>
```
You should cast (or ignore).
```python
from pydicom.sr import codes
from pydicom.sr.codedict import _CodesDict
from typing import cast
code = cast(_CodesDict, codes.SCT).Tissue
```
Thanks for your feedback @scaramallion. We are using this abstraction very frequently in *highdicom* and I don't consider casting or ignoring viable options. The cast is quite ugly and really defeats the purpose of having this nice abstraction in the first place. Ignoring is a) not ideal and b) doesn't solve the problem entirely, because the `Union` type is viral and affects other calls downstream, where `Union[Code, ...]` is expected.
I think we should refactor this and generally avoid return values of `Union` type. Would it make sense to implement a different class for each hierarchical "level" (`_CodesDict`, `_CID_Dict`, `Code`) so that each `__getattr__` would return a value of the appropriate type?
> Would it make sense to implement a different class for each hierarchical "level"
Yeah, I think so. They could probably be "public" classes, too.
Assigning this to pydicom v3.0, where the plan is to drop Python versions and therefore have access to better `typing` syntax and types.
--------------------
</issues> | f57c7aceaeda48b60ef3d66fdb875db61e5b49a8 |
deepset-ai__haystack-7915 | 7,915 | deepset-ai/haystack | null | fc011d7b04109c0ae4563b4db639cc63c78ebcf7 | 2024-06-23T15:38:27Z | diff --git a/haystack/components/joiners/document_joiner.py b/haystack/components/joiners/document_joiner.py
index 6c02c1ffa9..6e1e5a803b 100644
--- a/haystack/components/joiners/document_joiner.py
+++ b/haystack/components/joiners/document_joiner.py
@@ -22,6 +22,7 @@ class DocumentJoiner:
- concatenate: Keeps the highest scored Document in case of duplicates.
- merge: Merge a calculate a weighted sum of the scores of duplicate Documents.
- reciprocal_rank_fusion: Merge and assign scores based on reciprocal rank fusion.
+ - distribution_based_rank_fusion: Merge and assign scores based on scores distribution in each retriever
Usage example:
```python
@@ -57,16 +58,17 @@ def __init__(
- `concatenate`
- `merge`
- `reciprocal_rank_fusion`
+ - `distribution_based_rank_fusion`
:param weights:
Weight for each list of Documents received, must have the same length as the number of inputs.
- If `join_mode` is `concatenate` this parameter is ignored.
+ If `join_mode` is `concatenate` or `distribution_based_rank_fusion` this parameter is ignored.
:param top_k:
The maximum number of Documents to return.
:param sort_by_score:
If True sorts the Documents by score in descending order.
If a Document has no score, it is handled as if its score is -infinity.
"""
- if join_mode not in ["concatenate", "merge", "reciprocal_rank_fusion"]:
+ if join_mode not in ["concatenate", "merge", "reciprocal_rank_fusion", "distribution_based_rank_fusion"]:
raise ValueError(f"DocumentJoiner component does not support '{join_mode}' join_mode.")
self.join_mode = join_mode
self.weights = [float(i) / sum(weights) for i in weights] if weights else None
@@ -88,12 +90,16 @@ def run(self, documents: Variadic[List[Document]], top_k: Optional[int] = None):
- `documents`: Merged list of Documents
"""
output_documents = []
+
+ documents = list(documents)
if self.join_mode == "concatenate":
output_documents = self._concatenate(documents)
elif self.join_mode == "merge":
output_documents = self._merge(documents)
elif self.join_mode == "reciprocal_rank_fusion":
output_documents = self._reciprocal_rank_fusion(documents)
+ elif self.join_mode == "distribution_based_rank_fusion":
+ output_documents = self._distribution_based_rank_fusion(documents)
if self.sort_by_score:
output_documents = sorted(
@@ -112,7 +118,7 @@ def run(self, documents: Variadic[List[Document]], top_k: Optional[int] = None):
return {"documents": output_documents}
- def _concatenate(self, document_lists):
+ def _concatenate(self, document_lists: List[List[Document]]) -> List[Document]:
"""
Concatenate multiple lists of Documents and return only the Document with the highest score for duplicates.
"""
@@ -125,11 +131,11 @@ def _concatenate(self, document_lists):
output.append(doc_with_best_score)
return output
- def _merge(self, document_lists):
+ def _merge(self, document_lists: List[List[Document]]) -> List[Document]:
"""
Merge multiple lists of Documents and calculate a weighted sum of the scores of duplicate Documents.
"""
- scores_map = defaultdict(int)
+ scores_map: dict = defaultdict(int)
documents_map = {}
weights = self.weights if self.weights else [1 / len(document_lists)] * len(document_lists)
@@ -141,9 +147,9 @@ def _merge(self, document_lists):
for doc in documents_map.values():
doc.score = scores_map[doc.id]
- return documents_map.values()
+ return list(documents_map.values())
- def _reciprocal_rank_fusion(self, document_lists):
+ def _reciprocal_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]:
"""
Merge multiple lists of Documents and assign scores based on reciprocal rank fusion.
@@ -152,7 +158,7 @@ def _reciprocal_rank_fusion(self, document_lists):
"""
k = 61
- scores_map = defaultdict(int)
+ scores_map: dict = defaultdict(int)
documents_map = {}
weights = self.weights if self.weights else [1 / len(document_lists)] * len(document_lists)
@@ -170,4 +176,29 @@ def _reciprocal_rank_fusion(self, document_lists):
for doc in documents_map.values():
doc.score = scores_map[doc.id]
- return documents_map.values()
+ return list(documents_map.values())
+
+ def _distribution_based_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]:
+ """
+ Merge multiple lists of Documents and assign scores based on Distribution-Based Score Fusion.
+
+ (https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18)
+ If a Document is in more than one retriever, the one with the highest score is used.
+ """
+ for documents in document_lists:
+ scores_list = []
+
+ for doc in documents:
+ scores_list.append(doc.score if doc.score is not None else 0)
+
+ mean_score = sum(scores_list) / len(scores_list)
+ std_dev = (sum((x - mean_score) ** 2 for x in scores_list) / len(scores_list)) ** 0.5
+ min_score = mean_score - 3 * std_dev
+ max_score = mean_score + 3 * std_dev
+
+ for doc in documents:
+ doc.score = (doc.score - min_score) / (max_score - min_score)
+
+ output = self._concatenate(document_lists=document_lists)
+
+ return output
diff --git a/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml b/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml
new file mode 100644
index 0000000000..e7bb46a8a5
--- /dev/null
+++ b/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml
@@ -0,0 +1,6 @@
+---
+features:
+ - |
+ Added a new mode in JoinDocuments,
+ Distribution-based rank fusion as
+ [the article](https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18)
| diff --git a/test/components/joiners/test_document_joiner.py b/test/components/joiners/test_document_joiner.py
index 48fa5b2302..41fe275541 100644
--- a/test/components/joiners/test_document_joiner.py
+++ b/test/components/joiners/test_document_joiner.py
@@ -115,6 +115,36 @@ def test_run_with_reciprocal_rank_fusion_join_mode(self):
]
assert all(doc.id in expected_document_ids for doc in output["documents"])
+ def test_run_with_distribution_based_rank_fusion_join_mode(self):
+ joiner = DocumentJoiner(join_mode="distribution_based_rank_fusion")
+ documents_1 = [
+ Document(content="a", score=0.6),
+ Document(content="b", score=0.2),
+ Document(content="c", score=0.5),
+ ]
+ documents_2 = [
+ Document(content="d", score=0.5),
+ Document(content="e", score=0.8),
+ Document(content="f", score=1.1, meta={"key": "value"}),
+ Document(content="g", score=0.3),
+ Document(content="a", score=0.3),
+ ]
+ output = joiner.run([documents_1, documents_2])
+ assert len(output["documents"]) == 7
+ expected_document_ids = [
+ doc.id
+ for doc in [
+ Document(content="a", score=0.66),
+ Document(content="b", score=0.27),
+ Document(content="c", score=0.56),
+ Document(content="d", score=0.44),
+ Document(content="e", score=0.60),
+ Document(content="f", score=0.76, meta={"key": "value"}),
+ Document(content="g", score=0.33),
+ ]
+ ]
+ assert all(doc.id in expected_document_ids for doc in output["documents"])
+
def test_run_with_top_k_in_run_method(self):
joiner = DocumentJoiner()
documents_1 = [Document(content="a"), Document(content="b"), Document(content="c")]
| diff --git a/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml b/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml
new file mode 100644
index 0000000000..e7bb46a8a5
--- /dev/null
+++ b/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml
@@ -0,0 +1,6 @@
+---
+features:
+ - |
+ Added a new mode in JoinDocuments,
+ Distribution-based rank fusion as
+ [the article](https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18)
| [
{
"components": [
{
"doc": "Merge multiple lists of Documents and assign scores based on Distribution-Based Score Fusion.\n\n(https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18)\nIf a Document is in more than one retri... | [
"test/components/joiners/test_document_joiner.py::TestDocumentJoiner::test_run_with_distribution_based_rank_fusion_join_mode"
] | [
"[",
"test/components/joiners/test_document_joiner.py::TestDocumentJoiner::test_init",
"test/components/joiners/test_document_joiner.py::TestDocumentJoiner::test_init_with_custom_parameters",
"test/components/joiners/test_document_joiner.py::TestDocumentJoiner::test_empty_list",
"test/components/joiners/tes... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add Distribution based rank fusion mode
### Related Issues
- fixes #7914
### Proposed Changes:
How it works:
```
from haystack import Document
from haystack.components.joiners.document_joiner import DocumentJoiner
joiner = DocumentJoiner(join_mode="distribution_based_rank_fusion")
documents_1 = [
Document(content="a", score=0.6),
Document(content="b", score=0.2),
Document(content="c", score=0.5),
]
documents_2 = [
Document(content="d", score=0.5),
Document(content="e", score=0.8),
Document(content="f", score=1.1, meta={"key": "value"}),
Document(content="g", score=0.3),
Document(content="a", score=0.3),
]
output = joiner.run([documents_1, documents_2])
# output
# [
# Document(content="a", score=0.66),
# Document(content="b", score=0.27),
# Document(content="c", score=0.56),
# Document(content="d", score=0.44),
# Document(content="e", score=0.60),
# Document(content="f", score=0.76, meta={"key": "value"}),
# Document(content="g", score=0.33),
# ]
```
### How did you test it?
unit 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/joiners/document_joiner.py]
(definition of DocumentJoiner._distribution_based_rank_fusion:)
def _distribution_based_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]:
"""Merge multiple lists of Documents and assign scores based on Distribution-Based Score Fusion.
(https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18)
If a Document is in more than one retriever, the one with the highest score is used."""
[end of new definitions in haystack/components/joiners/document_joiner.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 Distribution-based rank fusion in JoinDocuments
**Is your feature request related to a problem? Please describe.**
Add [Distribution-based rank fusion](https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18) in JoinDocuments
**Describe the solution you'd like**
```
def _distribution_based_rank_fusion(self, document_lists):
"""
Merge multiple lists of Documents and assign scores based on Distribution-Based Score Fusion.
(https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18)
If a Document is in more than one retriever, the sone with the highest score is used.
"""
for documents in document_lists:
scores_list = []
for doc in documents:
scores_list.append(doc.score)
mean_score = sum(scores_list) / len(scores_list)
std_dev = (
sum((x - mean_score) ** 2 for x in scores_list) / len(scores_list)
) ** 0.5
min_score = mean_score - 3 * std_dev
max_score = mean_score + 3 * std_dev
for doc in documents:
doc.score = (doc.score - min_score) / (max_score - min_score)
output = self._concatenate(document_lists=document_lists)
return output
```
----------
--------------------
</issues> | f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967 |
googleapis__python-aiplatform-3982 | 3,982 | googleapis/python-aiplatform | null | a90ee8da161f95aa489aa4f09309a3fa34320a4c | 2024-06-21T03:56:54Z | diff --git a/samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management.py b/samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management.py
new file mode 100644
index 0000000000..ae92ca5855
--- /dev/null
+++ b/samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management.py
@@ -0,0 +1,53 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+# [START aiplatform_sdk_create_feature_view_from_bq_source_with_embedding_management]
+
+from google.cloud import aiplatform
+from vertexai.resources.preview import feature_store
+from typing import List
+
+
+def create_feature_view_from_bq_source_with_embedding_management(
+ project: str,
+ location: str,
+ existing_feature_online_store_id: str,
+ feature_view_id: str,
+ bq_table_uri: str,
+ entity_id_columns: List[str],
+ embedding_column: str,
+ embedding_dimensions: str,
+):
+ aiplatform.init(project=project, location=location)
+
+ fos = feature_store.FeatureOnlineStore(existing_feature_online_store_id)
+
+ bigquery_source = feature_store.utils.FeatureViewBigQuerySource(
+ uri=bq_table_uri,
+ entity_id_columns=entity_id_columns,
+ )
+ index_config = feature_store.utils.IndexConfig(
+ embedding_column=embedding_column,
+ dimensions=embedding_dimensions,
+ algorithm_config=feature_store.utils.TreeAhConfig(),
+ )
+ fv = fos.create_feature_view(
+ name=feature_view_id,
+ source=bigquery_source,
+ index_config=index_config,
+ )
+ return fv
+
+
+# [END aiplatform_sdk_create_feature_view_from_bq_source_with_embedding_management]
| diff --git a/samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management_test.py b/samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management_test.py
new file mode 100644
index 0000000000..71565bcbdd
--- /dev/null
+++ b/samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management_test.py
@@ -0,0 +1,43 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+from feature_store import create_feature_view_from_bq_source_with_embedding_management
+import test_constants as constants
+
+
+def test_create_feature_view_from_bq_source_with_embedding_management(
+ mock_sdk_init,
+ mock_get_feature_online_store,
+):
+ create_feature_view_from_bq_source_with_embedding_management.create_feature_view_from_bq_source_with_embedding_management(
+ project=constants.PROJECT,
+ location=constants.LOCATION,
+ existing_feature_online_store_id=constants.FEATURE_ONLINE_STORE_ID,
+ feature_view_id=constants.FEATURE_VIEW_ID,
+ bq_table_uri=constants.FEATURE_VIEW_BQ_URI,
+ entity_id_columns=constants.FEATURE_VIEW_BQ_ENTITY_ID_COLUMNS,
+ embedding_column=constants.FEATURE_VIEW_BQ_EMBEDDING_COLUMN,
+ embedding_dimensions=constants.FEATURE_VIEW_BQ_EMBEDDING_DIMENSIONS,
+ )
+
+ mock_sdk_init.assert_called_once_with(
+ project=constants.PROJECT, location=constants.LOCATION
+ )
+
+ mock_get_feature_online_store.assert_called_once()
+ mock_get_feature_online_store.return_value.create_feature_view.assert_called_once_with(
+ name=constants.FEATURE_VIEW_ID,
+ source=constants.FEATURE_VIEW_BQ_SOURCE,
+ index_config=constants.FEATURE_VIEW_BQ_INDEX_CONFIG,
+ )
diff --git a/samples/model-builder/test_constants.py b/samples/model-builder/test_constants.py
index 0309691606..fd32f29f48 100644
--- a/samples/model-builder/test_constants.py
+++ b/samples/model-builder/test_constants.py
@@ -264,6 +264,15 @@
entity_id_columns=FEATURE_VIEW_BQ_ENTITY_ID_COLUMNS,
)
)
+FEATURE_VIEW_BQ_EMBEDDING_COLUMN = "embedding"
+FEATURE_VIEW_BQ_EMBEDDING_DIMENSIONS = 10
+FEATURE_VIEW_BQ_INDEX_CONFIG = (
+ vertexai.resources.preview.feature_store.utils.IndexConfig(
+ embedding_column=FEATURE_VIEW_BQ_EMBEDDING_COLUMN,
+ dimensions=FEATURE_VIEW_BQ_EMBEDDING_DIMENSIONS,
+ algorithm_config=vertexai.resources.preview.feature_store.utils.TreeAhConfig(),
+ )
+)
FEATURE_GROUP_ID = "sample_feature_group"
PROJECT_ALLOWLISTED = ["test-project"]
| [
{
"components": [
{
"doc": "",
"lines": [
22,
50
],
"name": "create_feature_view_from_bq_source_with_embedding_management",
"signature": "def create_feature_view_from_bq_source_with_embedding_management( project: str, location: str, existing_feat... | [
"samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management_test.py::test_create_feature_view_from_bq_source_with_embedding_management"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
chore: feature store code sample - feature view from BQ source w/embedding management
chore: feature store code sample - feature view from BQ source w/embedding management
----------
</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/feature_store/create_feature_view_from_bq_source_with_embedding_management.py]
(definition of create_feature_view_from_bq_source_with_embedding_management:)
def create_feature_view_from_bq_source_with_embedding_management( project: str, location: str, existing_feature_online_store_id: str, feature_view_id: str, bq_table_uri: str, entity_id_columns: List[str], embedding_column: str, embedding_dimensions: str, ):
[end of new definitions in samples/model-builder/feature_store/create_feature_view_from_bq_source_with_embedding_management.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 | ||
googleapis__python-aiplatform-3979 | 3,979 | googleapis/python-aiplatform | null | 3e3671fca1d456661019038caf9e74ad1d68c3d3 | 2024-06-20T21:47:46Z | diff --git a/samples/model-builder/feature_store/create_feature_view_from_bq_source.py b/samples/model-builder/feature_store/create_feature_view_from_bq_source.py
new file mode 100644
index 0000000000..55122c6ec4
--- /dev/null
+++ b/samples/model-builder/feature_store/create_feature_view_from_bq_source.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+# [START aiplatform_sdk_create_feature_view_from_bq_source]
+
+from google.cloud import aiplatform
+from vertexai.resources.preview import feature_store
+from typing import List
+
+
+def create_feature_view_from_bq_source(
+ project: str,
+ location: str,
+ existing_feature_online_store_id: str,
+ feature_view_id: str,
+ bq_table_uri: str,
+ entity_id_columns: List[str],
+):
+ aiplatform.init(project=project, location=location)
+ fos = feature_store.FeatureOnlineStore(existing_feature_online_store_id)
+ fv = fos.create_feature_view(
+ name=feature_view_id,
+ source=feature_store.utils.FeatureViewBigQuerySource(
+ uri=bq_table_uri, entity_id_columns=entity_id_columns
+ ),
+ )
+ return fv
+
+
+# [END aiplatform_sdk_create_feature_view_from_bq_source]
| diff --git a/samples/model-builder/conftest.py b/samples/model-builder/conftest.py
index 55facdb363..c49a76a491 100644
--- a/samples/model-builder/conftest.py
+++ b/samples/model-builder/conftest.py
@@ -740,6 +740,15 @@ def mock_create_optimized_private_online_store(mock_feature_online_store):
yield mock_create_optimized_store
+@pytest.fixture
+def mock_get_feature_online_store(mock_feature_online_store):
+ with patch.object(
+ preview_resources.FeatureOnlineStore, "__new__"
+ ) as mock_get_feature_online_store:
+ mock_get_feature_online_store.return_value = mock_feature_online_store
+ yield mock_get_feature_online_store
+
+
"""
----------------------------------------------------------------------------
Experiment Tracking Fixtures
diff --git a/samples/model-builder/feature_store/create_feature_view_from_bq_source_test.py b/samples/model-builder/feature_store/create_feature_view_from_bq_source_test.py
new file mode 100644
index 0000000000..83bd175193
--- /dev/null
+++ b/samples/model-builder/feature_store/create_feature_view_from_bq_source_test.py
@@ -0,0 +1,40 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+from feature_store import create_feature_view_from_bq_source
+import test_constants as constants
+
+
+def test_create_feature_view_from_bq_source_sample(
+ mock_sdk_init,
+ mock_get_feature_online_store,
+):
+ create_feature_view_from_bq_source.create_feature_view_from_bq_source(
+ project=constants.PROJECT,
+ location=constants.LOCATION,
+ existing_feature_online_store_id=constants.FEATURE_ONLINE_STORE_ID,
+ feature_view_id=constants.FEATURE_VIEW_ID,
+ bq_table_uri=constants.FEATURE_VIEW_BQ_URI,
+ entity_id_columns=constants.FEATURE_VIEW_BQ_ENTITY_ID_COLUMNS,
+ )
+
+ mock_sdk_init.assert_called_once_with(
+ project=constants.PROJECT, location=constants.LOCATION
+ )
+
+ mock_get_feature_online_store.assert_called_once()
+ mock_get_feature_online_store.return_value.create_feature_view.assert_called_once_with(
+ name=constants.FEATURE_VIEW_ID,
+ source=constants.FEATURE_VIEW_BQ_SOURCE,
+ )
diff --git a/samples/model-builder/test_constants.py b/samples/model-builder/test_constants.py
index e17baa43a1..0309691606 100644
--- a/samples/model-builder/test_constants.py
+++ b/samples/model-builder/test_constants.py
@@ -18,6 +18,7 @@
from google.protobuf import timestamp_pb2
from google.auth import credentials
from google.cloud import aiplatform
+import vertexai
PROJECT = "abc"
LOCATION = "us-central1"
@@ -254,6 +255,15 @@
# Feature online store constants
FEATURE_ONLINE_STORE_ID = "sample_feature_online_store"
+FEATURE_VIEW_ID = "sample_feature_view"
+FEATURE_VIEW_BQ_URI = "bq://my_proj.my_dataset.my_table"
+FEATURE_VIEW_BQ_ENTITY_ID_COLUMNS = ["id"]
+FEATURE_VIEW_BQ_SOURCE = (
+ vertexai.resources.preview.feature_store.utils.FeatureViewBigQuerySource(
+ uri=FEATURE_VIEW_BQ_URI,
+ entity_id_columns=FEATURE_VIEW_BQ_ENTITY_ID_COLUMNS,
+ )
+)
FEATURE_GROUP_ID = "sample_feature_group"
PROJECT_ALLOWLISTED = ["test-project"]
| [
{
"components": [
{
"doc": "",
"lines": [
22,
38
],
"name": "create_feature_view_from_bq_source",
"signature": "def create_feature_view_from_bq_source( project: str, location: str, existing_feature_online_store_id: str, feature_view_id: str, bq_t... | [
"samples/model-builder/feature_store/create_feature_view_from_bq_source_test.py::test_create_feature_view_from_bq_source_sample"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
chore: feature store code sample - feature view from BQ source
chore: feature store code sample - feature view from BQ source
----------
</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/feature_store/create_feature_view_from_bq_source.py]
(definition of create_feature_view_from_bq_source:)
def create_feature_view_from_bq_source( project: str, location: str, existing_feature_online_store_id: str, feature_view_id: str, bq_table_uri: str, entity_id_columns: List[str], ):
[end of new definitions in samples/model-builder/feature_store/create_feature_view_from_bq_source.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 | ||
conan-io__conan-16511 | 16,511 | conan-io/conan | null | fed5f7f4ff8d0b003f76a161d9f9931cb3199f2e | 2024-06-20T19:06:58Z | diff --git a/conan/api/subapi/lockfile.py b/conan/api/subapi/lockfile.py
index e2d51c1f985..1d193bbcd79 100644
--- a/conan/api/subapi/lockfile.py
+++ b/conan/api/subapi/lockfile.py
@@ -64,11 +64,13 @@ def update_lockfile_export(self, lockfile, conanfile, ref, is_build_require=Fals
else:
python_requires = []
python_requires = python_requires + ([ref] if is_python_require else [])
- lockfile = self.add_lockfile(lockfile,
+ new_lock = self.add_lockfile(lockfile,
requires=[ref] if is_require else None,
python_requires=python_requires,
build_requires=[ref] if is_build_require else None)
- return lockfile
+ if lockfile is None: # If there was no lockfile, it is a partial one to lock export
+ new_lock.partial = True
+ return new_lock
@staticmethod
def update_lockfile(lockfile, graph, lock_packages=False, clean=False):
@@ -83,7 +85,6 @@ def add_lockfile(lockfile=None, requires=None, build_requires=None, python_requi
config_requires=None):
if lockfile is None:
lockfile = Lockfile() # create a new lockfile
- lockfile.partial = True
lockfile.add(requires=requires, build_requires=build_requires,
python_requires=python_requires, config_requires=config_requires)
diff --git a/conan/cli/commands/lock.py b/conan/cli/commands/lock.py
index 984661a98ae..0d7c3f3952c 100644
--- a/conan/cli/commands/lock.py
+++ b/conan/cli/commands/lock.py
@@ -11,7 +11,7 @@
@conan_command(group="Consumer")
-def lock(conan_api, parser, *args):
+def lock(conan_api, parser, *args): # noqa
"""
Create or manage lockfiles.
"""
@@ -63,7 +63,7 @@ def lock_create(conan_api, parser, subparser, *args):
@conan_subcommand()
-def lock_merge(conan_api, parser, subparser, *args):
+def lock_merge(conan_api, parser, subparser, *args): # noqa
"""
Merge 2 or more lockfiles.
"""
@@ -132,7 +132,7 @@ def _parse_requires(reqs):
@conan_subcommand()
def lock_remove(conan_api, parser, subparser, *args):
"""
- Remove requires, build-requires or python-requires from an existing or new lockfile.
+ Remove requires, build-requires or python-requires from an existing lockfile.
References can be supplied with and without revisions like "--requires=pkg/version",
"""
subparser.add_argument('--requires', action="append", help='Remove references to lockfile.')
@@ -154,3 +154,28 @@ def lock_remove(conan_api, parser, subparser, *args):
build_requires=args.build_requires,
config_requires=args.config_requires)
conan_api.lockfile.save_lockfile(lockfile, args.lockfile_out)
+
+
+@conan_subcommand()
+def lock_update(conan_api, parser, subparser, *args):
+ """
+ Update requires, build-requires or python-requires from an existing lockfile.
+ References that matches the arguments package names will be replaced by the arguments.
+ References can be supplied with and without revisions like "--requires=pkg/version",
+ """
+ subparser.add_argument('--requires', action="append", help='Update references to lockfile.')
+ subparser.add_argument('--build-requires', action="append",
+ help='Update build-requires from lockfile')
+ subparser.add_argument('--python-requires', action="append",
+ help='Update python-requires from lockfile')
+ subparser.add_argument('--config-requires', action="append",
+ help='Update config-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.update(requires=args.requires, build_requires=args.build_requires,
+ python_requires=args.python_requires, config_requires=args.config_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 29e87de77ba..999c57cc197 100644
--- a/conans/model/graph_lock.py
+++ b/conans/model/graph_lock.py
@@ -83,6 +83,21 @@ def remove(self, pattern):
self._requires = OrderedDict((k, v) for k, v in self._requires.items() if k not in remove)
return remove
+ def update(self, refs, name):
+ if not refs:
+ return
+ for r in refs:
+ r = RecipeReference.loads(r)
+ new_reqs = {}
+ for k, v in self._requires.items():
+ if r.name == k.name:
+ ConanOutput().info(f"Replacing {name}: {k.repr_notime()} -> {repr(r)}")
+ else:
+ new_reqs[k] = v
+ self._requires = new_reqs
+ self._requires[r] = None # No package-id at the moment
+ self.sort()
+
def sort(self):
self._requires = OrderedDict(reversed(sorted(self._requires.items())))
@@ -211,6 +226,12 @@ def _remove(reqs, self_reqs, name):
_remove(python_requires, self._python_requires, "python_require")
_remove(config_requires, self._conf_requires, "config_requires")
+ def update(self, requires=None, build_requires=None, python_requires=None, config_requires=None):
+ self._requires.update(requires, "require")
+ self._build_requires.update(build_requires, "build_requires")
+ self._python_requires.update(python_requires, "python_requires")
+ self._conf_requires.update(config_requires, "config_requires")
+
@staticmethod
def deserialize(data):
""" constructs a GraphLock from a json like dict
| diff --git a/test/integration/lockfile/test_user_overrides.py b/test/integration/lockfile/test_user_overrides.py
index 2f3c3c32523..601f365d519 100644
--- a/test/integration/lockfile/test_user_overrides.py
+++ b/test/integration/lockfile/test_user_overrides.py
@@ -327,3 +327,36 @@ def test_lock_remove_user_channel(self, args, removed):
"other/1.0@user", "pkg/1.0@team", "engine/1.0"}.difference(removed)
for pkg in rest:
assert pkg in lock
+
+
+class TestLockUpdate:
+ @pytest.mark.parametrize("kind, old, new", [
+ ("requires", "math/1.0", "math/1.1"),
+ ("build-requires", "cmake/1.0", "cmake/1.1"),
+ ("python-requires", "mytool/1.0", "mytool/1.1"),
+ ])
+ def test_lock_update(self, kind, old, new):
+ 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 update --{kind}={new}")
+ lock = c.load("conan.lock")
+ assert old not in lock
+ assert new in lock
| [
{
"components": [
{
"doc": "Update requires, build-requires or python-requires from an existing lockfile.\nReferences that matches the arguments package names will be replaced by the arguments.\nReferences can be supplied with and without revisions like \"--requires=pkg/version\",",
"lines... | [
"test/integration/lockfile/test_user_overrides.py::TestLockUpdate::test_lock_update[requires-math/1.0-math/1.1]",
"test/integration/lockfile/test_user_overrides.py::TestLockUpdate::test_lock_update[build-requires-cmake/1.0-cmake/1.1]",
"test/integration/lockfile/test_user_overrides.py::TestLockUpdate::test_lock... | [
"test/integration/lockfile/test_user_overrides.py::test_user_overrides",
"test/integration/lockfile/test_user_overrides.py::test_user_build_overrides",
"test/integration/lockfile/test_user_overrides.py::test_user_python_overrides",
"test/integration/lockfile/test_user_overrides.py::test_config_overrides",
"... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
new lock update subcommand
Changelog: Feature: New ``conan lock update`` subcommand to remove + add a reference in the same command.
Docs: https://github.com/conan-io/docs/pull/3784
Close https://github.com/conan-io/conan/issues/16377
----------
</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/cli/commands/lock.py]
(definition of lock_update:)
def lock_update(conan_api, parser, subparser, *args):
"""Update requires, build-requires or python-requires from an existing lockfile.
References that matches the arguments package names will be replaced by the arguments.
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.update:)
def update(self, refs, name):
(definition of Lockfile.update:)
def update(self, requires=None, build_requires=None, python_requires=None, config_requires=None):
[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 | ||
RDFLib__rdflib-2804 | 2,804 | RDFLib/rdflib | null | bb170723b21c1cfb5b90f05b541d02be53867574 | 2024-06-20T16:33:13Z | diff --git a/rdflib/plugins/parsers/jsonld.py b/rdflib/plugins/parsers/jsonld.py
index 6a5bc1103..09ef977d6 100644
--- a/rdflib/plugins/parsers/jsonld.py
+++ b/rdflib/plugins/parsers/jsonld.py
@@ -80,21 +80,61 @@ def __init__(self):
super(JsonLDParser, self).__init__()
def parse(
- self, source: InputSource, sink: Graph, version: float = 1.1, **kwargs: Any
+ self,
+ source: InputSource,
+ sink: Graph,
+ version: float = 1.1,
+ encoding: Optional[str] = "utf-8",
+ base: Optional[str] = None,
+ context: Optional[
+ Union[
+ List[Union[Dict[str, Any], str, None]],
+ Dict[str, Any],
+ str,
+ ]
+ ] = None,
+ generalized_rdf: Optional[bool] = False,
+ extract_all_scripts: Optional[bool] = False,
) -> None:
- # TODO: docstring w. args and return value
- encoding = kwargs.get("encoding") or "utf-8"
+ """Parse JSON-LD from a source document.
+
+ The source document can be JSON or HTML with embedded JSON script
+ elements (type attribute = "application/ld+json"). To process as HTML
+ ``source.content_type`` must be set to "text/html" or
+ "application/xhtml+xml".
+
+ :param source: InputSource with JSON-formatted data (JSON or HTML)
+
+ :param sink: Graph to receive the parsed triples
+
+ :param version: parse as JSON-LD version, defaults to 1.1
+
+ :param encoding: character encoding of the JSON (should be "utf-8"
+ or "utf-16"), defaults to "utf-8"
+
+ :param base: JSON-LD `Base IRI <https://www.w3.org/TR/json-ld/#base-iri>`_, defaults to None
+
+ :param context: JSON-LD `Context <https://www.w3.org/TR/json-ld/#the-context>`_, defaults to None
+
+ :param generalized_rdf: parse as `Generalized RDF <https://www.w3.org/TR/json-ld/#relationship-to-rdf>`_, defaults to False
+
+ :param extract_all_scripts: if source is an HTML document then extract
+ all script elements, defaults to False (extract only the first
+ script element). This is ignored if ``source.system_id`` contains
+ a fragment identifier, in which case only the script element with
+ matching id attribute is extracted.
+
+ """
if encoding not in ("utf-8", "utf-16"):
warnings.warn(
"JSON should be encoded as unicode. "
"Given encoding was: %s" % encoding
)
- base = kwargs.get("base") or sink.absolutize(
- source.getPublicId() or source.getSystemId() or ""
- )
+ if not base:
+ base = sink.absolutize(source.getPublicId() or source.getSystemId() or "")
- context_data = kwargs.get("context")
+ context_data = context
if not context_data and hasattr(source, "url") and hasattr(source, "links"):
if TYPE_CHECKING:
assert isinstance(source, URLInputSource)
@@ -105,9 +145,15 @@ def parse(
except ValueError:
version = 1.1
- generalized_rdf = kwargs.get("generalized_rdf", False)
+ # Get the optional fragment identifier
+ try:
+ fragment_id = URIRef(source.getSystemId()).fragment
+ except Exception:
+ fragment_id = None
- data = source_to_json(source)
+ data, html_base = source_to_json(source, fragment_id, extract_all_scripts)
+ if html_base is not None:
+ base = URIRef(html_base, base=base)
# NOTE: A ConjunctiveGraph parses into a Graph sink, so no sink will be
# context_aware. Keeping this check in case RDFLib is changed, or
@@ -118,7 +164,7 @@ def parse(
else:
conj_sink = sink
- to_rdf(data, conj_sink, base, context_data, version, generalized_rdf)
+ to_rdf(data, conj_sink, base, context_data, version, bool(generalized_rdf))
def to_rdf(
diff --git a/rdflib/plugins/shared/jsonld/context.py b/rdflib/plugins/shared/jsonld/context.py
index 0ee9e52a1..f80cdf376 100644
--- a/rdflib/plugins/shared/jsonld/context.py
+++ b/rdflib/plugins/shared/jsonld/context.py
@@ -481,7 +481,7 @@ def _fetch_context(
return self._context_cache[source_url]
# type error: Incompatible types in assignment (expression has type "Optional[Any]", variable has type "str")
- source = source_to_json(source_url) # type: ignore[assignment]
+ source, _ = source_to_json(source_url)
if source and CONTEXT not in source:
raise INVALID_REMOTE_CONTEXT
diff --git a/rdflib/plugins/shared/jsonld/util.py b/rdflib/plugins/shared/jsonld/util.py
index ae2ceb3b9..524d5ece8 100644
--- a/rdflib/plugins/shared/jsonld/util.py
+++ b/rdflib/plugins/shared/jsonld/util.py
@@ -2,7 +2,7 @@
from __future__ import annotations
import pathlib
-from typing import IO, TYPE_CHECKING, Any, Optional, TextIO, Tuple, Union
+from typing import IO, TYPE_CHECKING, Any, List, Optional, TextIO, Tuple, Union
if TYPE_CHECKING:
import json
@@ -14,6 +14,7 @@
except ImportError:
import simplejson as json
+from html.parser import HTMLParser
from io import TextIOBase, TextIOWrapper
from posixpath import normpath, sep
from urllib.parse import urljoin, urlsplit, urlunsplit
@@ -31,13 +32,29 @@
def source_to_json(
source: Optional[
Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath]
- ]
-) -> Optional[Any]:
+ ],
+ fragment_id: Optional[str] = None,
+ extract_all_scripts: Optional[bool] = False,
+) -> Tuple[Any, Any]:
+ """Extract JSON from a source document.
+
+ The source document can be JSON or HTML with embedded JSON script elements (type attribute = "application/ld+json").
+ To process as HTML ``source.content_type`` must be set to "text/html" or "application/xhtml+xml".
+
+ :param source: the input source document (JSON or HTML)
+
+ :param fragment_id: if source is an HTML document then extract only the script element with matching id attribute, defaults to None
+
+ :param extract_all_scripts: if source is an HTML document then extract all script elements (unless fragment_id is provided), defaults to False (extract only the first script element)
+
+ :return: Tuple with the extracted JSON document and value of the HTML base element
+ """
+
if isinstance(source, PythonInputSource):
- return source.data
+ return (source.data, None)
if isinstance(source, StringInputSource):
- return json.load(source.getCharacterStream())
+ return (json.load(source.getCharacterStream()), None)
# TODO: conneg for JSON (fix support in rdflib's URLInputSource!)
source = create_input_source(source, format="json-ld")
@@ -50,7 +67,15 @@ def source_to_json(
use_stream = stream
else:
use_stream = TextIOWrapper(stream, encoding="utf-8")
- return json.load(use_stream)
+
+ if source.content_type in ("text/html", "application/xhtml+xml"):
+ parser = HTMLJSONParser(
+ fragment_id=fragment_id, extract_all_scripts=extract_all_scripts
+ )
+ parser.feed(use_stream.read())
+ return (parser.get_json(), parser.get_base())
+ else:
+ return (json.load(use_stream), None)
finally:
stream.close()
@@ -126,3 +151,67 @@ def context_from_urlinputsource(source: URLInputSource) -> Optional[str]: # typ
"norm_url",
"context_from_urlinputsource",
]
+
+
+class HTMLJSONParser(HTMLParser):
+ def __init__(
+ self,
+ fragment_id: Optional[str] = None,
+ extract_all_scripts: Optional[bool] = False,
+ ):
+ super().__init__()
+ self.fragment_id = fragment_id
+ self.json: List[Any] = []
+ self.contains_json = False
+ self.fragment_id_does_not_match = False
+ self.base = None
+ self.extract_all_scripts = extract_all_scripts
+ self.script_count = 0
+
+ def handle_starttag(self, tag, attrs):
+ self.contains_json = False
+ self.fragment_id_does_not_match = False
+
+ # Only set self. contains_json to True if the
+ # type is 'application/ld+json'
+ if tag == "script":
+ for attr, value in attrs:
+ if attr == "type" and value == "application/ld+json":
+ self.contains_json = True
+ elif attr == "id" and self.fragment_id and value != self.fragment_id:
+ self.fragment_id_does_not_match = True
+
+ elif tag == "base":
+ for attr, value in attrs:
+ if attr == "href":
+ self.base = value
+
+ def handle_data(self, data):
+ # Only do something when we know the context is a
+ # script element containing application/ld+json
+
+ if self.contains_json is True and self.fragment_id_does_not_match is False:
+
+ if not self.extract_all_scripts and self.script_count > 0:
+ return
+
+ if data.strip() == "":
+ # skip empty data elements
+ return
+
+ # Try to parse the json
+ parsed = json.loads(data)
+
+ # Add to the result document
+ if isinstance(parsed, list):
+ self.json.extend(parsed)
+ else:
+ self.json.append(parsed)
+
+ self.script_count += 1
+
+ def get_json(self):
+ return self.json
+
+ def get_base(self):
+ return self.base
| diff --git a/test/jsonld/runner.py b/test/jsonld/runner.py
index e07dc46b6..a8237fd95 100644
--- a/test/jsonld/runner.py
+++ b/test/jsonld/runner.py
@@ -22,6 +22,9 @@ def _preserving_nodeid(self, bnode_context=None):
def make_fake_urlinputsource(input_uri, format=None, suite_base=None, options={}):
local_url = input_uri.replace("https://w3c.github.io/json-ld-api/tests/", "./")
+ if (index := local_url.find("#")) > -1:
+ # Strip off the optional fragment identifier
+ local_url = local_url[0:index]
try:
f = open(local_url, "rb")
except FileNotFoundError:
@@ -33,6 +36,8 @@ def make_fake_urlinputsource(input_uri, format=None, suite_base=None, options={}
source.links = []
if local_url.endswith((".jsonld", ".jldt")):
source.content_type = "application/ld+json"
+ elif local_url.endswith(".html"):
+ source.content_type = "text/html"
else:
source.content_type = "application/json"
source.format = format
@@ -172,6 +177,52 @@ def do_test_serializer(suite_base, cat, num, inputpath, expectedpath, context, o
_compare_json(expected_json, result_json)
+def do_test_html(suite_base, cat, num, inputpath, expectedpath, context, options):
+ input_uri = suite_base + inputpath
+ input_graph = ConjunctiveGraph()
+
+ input_src = make_fake_urlinputsource(
+ input_uri, format="json-ld", suite_base=suite_base, options=options
+ )
+
+ context = _load_json(context) if context else context
+
+ # Get test options from the manifest
+ base = options.get("base", input_src.getPublicId())
+ extract_all_scripts = options.get("extractAllScripts", False)
+
+ p = JsonLDParser()
+ p.parse(
+ input_src,
+ input_graph,
+ base=base,
+ context=context,
+ generalized_rdf=True,
+ extract_all_scripts=extract_all_scripts,
+ )
+
+ if expectedpath.endswith(".nq"):
+ expected_graph = _load_nquads(expectedpath)
+
+ elif expectedpath.endswith(".jsonld"):
+ expected_graph = ConjunctiveGraph()
+ with open(expectedpath) as f:
+ data = f.read()
+ expected_graph.parse(data=data, format="json-ld")
+
+ # TODO: Change test from graph comparison to json comparison
+ # The html test cases combine testing for JSON-LD extraction from the HTML
+ # along with testing for other algorithms (compact/flatten), which we do
+ # not currently support. In order to test extraction only, we currently
+ # perform a graph comparison. Consider changing this to a json comparison
+ # once the processing algorithms are implemented.
+
+ assert isomorphic(input_graph, expected_graph), "Expected:\n%s\nGot:\n%s" % (
+ expected_graph.serialize(),
+ input_graph.serialize(),
+ )
+
+
def _load_nquads(source):
graph = ConjunctiveGraph()
with open(source) as f:
diff --git a/test/jsonld/test_context.py b/test/jsonld/test_context.py
index e99304ffd..cdecd6363 100644
--- a/test/jsonld/test_context.py
+++ b/test/jsonld/test_context.py
@@ -144,7 +144,7 @@ def _mock_source_loader(f):
@wraps(f)
def _wrapper():
try:
- context.source_to_json = SOURCES.get
+ context.source_to_json = lambda source: (SOURCES.get(source), None)
f()
finally:
context.source_to_json = _source_to_json
diff --git a/test/jsonld/test_onedotone.py b/test/jsonld/test_onedotone.py
index 7d27f4c45..840a657cb 100644
--- a/test/jsonld/test_onedotone.py
+++ b/test/jsonld/test_onedotone.py
@@ -2,6 +2,7 @@
import json
import os
+import re
from os import chdir, environ, getcwd
from os import path as p
from typing import Tuple
@@ -23,7 +24,6 @@
"remote",
)
unsupported_tests += ("flatten", "compact", "expand")
-unsupported_tests += ("html",)
unsupported_tests += ("fromRdf",) # The JSON-LD 1.1 enhancement applies to parsing only
known_bugs: Tuple[str, ...] = (
@@ -138,7 +138,8 @@
"toRdf/tn02-in",
# TODO: Rdflib should silently reject bad predicate URIs
"toRdf/wf02-in",
- # TODO: we don't extract context or json-ld that's embedded in HTML
+ # TODO: Determine why f004 expects to extract all scripts
+ "html/f004-in",
"remote-doc/0013-in",
"remote-doc/la01-in",
"remote-doc/la02-in",
@@ -219,6 +220,10 @@ def get_test_suite_cases():
func = runner.do_test_json
else: # toRdf
func = runner.do_test_parser
+ elif re.search(
+ r"\.html(#.*)?$", inputpath
+ ): # html (with optional fragment identifier)
+ func = runner.do_test_html
else: # fromRdf
func = runner.do_test_serializer
rdf_test_uri = URIRef("{0}{1}-manifest#t{2}".format(TC_BASE, cat, num))
| [
{
"components": [
{
"doc": "",
"lines": [
156,
217
],
"name": "HTMLJSONParser",
"signature": "class HTMLJSONParser(HTMLParser):",
"type": "class"
},
{
"doc": "",
"lines": [
157,
169
... | [
"test/jsonld/test_context.py::test_loading_contexts",
"test/jsonld/test_context.py::test_ignore_base_remote_context",
"test/jsonld/test_context.py::test_recursive_context_inclusion_error",
"test/jsonld/test_onedotone.py::test_suite[https://w3c.github.io/json-ld-api/tests/html-manifest#te001-do_test_html-https... | [
"test/jsonld/test_context.py::test_create_context",
"test/jsonld/test_context.py::test_select_term_based_on_value_characteristics",
"test/jsonld/test_context.py::test_getting_keyword_values_from_nodes",
"test/jsonld/test_context.py::test_parsing_a_context_expands_prefixes",
"test/jsonld/test_context.py::tes... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add JSON-LD extraction from HTML
Implementation of issue #2692.
See also https://w3c.github.io/json-ld-syntax/#embedding-json-ld-in-html-documents and https://www.w3.org/TR/json-ld11-api/#html-content-algorithms .
# Summary of changes
If `source.content_type` is "text/html" or "application/xhtml+xml" then parse the document as HTML and extract script elements of type="application/ld+json" as JSON-LD.
The default behavior is to extract only the first matching script element. These overrides are available:
* To extract all script elements: supply an optional `extract_all_scripts=True` parameter to `JsonLDParser.parse()`
* To extract one script element with a specific id attribute value: add the id value as a fragment identifier in the IRI available from `source.getSystemId()`
# Detailed changes
`rdflib.plugins.parsers.jsonld.JsonLDParser.parse`
* add docstring
* change parameter list from **kwargs to explicit list
* add optional extract_all_scripts parameter
* get the fragment identifier from source.getSystemId()
* add fragment_id and extract_all_scripts parameters to the call to source_to_json
`rdflib.plugins.shared.jsonld.util.source_to_json`
* add docstring
* add optional fragment_id and extract_all_scripts parameters
* change the return value to a tuple with the extracted JSON document and value of the HTML base element
* if source.content_type is "text/html" or "application/xhtml+xml" then parse source as HTML and extract the appropriate script element(s) and the HTML base element
`test/jsonld/test_onedotone.py`
* enable all existing html tests (except html/f004-in). (*Note*: for more information on the failing html/f004-in test, see https://lists.w3.org/Archives/Public/public-json-ld-wg/2024May/0000.html)
* if inputpath ends with ".html" (with optional fragment identifier) then invoke runner.do_test_html
`test/jsonld/runner.py`
* add new `do_test_html` function (*Note*: the html test cases from the JSON-LD Test Suite combine testing
for JSON-LD extraction from the HTML with testing for other algorithms (e.g. compact/flatten),
which rdflib does not currently support. In order to test extraction only and ignore
the compact/flatten algorithms, do_test_html performs a graph comparison using
rdflib.compare.isomorphic, without serializing back to JSON)
# Breaking Changes
When `rdflib.plugins.shared.jsonld.util.source_to_json` extracts JSON-LD from HTML, it needs to return the value of the HTML base element in addition to the JSON. I took the simplest path and returned a tuple containing the JSON and the base.
I can think of other ways to return the base without breaking the current return value:
* Return json when processing a json document and tuple (json, base) when processing an html document.
* Add an optional parameter to return tuple (json, base) instead of json.
* Continue returning only json, but add an optional parameter which will receive the value of base.
# Checklist
- [x] Checked that there aren't other open pull requests for
the same change.
- [x] Checked that all tests and type checking passes.
- If the change adds new features or changes the RDFLib public API:
- [x] Created an issue to discuss the change and get in-principle agreement. #2692
- [ ] Considered adding an example in `./examples`.
- If the change has a potential impact on users of this project:
- [x] Added or updated tests that fail without the change.
- [ ] Updated relevant documentation to avoid inaccuracies.
- [ ] Considered adding additional documentation.
- [x] Considered granting [push permissions to the PR branch](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork),
so maintainers can fix minor issues and keep your PR up to date.
----------
</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 rdflib/plugins/shared/jsonld/util.py]
(definition of HTMLJSONParser:)
class HTMLJSONParser(HTMLParser):
(definition of HTMLJSONParser.__init__:)
def __init__( self, fragment_id: Optional[str] = None, extract_all_scripts: Optional[bool] = False, ):
(definition of HTMLJSONParser.handle_starttag:)
def handle_starttag(self, tag, attrs):
(definition of HTMLJSONParser.handle_data:)
def handle_data(self, data):
(definition of HTMLJSONParser.get_json:)
def get_json(self):
(definition of HTMLJSONParser.get_base:)
def get_base(self):
[end of new definitions in rdflib/plugins/shared/jsonld/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>> | 0c11debb5178157baeac27b735e49a757916d2a6 | ||
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"
},
{
... | [
"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... | [] | 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 hand... | [
"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_me... | [] | 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 | |
tobymao__sqlglot-3678 | 3,678 | tobymao/sqlglot | null | ac0e89c4401f2f278d32c3e956670b262ab21ce7 | 2024-06-19T09:58:57Z | diff --git a/sqlglot/dialects/databricks.py b/sqlglot/dialects/databricks.py
index deddb6e138..fc1772d5c6 100644
--- a/sqlglot/dialects/databricks.py
+++ b/sqlglot/dialects/databricks.py
@@ -1,6 +1,8 @@
from __future__ import annotations
-from sqlglot import exp, transforms
+import typing as t
+
+from sqlglot import exp, transforms, jsonpath
from sqlglot.dialects.dialect import (
date_delta_sql,
build_date_delta,
@@ -10,16 +12,34 @@
from sqlglot.tokens import TokenType
+def _build_json_extract(args: t.List) -> exp.JSONExtract:
+ # Transform GET_JSON_OBJECT(expr, '$.<path>') -> expr:<path>
+ this = args[0]
+ path = args[1].name.lstrip("$.")
+ return exp.JSONExtract(this=this, expression=path)
+
+
def _timestamp_diff(
self: Databricks.Generator, expression: exp.DatetimeDiff | exp.TimestampDiff
) -> str:
return self.func("TIMESTAMPDIFF", expression.unit, expression.expression, expression.this)
+def _jsonextract_sql(
+ self: Databricks.Generator, expression: exp.JSONExtract | exp.JSONExtractScalar
+) -> str:
+ this = self.sql(expression, "this")
+ expr = self.sql(expression, "expression")
+ return f"{this}:{expr}"
+
+
class Databricks(Spark):
SAFE_DIVISION = False
COPY_PARAMS_ARE_CSV = False
+ class JSONPathTokenizer(jsonpath.JSONPathTokenizer):
+ IDENTIFIERS = ["`", '"']
+
class Parser(Spark.Parser):
LOG_DEFAULTS_TO_LN = True
STRICT_CAST = True
@@ -31,6 +51,7 @@ class Parser(Spark.Parser):
"DATE_ADD": build_date_delta(exp.DateAdd),
"DATEDIFF": build_date_delta(exp.DateDiff),
"TIMESTAMPDIFF": build_date_delta(exp.TimestampDiff),
+ "GET_JSON_OBJECT": _build_json_extract,
}
FACTOR = {
@@ -42,6 +63,8 @@ class Generator(Spark.Generator):
TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
COPY_PARAMS_ARE_WRAPPED = False
COPY_PARAMS_EQ_REQUIRED = True
+ JSON_PATH_SINGLE_QUOTE_ESCAPE = False
+ QUOTE_JSON_PATH = False
TRANSFORMS = {
**Spark.Generator.TRANSFORMS,
@@ -65,6 +88,9 @@ class Generator(Spark.Generator):
transforms.unnest_to_explode,
]
),
+ exp.JSONExtract: _jsonextract_sql,
+ exp.JSONExtractScalar: _jsonextract_sql,
+ exp.JSONPathRoot: lambda *_: "",
exp.ToChar: lambda self, e: self.function_fallback_sql(e),
}
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index 01042a7517..18b35a7da0 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -9,7 +9,7 @@
from sqlglot.errors import ParseError
from sqlglot.generator import Generator
from sqlglot.helper import AutoName, flatten, is_int, seq_get
-from sqlglot.jsonpath import parse as parse_json_path
+from sqlglot.jsonpath import JSONPathTokenizer, parse as parse_json_path
from sqlglot.parser import Parser
from sqlglot.time import TIMEZONES, format_time
from sqlglot.tokens import Token, Tokenizer, TokenType
@@ -125,12 +125,16 @@ def __new__(cls, clsname, bases, attrs):
base = seq_get(bases, 0)
base_tokenizer = (getattr(base, "tokenizer_class", Tokenizer),)
+ base_jsonpath_tokenizer = (getattr(base, "jsonpath_tokenizer_class", JSONPathTokenizer),)
base_parser = (getattr(base, "parser_class", Parser),)
base_generator = (getattr(base, "generator_class", Generator),)
klass.tokenizer_class = klass.__dict__.get(
"Tokenizer", type("Tokenizer", base_tokenizer, {})
)
+ klass.jsonpath_tokenizer_class = klass.__dict__.get(
+ "JSONPathTokenizer", type("JSONPathTokenizer", base_jsonpath_tokenizer, {})
+ )
klass.parser_class = klass.__dict__.get("Parser", type("Parser", base_parser, {}))
klass.generator_class = klass.__dict__.get(
"Generator", type("Generator", base_generator, {})
@@ -324,6 +328,7 @@ class Dialect(metaclass=_Dialect):
# --- Autofilled ---
tokenizer_class = Tokenizer
+ jsonpath_tokenizer_class = JSONPathTokenizer
parser_class = Parser
generator_class = Generator
@@ -621,9 +626,8 @@ def to_json_path(self, path: t.Optional[exp.Expression]) -> t.Optional[exp.Expre
path_text = path.name
if path.is_number:
path_text = f"[{path_text}]"
-
try:
- return parse_json_path(path_text)
+ return parse_json_path(path_text, self)
except ParseError as e:
logger.warning(f"Invalid JSON path syntax. {str(e)}")
@@ -655,6 +659,12 @@ def tokenizer(self) -> Tokenizer:
self._tokenizer = self.tokenizer_class(dialect=self)
return self._tokenizer
+ @property
+ def jsonpath_tokenizer(self) -> JSONPathTokenizer:
+ if not hasattr(self, "_jsonpath_tokenizer"):
+ self._jsonpath_tokenizer = self.jsonpath_tokenizer_class(dialect=self)
+ return self._jsonpath_tokenizer
+
def parser(self, **opts) -> Parser:
return self.parser_class(dialect=self, **opts)
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index 021b34b2e9..617ea4e527 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -368,6 +368,9 @@ class Generator(metaclass=_Generator):
# The keywords to use when prefixing & separating WITH based properties
WITH_PROPERTIES_PREFIX = "WITH"
+ # Whether to quote the generated expression of exp.JsonPath
+ QUOTE_JSON_PATH = True
+
TYPE_MAPPING = {
exp.DataType.Type.NCHAR: "CHAR",
exp.DataType.Type.NVARCHAR: "VARCHAR",
@@ -2655,7 +2658,10 @@ def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
def jsonpath_sql(self, expression: exp.JSONPath) -> str:
path = self.expressions(expression, sep="", flat=True).lstrip(".")
- return f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
+ if self.QUOTE_JSON_PATH:
+ path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
+
+ return path
def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
if isinstance(expression, exp.JSONPathPart):
diff --git a/sqlglot/jsonpath.py b/sqlglot/jsonpath.py
index 129a4e6fed..911debe4b5 100644
--- a/sqlglot/jsonpath.py
+++ b/sqlglot/jsonpath.py
@@ -8,6 +8,7 @@
if t.TYPE_CHECKING:
from sqlglot._typing import Lit
+ from sqlglot.dialects.dialect import DialectType
class JSONPathTokenizer(Tokenizer):
@@ -36,9 +37,12 @@ class JSONPathTokenizer(Tokenizer):
STRING_ESCAPES = ["\\"]
-def parse(path: str) -> exp.JSONPath:
+def parse(path: str, dialect: DialectType = None) -> exp.JSONPath:
"""Takes in a JSON path string and parses it into a JSONPath expression."""
- tokens = JSONPathTokenizer().tokenize(path)
+ from sqlglot.dialects import Dialect
+
+ jsonpath_tokenizer = Dialect.get_or_raise(dialect).jsonpath_tokenizer
+ tokens = jsonpath_tokenizer.tokenize(path)
size = len(tokens)
i = 0
| diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py
index 9ef3b86e18..c88679dc5c 100644
--- a/tests/dialects/test_databricks.py
+++ b/tests/dialects/test_databricks.py
@@ -96,33 +96,30 @@ def test_databricks(self):
# https://docs.databricks.com/sql/language-manual/functions/colonsign.html
def test_json(self):
+ self.validate_identity("SELECT c1:price, c1:price.foo, c1:price.bar[1]")
self.validate_identity(
- """SELECT c1 : price FROM VALUES ('{ "price": 5 }') AS T(c1)""",
- """SELECT GET_JSON_OBJECT(c1, '$.price') FROM VALUES ('{ "price": 5 }') AS T(c1)""",
+ """SELECT c1:item[1].price FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)"""
)
self.validate_identity(
- """SELECT c1:['price'] FROM VALUES('{ "price": 5 }') AS T(c1)""",
- """SELECT GET_JSON_OBJECT(c1, '$.price') FROM VALUES ('{ "price": 5 }') AS T(c1)""",
+ """SELECT c1:item[*].price FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)"""
)
self.validate_identity(
- """SELECT c1:item[1].price FROM VALUES('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
- """SELECT GET_JSON_OBJECT(c1, '$.item[1].price') FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
+ """SELECT FROM_JSON(c1:item[*].price, 'ARRAY<DOUBLE>')[0] FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)"""
)
self.validate_identity(
- """SELECT c1:item[*].price FROM VALUES('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
- """SELECT GET_JSON_OBJECT(c1, '$.item[*].price') FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
+ """SELECT INLINE(FROM_JSON(c1:item[*], 'ARRAY<STRUCT<model STRING, price DOUBLE>>')) FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)"""
)
self.validate_identity(
- """SELECT from_json(c1:item[*].price, 'ARRAY<DOUBLE>')[0] FROM VALUES('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
- """SELECT FROM_JSON(GET_JSON_OBJECT(c1, '$.item[*].price'), 'ARRAY<DOUBLE>')[0] FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
+ """SELECT c1:['price'] FROM VALUES ('{ "price": 5 }') AS T(c1)""",
+ """SELECT c1:price FROM VALUES ('{ "price": 5 }') AS T(c1)""",
)
self.validate_identity(
- """SELECT inline(from_json(c1:item[*], 'ARRAY<STRUCT<model STRING, price DOUBLE>>')) FROM VALUES('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
- """SELECT INLINE(FROM_JSON(GET_JSON_OBJECT(c1, '$.item[*]'), 'ARRAY<STRUCT<model STRING, price DOUBLE>>')) FROM VALUES ('{ "item": [ { "model" : "basic", "price" : 6.12 }, { "model" : "medium", "price" : 9.24 } ] }') AS T(c1)""",
+ """SELECT GET_JSON_OBJECT(c1, '$.price') FROM VALUES ('{ "price": 5 }') AS T(c1)""",
+ """SELECT c1:price FROM VALUES ('{ "price": 5 }') AS T(c1)""",
)
self.validate_identity(
- "SELECT c1 : price",
- "SELECT GET_JSON_OBJECT(c1, '$.price')",
+ """SELECT raw:`zip code`, raw:`fb:testid`, raw:store['bicycle'], raw:store["zip code"]""",
+ """SELECT raw:["zip code"], raw:["fb:testid"], raw:store.bicycle, raw:store["zip code"]""",
)
def test_datediff(self):
diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py
index 87076fe7fa..26d87d2114 100644
--- a/tests/dialects/test_redshift.py
+++ b/tests/dialects/test_redshift.py
@@ -28,7 +28,7 @@ def test_redshift(self):
"""SELECT JSON_EXTRACT_PATH_TEXT('{ "farm": {"barn": { "color": "red", "feed stocked": true }}}', 'farm', 'barn', 'color')""",
write={
"bigquery": """SELECT JSON_EXTRACT_SCALAR('{ "farm": {"barn": { "color": "red", "feed stocked": true }}}', '$.farm.barn.color')""",
- "databricks": """SELECT GET_JSON_OBJECT('{ "farm": {"barn": { "color": "red", "feed stocked": true }}}', '$.farm.barn.color')""",
+ "databricks": """SELECT '{ "farm": {"barn": { "color": "red", "feed stocked": true }}}':farm.barn.color""",
"duckdb": """SELECT '{ "farm": {"barn": { "color": "red", "feed stocked": true }}}' ->> '$.farm.barn.color'""",
"postgres": """SELECT JSON_EXTRACT_PATH_TEXT('{ "farm": {"barn": { "color": "red", "feed stocked": true }}}', 'farm', 'barn', 'color')""",
"presto": """SELECT JSON_EXTRACT_SCALAR('{ "farm": {"barn": { "color": "red", "feed stocked": true }}}', '$.farm.barn.color')""",
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py
index 12864369fb..052f711a53 100644
--- a/tests/dialects/test_snowflake.py
+++ b/tests/dialects/test_snowflake.py
@@ -337,7 +337,7 @@ def test_snowflake(self):
"""SELECT PARSE_JSON('{"fruit":"banana"}'):fruit""",
write={
"bigquery": """SELECT JSON_EXTRACT(PARSE_JSON('{"fruit":"banana"}'), '$.fruit')""",
- "databricks": """SELECT GET_JSON_OBJECT('{"fruit":"banana"}', '$.fruit')""",
+ "databricks": """SELECT '{"fruit":"banana"}':fruit""",
"duckdb": """SELECT JSON('{"fruit":"banana"}') -> '$.fruit'""",
"mysql": """SELECT JSON_EXTRACT('{"fruit":"banana"}', '$.fruit')""",
"presto": """SELECT JSON_EXTRACT(JSON_PARSE('{"fruit":"banana"}'), '$.fruit')""",
diff --git a/tests/test_jsonpath.py b/tests/test_jsonpath.py
index 4daf3c1ce0..c939c52321 100644
--- a/tests/test_jsonpath.py
+++ b/tests/test_jsonpath.py
@@ -2,8 +2,9 @@
import os
import unittest
-from sqlglot import exp, jsonpath
+from sqlglot import exp
from sqlglot.errors import ParseError, TokenError
+from sqlglot.jsonpath import parse
from tests.helpers import FIXTURES_DIR
@@ -25,7 +26,7 @@ def test_jsonpath(self):
exp.JSONPathSelector(this=exp.JSONPathScript(this="@.x)")),
]
self.assertEqual(
- jsonpath.parse("$.*.a[0]['x'][*, 'y', 1].z[?(@.a == 'b'), 1:][1:5][1,?@.a][(@.x)]"),
+ parse("$.*.a[0]['x'][*, 'y', 1].z[?(@.a == 'b'), 1:][1:5][1,?@.a][(@.x)]"),
exp.JSONPath(expressions=expected_expressions),
)
@@ -36,7 +37,7 @@ def test_identity(self):
("$[((@.length-1))]", "$[((@.length-1))]"),
):
with self.subTest(f"{selector} -> {expected}"):
- self.assertEqual(jsonpath.parse(selector).sql(), f"'{expected}'")
+ self.assertEqual(parse(selector).sql(), f"'{expected}'")
def test_cts_file(self):
with open(os.path.join(FIXTURES_DIR, "jsonpath", "cts.json")) as file:
@@ -131,9 +132,9 @@ def test_cts_file(self):
with self.subTest(f"{selector.strip()} /* {test['name']} */"):
if test.get("invalid_selector"):
try:
- jsonpath.parse(selector)
+ parse(selector)
except (ParseError, TokenError):
pass
else:
- path = jsonpath.parse(selector)
+ path = parse(selector)
self.assertEqual(path.sql(), f"'{overrides.get(selector, selector)}'")
| [] | [
"tests/dialects/test_databricks.py::TestDatabricks::test_json",
"tests/dialects/test_redshift.py::TestRedshift::test_redshift",
"tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake"
] | [
"tests/dialects/test_databricks.py::TestDatabricks::test_add_date",
"tests/dialects/test_databricks.py::TestDatabricks::test_databricks",
"tests/dialects/test_databricks.py::TestDatabricks::test_datediff",
"tests/dialects/test_databricks.py::TestDatabricks::test_without_as",
"tests/dialects/test_redshift.py... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(databricks)!: Preserve JSON/VARIANT path with operators
Fixes #3673
This PR aims to preserve the JSON/Variant access in Databricks using operators instead of JSON functions + JSONPath by:
- Adding `IDENTIFIERS` in `jsonpath.py` to be able to parse keys with special chars (see [example](https://docs.databricks.com/en/semi-structured/variant.html#extract-a-top-level-variant-field))
- Manually parsing `GET_JSON_OBJECT()` -> `exp.JSONExtract`
- Changing the generation of `exp.JSONExtract` & `exp.JSONExtractScalar` (only in DB) to the operator-based syntax
Docs
--------
[DB querying VARIANT](https://docs.databricks.com/en/semi-structured/variant.html#query-variant-data) | [DB path expression](https://docs.databricks.com/en/sql/language-manual/sql-ref-json-path-expression.html) | [DB JSON functions](https://docs.databricks.com/en/sql/language-manual/sql-ref-functions-builtin.html#json-functions)
----------
</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>
</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>
Sqlglot does not preserve new Databricks's Variant Syntax
The newest Databricks Runtime (15.3) does support a number of fancy syntax for their new Variant Type.
Docs: https://docs.databricks.com/en/semi-structured/variant.html
Those do not get preserved
```python
import sqlglot as sg
print(sg.parse_one("SELECT raw:store.bicycle FROM store_data", dialect="databricks").sql("databricks"))
-- prints "SELECT GET_JSON_OBJECT(raw, '$.store.bicycle') FROM store_data"
print(sg.parse_one("SELECT raw:`zip code`, raw:`fb:testid` FROM store_data", dialect="databricks").sql("databricks"))
-- prints "SELECT GET_JSON_OBJECT(raw, '$[\\'`zip\\'][\\'code`\\']'), GET_JSON_OBJECT(raw, '$[\\'`fb\\'][\\'testid`\\']') FROM store_data"
```
----------
This is intentional, so unless there's an issue with the semantics of the resulting queries, changing it is out of scope. Happy to continue discussing.
> This is intentional, so unless there's an issue with the semantics of the resulting queries, changing it is out of scope. Happy to continue discussing.
There is, variant is a new type, and it's not json. see https://docs.databricks.com/en/semi-structured/variant-json-diff.html#what-are-the-sql-functions-for-working-with-variants
I see, thanks for clarifying. We'll take a closer look 👍
Transpilation of `:` will get a bit tricky now, because it requires type information.. @VaggelisD maybe let's try to change the `-> databricks` generation so that it preserves the `:` operator but continue parsing it into a `JSONExtract` to preserve current behavior and do a best-effort transpilation as if it was a JSON extraction.
--------------------
</issues> | ceb42fabad60312699e4b15936aeebac00e22e4d | |
conan-io__conan-16496 | 16,496 | conan-io/conan | null | 0a15ae21ccbe4a45957bd1cf236e0deaf89f187c | 2024-06-18T23:33:51Z | diff --git a/conan/tools/cmake/toolchain/blocks.py b/conan/tools/cmake/toolchain/blocks.py
index ae023a00906..5d1f340518d 100644
--- a/conan/tools/cmake/toolchain/blocks.py
+++ b/conan/tools/cmake/toolchain/blocks.py
@@ -23,11 +23,12 @@
from conans.util.files import load
-class Block(object):
- def __init__(self, conanfile, toolchain):
+class Block:
+ def __init__(self, conanfile, toolchain, name):
self._conanfile = conanfile
self._toolchain = toolchain
self._context_values = None
+ self._name = name
@property
def values(self):
@@ -44,7 +45,8 @@ def get_rendered_content(self):
if context is None:
return
- template = Template(self.template, trim_blocks=True, lstrip_blocks=True)
+ template = f"########## '{self._name}' block #############\n" + self.template + "\n\n"
+ template = Template(template, trim_blocks=True, lstrip_blocks=True)
return template.render(**context)
def context(self):
@@ -56,8 +58,10 @@ def template(self):
class VSRuntimeBlock(Block):
- template = textwrap.dedent("""
- # Definition of VS runtime, defined from build_type, compiler.runtime, compiler.runtime_type
+ template = textwrap.dedent("""\
+ # Definition of VS runtime CMAKE_MSVC_RUNTIME_LIBRARY, from settings build_type,
+ # compiler.runtime, compiler.runtime_type
+
{% set genexpr = namespace(str='') %}
{% for config, value in vs_runtimes.items() %}
{% set genexpr.str = genexpr.str +
@@ -67,6 +71,7 @@ class VSRuntimeBlock(Block):
if(NOT "${POLICY_CMP0091}" STREQUAL NEW)
message(FATAL_ERROR "The CMake policy CMP0091 must be NEW, but is '${POLICY_CMP0091}'")
endif()
+ message(STATUS "Conan toolchain: Setting CMAKE_MSVC_RUNTIME_LIBRARY={{ genexpr.str }}")
set(CMAKE_MSVC_RUNTIME_LIBRARY "{{ genexpr.str }}")
""")
@@ -116,9 +121,11 @@ def context(self):
class VSDebuggerEnvironment(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Definition of CMAKE_VS_DEBUGGER_ENVIRONMENT from "bindirs" folders of dependencies
+ # for execution of applications with shared libraries within the VS IDE
+
{% if vs_debugger_path %}
- # Definition of CMAKE_VS_DEBUGGER_ENVIRONMENT
set(CMAKE_VS_DEBUGGER_ENVIRONMENT "{{ vs_debugger_path }}")
{% endif %}
""")
@@ -166,7 +173,9 @@ def context(self):
class FPicBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Defining CMAKE_POSITION_INDEPENDENT_CODE for static libraries when necessary
+
{% if fpic %}
message(STATUS "Conan toolchain: Setting CMAKE_POSITION_INDEPENDENT_CODE={{ fpic }} (options.fPIC)")
set(CMAKE_POSITION_INDEPENDENT_CODE {{ fpic }} CACHE BOOL "Position independent code")
@@ -185,11 +194,16 @@ def context(self):
class GLibCXXBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Definition of libcxx from 'compiler.libcxx' setting, defining the
+ # right CXX_FLAGS for that libcxx
+
{% if set_libcxx %}
+ message(STATUS "Conan toolchain: Defining libcxx as C++ flags: {{ set_libcxx }}")
string(APPEND CONAN_CXX_FLAGS " {{ set_libcxx }}")
{% endif %}
{% if glibcxx %}
+ message(STATUS "Conan toolchain: Adding glibcxx compile definition: {{ glibcxx }}")
add_compile_definitions({{ glibcxx }})
{% endif %}
""")
@@ -200,7 +214,9 @@ def context(self):
class SkipRPath(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Defining CMAKE_SKIP_RPATH
+
{% if skip_rpath %}
set(CMAKE_SKIP_RPATH 1 CACHE BOOL "rpaths" FORCE)
# Policy CMP0068
@@ -216,7 +232,10 @@ def context(self):
class ArchitectureBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define C++ flags, C flags and linker flags from 'settings.arch'
+
+ message(STATUS "Conan toolchain: Defining architecture flag: {{ arch_flag }}")
string(APPEND CONAN_CXX_FLAGS " {{ arch_flag }}")
string(APPEND CONAN_C_FLAGS " {{ arch_flag }}")
string(APPEND CONAN_SHARED_LINKER_FLAGS " {{ arch_flag }}")
@@ -231,7 +250,10 @@ def context(self):
class LinkerScriptsBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Add linker flags from tools.build:linker_scripts conf
+
+ message(STATUS "Conan toolchain: Defining linker script flag: {{ linker_script_flags }}")
string(APPEND CONAN_EXE_LINKER_FLAGS {{ linker_script_flags }})
""")
@@ -248,7 +270,9 @@ def context(self):
class CppStdBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define the C++ and C standards from 'compiler.cppstd' and 'compiler.cstd'
+
{% if cppstd %}
message(STATUS "Conan toolchain: C++ Standard {{ cppstd }} with extensions {{ cppstd_extensions }}")
set(CMAKE_CXX_STANDARD {{ cppstd }})
@@ -285,7 +309,9 @@ def context(self):
class SharedLibBock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define BUILD_SHARED_LIBS for shared libraries
+
message(STATUS "Conan toolchain: Setting BUILD_SHARED_LIBS = {{ shared_libs }}")
set(BUILD_SHARED_LIBS {{ shared_libs }} CACHE BOOL "Build shared libraries")
""")
@@ -299,7 +325,9 @@ def context(self):
class ParallelBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define VS paralell build /MP flags
+
string(APPEND CONAN_CXX_FLAGS " /MP{{ parallel }}")
string(APPEND CONAN_C_FLAGS " /MP{{ parallel }}")
""")
@@ -318,12 +346,18 @@ def context(self):
class AndroidSystemBlock(Block):
- template = textwrap.dedent("""
- # New toolchain things
+ template = textwrap.dedent("""\
+ # Define Android variables ANDROID_PLATFORM, ANDROID_STL, ANDROID_ABI, etc
+ # and include(.../android.toolchain.cmake) from NDK toolchain file
+
+ # New Android toolchain definitions
+ message(STATUS "Conan toolchain: Setting Android platform: {{ android_platform }}")
set(ANDROID_PLATFORM {{ android_platform }})
{% if android_stl %}
+ message(STATUS "Conan toolchain: Setting Android stl: {{ android_stl }}")
set(ANDROID_STL {{ android_stl }})
{% endif %}
+ message(STATUS "Conan toolchain: Setting Android abi: {{ android_abi }}")
set(ANDROID_ABI {{ android_abi }})
{% if android_use_legacy_toolchain_file %}
set(ANDROID_USE_LEGACY_TOOLCHAIN_FILE {{ android_use_legacy_toolchain_file }})
@@ -363,7 +397,9 @@ def context(self):
class AppleSystemBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define Apple architectures, sysroot, deployment target, bitcode, etc
+
# Set the architectures for which to build.
set(CMAKE_OSX_ARCHITECTURES {{ cmake_osx_architectures }} CACHE STRING "" FORCE)
# Setting CMAKE_OSX_SYSROOT SDK, when using Xcode generator the name is enough
@@ -469,7 +505,9 @@ def to_apple_archs(conanfile):
class FindFiles(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define paths to find packages, programs, libraries, etc.
+
{% if find_package_prefer_config %}
set(CMAKE_FIND_PACKAGE_PREFER_CONFIG {{ find_package_prefer_config }})
{% endif %}
@@ -618,7 +656,9 @@ def context(self):
class PkgConfigBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define pkg-config from 'tools.gnu:pkg_config' executable and paths
+
{% if pkg_config %}
set(PKG_CONFIG_EXECUTABLE {{ pkg_config }} CACHE FILEPATH "pkg-config executable")
{% endif %}
@@ -643,7 +683,9 @@ def context(self):
class UserToolchain(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Include one or more CMake user toolchain from tools.cmake.cmaketoolchain:user_toolchain
+
{% for user_toolchain in paths %}
include("{{user_toolchain}}")
{% endfor %}
@@ -662,7 +704,10 @@ def context(self):
class ExtraFlagsBlock(Block):
"""This block is adding flags directly from user [conf] section"""
- _template = textwrap.dedent("""
+ _template = textwrap.dedent("""\
+ # Include extra C++, C and linker flags from configuration tools.build:<type>flags
+ # and from CMakeToolchain.extra_<type>_flags
+
# Conan conf flags start: {{config}}
{% if cxxflags %}
string(APPEND CONAN_CXX_FLAGS{{suffix}} "{% for cxxflag in cxxflags %} {{ cxxflag }}{% endfor %}")
@@ -753,7 +798,9 @@ def context(self):
class CMakeFlagsInitBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Define CMAKE_<XXX>_FLAGS from CONAN_<XXX>_FLAGS
+
foreach(config IN LISTS CMAKE_CONFIGURATION_TYPES)
string(TOUPPER ${config} config)
if(DEFINED CONAN_CXX_FLAGS_${config})
@@ -782,12 +829,13 @@ class CMakeFlagsInitBlock(Block):
if(DEFINED CONAN_EXE_LINKER_FLAGS)
string(APPEND CMAKE_EXE_LINKER_FLAGS_INIT " ${CONAN_EXE_LINKER_FLAGS}")
endif()
-
""")
class TryCompileBlock(Block):
- template = textwrap.dedent("""
+ template = textwrap.dedent("""\
+ # Blocks after this one will not be added when running CMake try/checks
+
get_property( _CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE )
if(_CMAKE_IN_TRY_COMPILE)
message(STATUS "Running toolchain IN_TRY_COMPILE")
@@ -821,14 +869,12 @@ def context(self):
class GenericSystemBlock(Block):
- template = textwrap.dedent("""
- ########## generic_system block #############
+ template = textwrap.dedent("""\
# Definition of system, platform and toolset
- #############################################
+
{% if cmake_sysroot %}
set(CMAKE_SYSROOT {{ cmake_sysroot }})
{% endif %}
-
{% if cmake_system_name %}
# Cross building
set(CMAKE_SYSTEM_NAME {{ cmake_system_name }})
@@ -947,7 +993,8 @@ def _is_apple_cross_building(self):
return os_host in ('iOS', 'watchOS', 'tvOS', 'visionOS') or (
os_host == 'Macos' and (arch_host != arch_build or os_build != os_host))
- def _get_darwin_version(self, os_name, os_version):
+ @staticmethod
+ def _get_darwin_version(os_name, os_version):
# version mapping from https://en.wikipedia.org/wiki/Darwin_(operating_system)
version_mapping = {
"Macos": {
@@ -1063,8 +1110,11 @@ def context(self):
"winsdk_version": winsdk_version,
"gen_platform_sdk_version": gen_platform_sdk_version}
+
class ExtraVariablesBlock(Block):
- template = textwrap.dedent(r"""
+ template = textwrap.dedent("""\
+ # Definition of extra CMake variables from tools.cmake.cmaketoolchain:extra_variables
+
{% if extra_variables %}
{% for key, value in extra_variables.items() %}
set({{ key }} {{ value }})
@@ -1072,7 +1122,7 @@ class ExtraVariablesBlock(Block):
{% endif %}
""")
- CMAKE_CACHE_TYPES = ["BOOL","FILEPATH", "PATH", "STRING", "INTERNAL"]
+ CMAKE_CACHE_TYPES = ["BOOL", "FILEPATH", "PATH", "STRING", "INTERNAL"]
def get_exact_type(self, key, value):
if isinstance(value, str):
@@ -1096,27 +1146,30 @@ def get_exact_type(self, key, value):
raise ConanException(f'tools.cmake.cmaketoolchain:extra_variables "{key}" invalid type "{var_type}" for cache variable. Possible types: {", ".join(self.CMAKE_CACHE_TYPES)}')
# Set docstring as variable name if not defined
docstring = value.get("docstring") or key
- force_str = " FORCE" if is_force else "" # Support python < 3.11
+ force_str = " FORCE" if is_force else "" # Support python < 3.11
return f"{var_value} CACHE {var_type} \"{docstring}\"{force_str}"
else:
if is_force:
raise ConanException(f'tools.cmake.cmaketoolchain:extra_variables "{key}" "force" is only allowed for cache variables')
return var_value
-
def context(self):
# Reading configuration from "tools.cmake.cmaketoolchain:extra_variables"
- extra_variables = self._conanfile.conf.get("tools.cmake.cmaketoolchain:extra_variables", default={}, check_type=dict)
+ extra_variables = self._conanfile.conf.get("tools.cmake.cmaketoolchain:extra_variables",
+ default={}, check_type=dict)
parsed_extra_variables = {}
for key, value in extra_variables.items():
parsed_extra_variables[key] = self.get_exact_type(key, value)
return {"extra_variables": parsed_extra_variables}
+
class OutputDirsBlock(Block):
@property
def template(self):
- return textwrap.dedent("""
+ return textwrap.dedent("""\
+ # Definition of CMAKE_INSTALL_XXX folders
+
{% if package_folder %}
set(CMAKE_INSTALL_PREFIX "{{package_folder}}")
{% endif %}
@@ -1152,6 +1205,81 @@ def context(self):
"default_res": self._get_cpp_info_value("resdirs")}
+class VariablesBlock(Block):
+ @property
+ def template(self):
+ return textwrap.dedent("""\
+ # Definition of CMake variables from CMakeToolchain.variables values
+
+ {% macro iterate_configs(var_config, action) %}
+ {% for it, values in var_config.items() %}
+ {% set genexpr = namespace(str='') %}
+ {% for conf, value in values -%}
+ set(CONAN_DEF_{{ conf }}{{ it }} "{{ value }}")
+ {% endfor %}
+ {% for conf, value in values -%}
+ {% set genexpr.str = genexpr.str +
+ '$<IF:$<CONFIG:' + conf + '>,${CONAN_DEF_' + conf|string + it|string + '},' %}
+ {% if loop.last %}{% set genexpr.str = genexpr.str + '""' -%}{%- endif -%}
+ {% endfor %}
+ {% for i in range(values|count) %}{% set genexpr.str = genexpr.str + '>' %}
+ {% endfor %}
+ set({{ it }} {{ genexpr.str }} CACHE STRING
+ "Variable {{ it }} conan-toolchain defined")
+ {% endfor %}
+ {% endmacro %}
+ # Variables
+ {% for it, value in variables.items() %}
+ {% if value is boolean %}
+ set({{ it }} {{ "ON" if value else "OFF"}} CACHE BOOL "Variable {{ it }} conan-toolchain defined")
+ {% else %}
+ set({{ it }} "{{ value }}" CACHE STRING "Variable {{ it }} conan-toolchain defined")
+ {% endif %}
+ {% endfor %}
+ # Variables per configuration
+ {{ iterate_configs(variables_config, action='set') }}
+ """)
+
+ def context(self):
+ return {"variables": self._toolchain.variables,
+ "variables_config": self._toolchain.variables.configuration_types}
+
+
+class PreprocessorBlock(Block):
+ @property
+ def template(self):
+ return textwrap.dedent("""\
+ # Preprocessor definitions from CMakeToolchain.preprocessor_definitions values
+
+ {% for it, value in preprocessor_definitions.items() %}
+ {% if value is none %}
+ add_compile_definitions("{{ it }}")
+ {% else %}
+ add_compile_definitions("{{ it }}={{ value }}")
+ {% endif %}
+ {% endfor %}
+ # Preprocessor definitions per configuration
+ {% for name, values in preprocessor_definitions_config.items() %}
+ {%- for (conf, value) in values %}
+ {% if value is none %}
+ set(CONAN_DEF_{{conf}}_{{name}} "{{name}}")
+ {% else %}
+ set(CONAN_DEF_{{conf}}_{{name}} "{{name}}={{value}}")
+ {% endif %}
+ {% endfor %}
+ add_compile_definitions(
+ {%- for (conf, value) in values %}
+ $<$<CONFIG:{{conf}}>:${CONAN_DEF_{{conf}}_{{name}}}>
+ {%- endfor -%})
+ {% endfor %}
+ """)
+
+ def context(self):
+ return {"preprocessor_definitions": self._toolchain.preprocessor_definitions,
+ "preprocessor_definitions_config":
+ self._toolchain.preprocessor_definitions.configuration_types}
+
+
class ToolchainBlocks:
def __init__(self, conanfile, toolchain, items=None):
self._blocks = OrderedDict()
@@ -1159,7 +1287,7 @@ def __init__(self, conanfile, toolchain, items=None):
self._toolchain = toolchain
if items:
for name, block in items:
- self._blocks[name] = block(conanfile, toolchain)
+ self._blocks[name] = block(conanfile, toolchain, name)
def keys(self):
return self._blocks.keys()
@@ -1173,6 +1301,16 @@ def remove(self, name, *args):
del self._blocks[arg]
def select(self, name, *args):
+ """
+ keep the blocks provided as arguments, remove the others, except pre-existing "variables"
+ and "preprocessor", to not break behavior
+ """
+ self._conanfile.output.warning("CMakeToolchain.select is deprecated. Use blocks.enabled()"
+ " instead", warn_tag="deprecated")
+ to_keep = [name] + list(args) + ["variables", "preprocessor"]
+ self._blocks = OrderedDict((k, v) for k, v in self._blocks.items() if k in to_keep)
+
+ def enabled(self, name, *args):
"""
keep the blocks provided as arguments, remove the others
"""
@@ -1182,7 +1320,7 @@ def select(self, name, *args):
def __setitem__(self, name, block_type):
# Create a new class inheriting Block with the elements of the provided one
block_type = type('proxyUserBlock', (Block,), dict(block_type.__dict__))
- self._blocks[name] = block_type(self._conanfile, self._toolchain)
+ self._blocks[name] = block_type(self._conanfile, self._toolchain, name)
def __getitem__(self, name):
return self._blocks[name]
diff --git a/conan/tools/cmake/toolchain/toolchain.py b/conan/tools/cmake/toolchain/toolchain.py
index 0692751eb94..6d834ec9b24 100644
--- a/conan/tools/cmake/toolchain/toolchain.py
+++ b/conan/tools/cmake/toolchain/toolchain.py
@@ -9,11 +9,12 @@
from conan.tools.build import use_win_mingw
from conan.tools.cmake.presets import write_cmake_presets
from conan.tools.cmake.toolchain import CONAN_TOOLCHAIN_FILENAME
-from conan.tools.cmake.toolchain.blocks import ExtraVariablesBlock, ToolchainBlocks, UserToolchain, GenericSystemBlock, \
+from conan.tools.cmake.toolchain.blocks import ExtraVariablesBlock, ToolchainBlocks, UserToolchain, \
+ GenericSystemBlock, \
AndroidSystemBlock, AppleSystemBlock, FPicBlock, ArchitectureBlock, GLibCXXBlock, VSRuntimeBlock, \
CppStdBlock, ParallelBlock, CMakeFlagsInitBlock, TryCompileBlock, FindFiles, PkgConfigBlock, \
SkipRPath, SharedLibBock, OutputDirsBlock, ExtraFlagsBlock, CompilersBlock, LinkerScriptsBlock, \
- VSDebuggerEnvironment
+ VSDebuggerEnvironment, VariablesBlock, PreprocessorBlock
from conan.tools.cmake.utils import is_multi_configuration
from conan.tools.env import VirtualBuildEnv, VirtualRunEnv
from conan.tools.intel import IntelCC
@@ -56,39 +57,18 @@ def quote_preprocessor_strings(self):
data[key] = str(var).replace('"', '\\"')
-class CMakeToolchain(object):
+class CMakeToolchain:
filename = CONAN_TOOLCHAIN_FILENAME
- # TODO: Clean this macro, do it explicitly for variables
- _template = textwrap.dedent("""
- {% macro iterate_configs(var_config, action) %}
- {% for it, values in var_config.items() %}
- {% set genexpr = namespace(str='') %}
- {% for conf, value in values -%}
- set(CONAN_DEF_{{ conf }}{{ it }} "{{ value }}")
- {% endfor %}
- {% for conf, value in values -%}
- {% set genexpr.str = genexpr.str +
- '$<IF:$<CONFIG:' + conf + '>,${CONAN_DEF_' + conf|string + it|string + '},' %}
- {% if loop.last %}{% set genexpr.str = genexpr.str + '""' -%}{%- endif -%}
- {% endfor %}
- {% for i in range(values|count) %}{% set genexpr.str = genexpr.str + '>' %}
- {% endfor %}
- set({{ it }} {{ genexpr.str }} CACHE STRING
- "Variable {{ it }} conan-toolchain defined")
- {% endfor %}
- {% endmacro %}
-
+ _template = textwrap.dedent("""\
# Conan automatically generated toolchain file
# DO NOT EDIT MANUALLY, it will be overwritten
# Avoid including toolchain file several times (bad if appending to variables like
# CMAKE_CXX_FLAGS. See https://github.com/android/ndk/issues/323
include_guard()
-
message(STATUS "Using Conan toolchain: ${CMAKE_CURRENT_LIST_FILE}")
-
if(${CMAKE_VERSION} VERSION_LESS "3.15")
message(FATAL_ERROR "The 'CMakeToolchain' generator only works with CMake >= 3.15")
endif()
@@ -97,41 +77,6 @@ class CMakeToolchain(object):
{{ conan_block }}
{% endfor %}
- # Variables
- {% for it, value in variables.items() %}
- {% if value is boolean %}
- set({{ it }} {{ "ON" if value else "OFF"}} CACHE BOOL "Variable {{ it }} conan-toolchain defined")
- {% else %}
- set({{ it }} "{{ value }}" CACHE STRING "Variable {{ it }} conan-toolchain defined")
- {% endif %}
- {% endfor %}
- # Variables per configuration
- {{ iterate_configs(variables_config, action='set') }}
-
- # Preprocessor definitions
- {% for it, value in preprocessor_definitions.items() %}
- {% if value is none %}
- add_compile_definitions("{{ it }}")
- {% else %}
- add_compile_definitions("{{ it }}={{ value }}")
- {% endif %}
- {% endfor %}
- # Preprocessor definitions per configuration
- {% for name, values in preprocessor_definitions_config.items() %}
- {%- for (conf, value) in values %}
- {% if value is none %}
- set(CONAN_DEF_{{conf}}_{{name}} "{{name}}")
- {% else %}
- set(CONAN_DEF_{{conf}}_{{name}} "{{name}}={{value}}")
- {% endif %}
- {% endfor %}
- add_compile_definitions(
- {%- for (conf, value) in values %}
- $<$<CONFIG:{{conf}}>:${CONAN_DEF_{{conf}}_{{name}}}>
- {%- endfor -%})
- {% endfor %}
-
-
if(CMAKE_POLICY_DEFAULT_CMP0091) # Avoid unused and not-initialized warnings
endif()
""")
@@ -171,7 +116,9 @@ def __init__(self, conanfile, generator=None):
("pkg_config", PkgConfigBlock),
("rpath", SkipRPath),
("shared", SharedLibBock),
- ("output_dirs", OutputDirsBlock)])
+ ("output_dirs", OutputDirsBlock),
+ ("variables", VariablesBlock),
+ ("preprocessor", PreprocessorBlock)])
# Set the CMAKE_MODULE_PATH and CMAKE_PREFIX_PATH to the deps .builddirs
self.find_builddirs = True
@@ -188,10 +135,7 @@ def _context(self):
blocks = self.blocks.process_blocks()
ctxt_toolchain = {
- "variables": self.variables,
- "variables_config": self.variables.configuration_types,
- "preprocessor_definitions": self.preprocessor_definitions,
- "preprocessor_definitions_config": self.preprocessor_definitions.configuration_types,
+
"conan_blocks": blocks
}
| diff --git a/test/unittests/tools/cmake/test_cmaketoolchain.py b/test/unittests/tools/cmake/test_cmaketoolchain.py
index 3d66adadaa6..8ba5ff7f03b 100644
--- a/test/unittests/tools/cmake/test_cmaketoolchain.py
+++ b/test/unittests/tools/cmake/test_cmaketoolchain.py
@@ -58,10 +58,16 @@ def test_remove(conanfile):
assert "_CMAKE_IN_TRY_COMPILE" in content
-def test_filter(conanfile):
+def test_select_blocks(conanfile):
toolchain = CMakeToolchain(conanfile)
toolchain.blocks.select("generic_system")
content = toolchain.content
+ assert "########## 'generic_system' block #############" in content
+ assert "########## 'cmake_flags_init' block #############" not in content
+ assert "########## 'libcxx' block #############" not in content
+ # These are not removed by default, to not break behavior
+ assert "########## 'variables' block #############" in content
+ assert "########## 'preprocessor' block #############" in content
assert 'CMAKE_SYSTEM_NAME' in content
assert "CMAKE_CXX_FLAGS_INIT" not in content
assert "_CMAKE_IN_TRY_COMPILE" not in content
@@ -70,10 +76,24 @@ def test_filter(conanfile):
toolchain = CMakeToolchain(conanfile)
toolchain.blocks.select("generic_system", "cmake_flags_init")
content = toolchain.content
+ assert "########## 'generic_system' block #############" in content
+ assert "########## 'cmake_flags_init' block #############" in content
+ assert "########## 'libcxx' block #############" not in content
+ # These are not removed by default, to not break behavior
+ assert "########## 'variables' block #############" in content
+ assert "########## 'preprocessor' block #############" in content
assert 'CMAKE_SYSTEM_NAME' in content
assert "CMAKE_CXX_FLAGS_INIT" in content
assert "_CMAKE_IN_TRY_COMPILE" not in content
+ # remove multiple
+ toolchain = CMakeToolchain(conanfile)
+ toolchain.blocks.enabled("generic_system")
+ content = toolchain.content
+ assert "########## 'generic_system' block #############" in content
+ assert "########## 'variables' block #############" not in content
+ assert "########## 'preprocessor' block #############" not in content
+
def test_dict_keys(conanfile):
toolchain = CMakeToolchain(conanfile)
| [
{
"components": [
{
"doc": "",
"lines": [
1208,
1245
],
"name": "VariablesBlock",
"signature": "class VariablesBlock(Block): @property",
"type": "class"
},
{
"doc": "",
"lines": [
1210,
1211... | [
"test/unittests/tools/cmake/test_cmaketoolchain.py::test_select_blocks"
] | [
"test/unittests/tools/cmake/test_cmaketoolchain.py::test_cmake_toolchain",
"test/unittests/tools/cmake/test_cmaketoolchain.py::test_remove",
"test/unittests/tools/cmake/test_cmaketoolchain.py::test_dict_keys",
"test/unittests/tools/cmake/test_cmaketoolchain.py::test_template_remove",
"test/unittests/tools/c... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
CMakeToolchain refactor
Changelog: Omit
Docs: Omit
This had some level of risk of breaking:
- If users are ``select()`` selecting blocks, but count on the variables + preprocessor definitions to be there. I have explicitly excluded the new "variables" and "preprocessor" blocks to be filtered out by ``select()``, they won't and will need explicit ``.remove()`` them if desired, or use the new ``keep()`` method that supersedes ``select()``
Refactors:
- Adding automatically a header for every block with its name
- Adding explanation to every block about the inputs and definitions
- Moved some global code in the toolchain to its own dedicated blocks
- Added some more ``message()`` information when Conan define values in the toolchain
- Normalizing the blank lines
- Some minor PEP style fixes
The goal is to make the generated file more friendly to read, with more hints of what can be configured, and also to prepare the toolchain for a better customization and selection of what blocks to use.
----------
</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/toolchain/blocks.py]
(definition of VariablesBlock:)
class VariablesBlock(Block): @property
(definition of VariablesBlock.template:)
def template(self):
(definition of VariablesBlock.context:)
def context(self):
(definition of PreprocessorBlock:)
class PreprocessorBlock(Block): @property
(definition of PreprocessorBlock.template:)
def template(self):
(definition of PreprocessorBlock.context:)
def context(self):
(definition of ToolchainBlocks.enabled:)
def enabled(self, name, *args):
"""keep the blocks provided as arguments, remove the others"""
[end of new definitions in conan/tools/cmake/toolchain/blocks.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 | ||
googleapis__python-aiplatform-3970 | 3,970 | googleapis/python-aiplatform | null | 380c9d973480961c82ad22b4b298ce31c965272b | 2024-06-18T20:48:25Z | diff --git a/samples/model-builder/feature_store/create_feature_sample.py b/samples/model-builder/feature_store/create_feature_sample.py
new file mode 100644
index 0000000000..a7198876bd
--- /dev/null
+++ b/samples/model-builder/feature_store/create_feature_sample.py
@@ -0,0 +1,35 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+# [START aiplatform_sdk_create_feature_sample]
+
+from google.cloud import aiplatform
+from vertexai.resources.preview import feature_store
+
+
+def create_feature_sample(
+ project: str,
+ location: str,
+ feature_group_id: str,
+ feature_id: str,
+):
+ aiplatform.init(project=project, location=location)
+ feature_group = feature_store.FeatureGroup.create(
+ feature_group_id
+ )
+ feature = feature_group.create_feature(feature_id)
+ return feature
+
+
+# [END aiplatform_sdk_create_feature_sample]
| diff --git a/samples/model-builder/conftest.py b/samples/model-builder/conftest.py
index c49a76a491..6c4b7db84c 100644
--- a/samples/model-builder/conftest.py
+++ b/samples/model-builder/conftest.py
@@ -731,6 +731,21 @@ def mock_create_feature_group(mock_feature_group):
yield mock_create_feature_group
+@pytest.fixture
+def mock_registry_feature():
+ mock = MagicMock(preview_resources.Feature)
+ yield mock
+
+
+@pytest.fixture
+def mock_create_registry_feature(mock_feature_group, mock_registry_feature):
+ with patch.object(
+ mock_feature_group, "create_feature"
+ ) as mock_create_registry_feature:
+ mock_create_registry_feature.return_value = mock_registry_feature
+ yield mock_create_registry_feature
+
+
@pytest.fixture
def mock_create_optimized_private_online_store(mock_feature_online_store):
with patch.object(
diff --git a/samples/model-builder/feature_store/create_registry_feature_sample_test.py b/samples/model-builder/feature_store/create_registry_feature_sample_test.py
new file mode 100644
index 0000000000..e74e021a4a
--- /dev/null
+++ b/samples/model-builder/feature_store/create_registry_feature_sample_test.py
@@ -0,0 +1,40 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+from feature_store import create_feature_sample
+
+import test_constants as constants
+
+
+def test_create_feature_sample(
+ mock_sdk_init, mock_create_registry_feature, mock_create_feature_group
+):
+ create_feature_sample.create_feature_sample(
+ project=constants.PROJECT,
+ location=constants.LOCATION,
+ feature_group_id=constants.FEATURE_GROUP_ID,
+ feature_id=constants.REGISTRY_FEATURE_ID,
+ )
+
+ mock_sdk_init.assert_called_once_with(
+ project=constants.PROJECT, location=constants.LOCATION
+ )
+
+ mock_create_feature_group.assert_called_once_with(
+ constants.FEATURE_GROUP_ID
+ )
+
+ mock_create_registry_feature.assert_called_once_with(
+ constants.REGISTRY_FEATURE_ID
+ )
diff --git a/samples/model-builder/test_constants.py b/samples/model-builder/test_constants.py
index fd32f29f48..179d6eb82b 100644
--- a/samples/model-builder/test_constants.py
+++ b/samples/model-builder/test_constants.py
@@ -274,6 +274,7 @@
)
)
FEATURE_GROUP_ID = "sample_feature_group"
+REGISTRY_FEATURE_ID = "sample_feature"
PROJECT_ALLOWLISTED = ["test-project"]
TABULAR_TARGET_COLUMN = "target_column"
| [
{
"components": [
{
"doc": "",
"lines": [
21,
32
],
"name": "create_feature_sample",
"signature": "def create_feature_sample( project: str, location: str, feature_group_id: str, feature_id: str, ):",
"type": "function"
}
],
... | [
"samples/model-builder/feature_store/create_registry_feature_sample_test.py::test_create_feature_sample"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: sample code for Vertex AI Feature Store
feat: sample code for Vertex AI Feature Store
----------
</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/feature_store/create_feature_sample.py]
(definition of create_feature_sample:)
def create_feature_sample( project: str, location: str, feature_group_id: str, feature_id: str, ):
[end of new definitions in samples/model-builder/feature_store/create_feature_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 | ||
deepset-ai__haystack-7888 | 7,888 | deepset-ai/haystack | null | 28902c4c65b30b10ccf19de64ddf34145fed18d8 | 2024-06-18T18:24:20Z | diff --git a/haystack/document_stores/in_memory/document_store.py b/haystack/document_stores/in_memory/document_store.py
index 5ff6cb1fe6..4fd10e1cd1 100644
--- a/haystack/document_stores/in_memory/document_store.py
+++ b/haystack/document_stores/in_memory/document_store.py
@@ -2,11 +2,13 @@
#
# SPDX-License-Identifier: Apache-2.0
+import json
import math
import re
import uuid
from collections import Counter
from dataclasses import dataclass
+from pathlib import Path
from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple
import numpy as np
@@ -339,6 +341,42 @@ def from_dict(cls, data: Dict[str, Any]) -> "InMemoryDocumentStore":
"""
return default_from_dict(cls, data)
+ def save_to_disk(self, path: str) -> None:
+ """
+ Write the database and its' data to disk as a JSON file.
+
+ :param path: The path to the JSON file.
+ """
+ data: Dict[str, Any] = self.to_dict()
+ data["documents"] = [doc.to_dict(flatten=False) for doc in self.storage.values()]
+ with open(path, "w") as f:
+ json.dump(data, f)
+
+ @classmethod
+ def load_from_disk(cls, path: str) -> "InMemoryDocumentStore":
+ """
+ Load the database and its' data from disk as a JSON file.
+
+ :param path: The path to the JSON file.
+ :returns: The loaded InMemoryDocumentStore.
+ """
+ if Path(path).exists():
+ try:
+ with open(path, "r") as f:
+ data = json.load(f)
+ except Exception as e:
+ raise Exception(f"Error loading InMemoryDocumentStore from disk. error: {e}")
+
+ documents = data.pop("documents")
+ cls_object = default_from_dict(cls, data)
+ cls_object.write_documents(
+ documents=[Document(**doc) for doc in documents], policy=DuplicatePolicy.OVERWRITE
+ )
+ return cls_object
+
+ else:
+ raise FileNotFoundError(f"File {path} not found.")
+
def count_documents(self) -> int:
"""
Returns the number of how many documents are present in the DocumentStore.
diff --git a/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml b/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml
new file mode 100644
index 0000000000..48e3c8e427
--- /dev/null
+++ b/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml
@@ -0,0 +1,4 @@
+---
+enhancements:
+ - |
+ Added serialization methods save_to_disk and write_to_disk to InMemoryDocumentStore.
| diff --git a/test/document_stores/test_in_memory.py b/test/document_stores/test_in_memory.py
index 2a8679502b..8b8ed0e5fa 100644
--- a/test/document_stores/test_in_memory.py
+++ b/test/document_stores/test_in_memory.py
@@ -6,6 +6,7 @@
import pandas as pd
import pytest
+import tempfile
from haystack import Document
from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumentError
@@ -18,6 +19,11 @@ class TestMemoryDocumentStore(DocumentStoreBaseTests): # pylint: disable=R0904
Test InMemoryDocumentStore's specific features
"""
+ @pytest.fixture
+ def tmp_dir(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ yield tmp_dir
+
@pytest.fixture
def document_store(self) -> InMemoryDocumentStore:
return InMemoryDocumentStore(bm25_algorithm="BM25L")
@@ -74,6 +80,18 @@ def test_from_dict(self, mock_regex):
assert store.bm25_parameters == {"key": "value"}
assert store.index == "my_cool_index"
+ def test_save_to_disk_and_load_from_disk(self, tmp_dir: str):
+ docs = [Document(content="Hello world"), Document(content="Haystack supports multiple languages")]
+ document_store = InMemoryDocumentStore()
+ document_store.write_documents(docs)
+ tmp_dir = tmp_dir + "/document_store.json"
+ document_store.save_to_disk(tmp_dir)
+ document_store_loaded = InMemoryDocumentStore.load_from_disk(tmp_dir)
+
+ assert document_store_loaded.count_documents() == 2
+ assert list(document_store_loaded.storage.values()) == docs
+ assert document_store_loaded.to_dict() == document_store.to_dict()
+
def test_invalid_bm25_algorithm(self):
with pytest.raises(ValueError, match="BM25 algorithm 'invalid' is not supported"):
InMemoryDocumentStore(bm25_algorithm="invalid")
| diff --git a/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml b/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml
new file mode 100644
index 0000000000..48e3c8e427
--- /dev/null
+++ b/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml
@@ -0,0 +1,4 @@
+---
+enhancements:
+ - |
+ Added serialization methods save_to_disk and write_to_disk to InMemoryDocumentStore.
| [
{
"components": [
{
"doc": "Write the database and its' data to disk as a JSON file.\n\n:param path: The path to the JSON file.",
"lines": [
344,
353
],
"name": "InMemoryDocumentStore.save_to_disk",
"signature": "def save_to_disk(self, path: str)... | [
"test/document_stores/test_in_memory.py::TestMemoryDocumentStore::test_save_to_disk_and_load_from_disk"
] | [
"[",
"test/document_stores/test_in_memory.py::TestMemoryDocumentStore::test_no_filters",
"test/document_stores/test_in_memory.py::TestMemoryDocumentStore::test_comparison_equal",
"test/document_stores/test_in_memory.py::TestMemoryDocumentStore::test_comparison_equal_with_dataframe",
"test/document_stores/te... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: InMemoryDocumentStore serialization
### Related Issues
- fixes #7887
### Proposed Changes:
<!--- In case of a bug: Describe what caused the issue and how you solved it -->
<!--- In case of a feature: Describe what did you add and how it works -->
Added two `save_to_disk` and `load_from_disk` functions.
### How did you test it?
Added a test `test_save_to_disk_and_load_from_disk`
### Notes for the reviewer
The test has an issue due to `cls.from_dict` methods somehow caching `InMemoryDocumentStore.values()`. I added an overwrite policy to avoid this but it is not the cleanest way. Not sure what is happening.
### 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/document_stores/in_memory/document_store.py]
(definition of InMemoryDocumentStore.save_to_disk:)
def save_to_disk(self, path: str) -> None:
"""Write the database and its' data to disk as a JSON file.
:param path: The path to the JSON file."""
(definition of InMemoryDocumentStore.load_from_disk:)
def load_from_disk(cls, path: str) -> "InMemoryDocumentStore":
"""Load the database and its' data from disk as a JSON file.
:param path: The path to the JSON file.
:returns: The loaded InMemoryDocumentStore."""
[end of new definitions in haystack/document_stores/in_memory/document_store.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>
feat: implement serialization for `InMemoryDocumentStore`
**Is your feature request related to a problem? Please describe.**
`InMemoryDocumentStore` is really nice for showcasing demos and it is relatively easy to implement a `to_disk` and `from_disk` method to make this easy. I wrote something custom and easy.
**Describe the solution you'd like**
```python
# Copyright 2024-present, David Berenstein, Inc.
#
# 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.
import json
from pathlib import Path
from typing import Any, Dict
from haystack import Document
from haystack.document_stores.in_memory import InMemoryDocumentStore
class Database(InMemoryDocumentStore):
def to_disk(self, path: str):
"""Write the database and its' data to disk as a JSON file."""
data: Dict[str, Any] = self.to_dict()
data["documents"] = [doc.to_dict(flatten=False) for doc in self.storage.values()]
with open(path, "w") as f:
json.dump(data, f)
@classmethod
def from_disk(cls, path: str) -> "Database":
"""Load the database and its' data from disk as a JSON file."""
if Path(path).exists():
try:
with open(path, "r") as f:
data = json.load(f)
cls_object = cls.from_dict(data)
cls_object.write_documents([Document(**doc) for doc in data["documents"]])
return cls_object
except Exception as e:
return cls()
else:
return cls()
```
**Describe alternatives you've considered**
N.A.
**Additional context**
N.A.
----------
Would love to work on a potential PR too.
@davidberenstein1957 that would be great!
This methods could be added directly to `InMemoryDocumentStore` really, no need for a wrapper. 😁
I would be a bit more specific and call them `save_to_disk` and `load_to_disk` maybe. 🤔
> @davidberenstein1957 that would be great!
>
> This methods could be added directly to `InMemoryDocumentStore` really, no need for a wrapper. 😁
>
> I would be a bit more specific and call them `save_to_disk` and `load_to_disk` maybe. 🤔
Yes it was an actual copy-paste from code I was using internally.
--------------------
</issues> | f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967 |
prometheus__client_python-1040 | 1,040 | prometheus/client_python | null | 09a5ae30602a7a81f6174dae4ba08b93ee7feed2 | 2024-06-18T15:59:01Z | diff --git a/prometheus_client/core.py b/prometheus_client/core.py
index ad3a4542..60f93ce1 100644
--- a/prometheus_client/core.py
+++ b/prometheus_client/core.py
@@ -5,9 +5,10 @@
SummaryMetricFamily, UnknownMetricFamily, UntypedMetricFamily,
)
from .registry import CollectorRegistry, REGISTRY
-from .samples import Exemplar, Sample, Timestamp
+from .samples import BucketSpan, Exemplar, NativeHistogram, Sample, Timestamp
__all__ = (
+ 'BucketSpan',
'CollectorRegistry',
'Counter',
'CounterMetricFamily',
@@ -21,6 +22,7 @@
'Info',
'InfoMetricFamily',
'Metric',
+ 'NativeHistogram',
'REGISTRY',
'Sample',
'StateSetMetricFamily',
diff --git a/prometheus_client/metrics.py b/prometheus_client/metrics.py
index af512115..03e1e66a 100644
--- a/prometheus_client/metrics.py
+++ b/prometheus_client/metrics.py
@@ -111,8 +111,8 @@ def describe(self) -> Iterable[Metric]:
def collect(self) -> Iterable[Metric]:
metric = self._get_metric()
- for suffix, labels, value, timestamp, exemplar in self._samples():
- metric.add_sample(self._name + suffix, labels, value, timestamp, exemplar)
+ for suffix, labels, value, timestamp, exemplar, native_histogram_value in self._samples():
+ metric.add_sample(self._name + suffix, labels, value, timestamp, exemplar, native_histogram_value)
return [metric]
def __str__(self) -> str:
@@ -246,8 +246,8 @@ def _multi_samples(self) -> Iterable[Sample]:
metrics = self._metrics.copy()
for labels, metric in metrics.items():
series_labels = list(zip(self._labelnames, labels))
- for suffix, sample_labels, value, timestamp, exemplar in metric._samples():
- yield Sample(suffix, dict(series_labels + list(sample_labels.items())), value, timestamp, exemplar)
+ for suffix, sample_labels, value, timestamp, exemplar, native_histogram_value in metric._samples():
+ yield Sample(suffix, dict(series_labels + list(sample_labels.items())), value, timestamp, exemplar, native_histogram_value)
def _child_samples(self) -> Iterable[Sample]: # pragma: no cover
raise NotImplementedError('_child_samples() must be implemented by %r' % self)
diff --git a/prometheus_client/metrics_core.py b/prometheus_client/metrics_core.py
index 7226d920..19166e1d 100644
--- a/prometheus_client/metrics_core.py
+++ b/prometheus_client/metrics_core.py
@@ -1,7 +1,7 @@
import re
from typing import Dict, List, Optional, Sequence, Tuple, Union
-from .samples import Exemplar, Sample, Timestamp
+from .samples import Exemplar, NativeHistogram, Sample, Timestamp
METRIC_TYPES = (
'counter', 'gauge', 'summary', 'histogram',
@@ -36,11 +36,11 @@ def __init__(self, name: str, documentation: str, typ: str, unit: str = ''):
self.type: str = typ
self.samples: List[Sample] = []
- def add_sample(self, name: str, labels: Dict[str, str], value: float, timestamp: Optional[Union[Timestamp, float]] = None, exemplar: Optional[Exemplar] = None) -> None:
+ def add_sample(self, name: str, labels: Dict[str, str], value: float, timestamp: Optional[Union[Timestamp, float]] = None, exemplar: Optional[Exemplar] = None, native_histogram: Optional[NativeHistogram] = None) -> None:
"""Add a sample to the metric.
Internal-only, do not use."""
- self.samples.append(Sample(name, labels, value, timestamp, exemplar))
+ self.samples.append(Sample(name, labels, value, timestamp, exemplar, native_histogram))
def __eq__(self, other: object) -> bool:
return (isinstance(other, Metric)
@@ -284,7 +284,6 @@ def add_metric(self,
Sample(self.name + '_sum', dict(zip(self._labelnames, labels)), sum_value, timestamp))
-
class GaugeHistogramMetricFamily(Metric):
"""A single gauge histogram and its samples.
diff --git a/prometheus_client/multiprocess.py b/prometheus_client/multiprocess.py
index 7021b49a..2682190a 100644
--- a/prometheus_client/multiprocess.py
+++ b/prometheus_client/multiprocess.py
@@ -93,7 +93,7 @@ def _accumulate_metrics(metrics, accumulate):
buckets = defaultdict(lambda: defaultdict(float))
samples_setdefault = samples.setdefault
for s in metric.samples:
- name, labels, value, timestamp, exemplar = s
+ name, labels, value, timestamp, exemplar, native_histogram_value = s
if metric.type == 'gauge':
without_pid_key = (name, tuple(l for l in labels if l[0] != 'pid'))
if metric._multiprocess_mode in ('min', 'livemin'):
diff --git a/prometheus_client/openmetrics/exposition.py b/prometheus_client/openmetrics/exposition.py
index 26f3109f..1959847b 100644
--- a/prometheus_client/openmetrics/exposition.py
+++ b/prometheus_client/openmetrics/exposition.py
@@ -10,7 +10,9 @@
def _is_valid_exemplar_metric(metric, sample):
if metric.type == 'counter' and sample.name.endswith('_total'):
return True
- if metric.type in ('histogram', 'gaugehistogram') and sample.name.endswith('_bucket'):
+ if metric.type in ('gaugehistogram') and sample.name.endswith('_bucket'):
+ return True
+ if metric.type in ('histogram') and sample.name.endswith('_bucket') or sample.name == metric.name:
return True
return False
diff --git a/prometheus_client/openmetrics/parser.py b/prometheus_client/openmetrics/parser.py
index 6128a0d3..39a44dc2 100644
--- a/prometheus_client/openmetrics/parser.py
+++ b/prometheus_client/openmetrics/parser.py
@@ -6,7 +6,7 @@
import re
from ..metrics_core import Metric, METRIC_LABEL_NAME_RE
-from ..samples import Exemplar, Sample, Timestamp
+from ..samples import BucketSpan, Exemplar, NativeHistogram, Sample, Timestamp
from ..utils import floatToGoString
@@ -364,6 +364,99 @@ def _parse_remaining_text(text):
return val, ts, exemplar
+def _parse_nh_sample(text, suffixes):
+ labels_start = text.find("{")
+ # check if it's a native histogram with labels
+ re_nh_without_labels = re.compile(r'^[^{} ]+ {[^{}]+}$')
+ re_nh_with_labels = re.compile(r'[^{} ]+{[^{}]+} {[^{}]+}$')
+ if re_nh_with_labels.match(text):
+ nh_value_start = text.rindex("{")
+ labels_end = nh_value_start - 2
+ labelstext = text[labels_start + 1:labels_end]
+ labels = _parse_labels(labelstext)
+ name_end = labels_start
+ name = text[:name_end]
+ if name.endswith(suffixes):
+ raise ValueError("the sample name of a native histogram with labels should have no suffixes", name)
+ nh_value = text[nh_value_start:]
+ nat_hist_value = _parse_nh_struct(nh_value)
+ return Sample(name, labels, None, None, None, nat_hist_value)
+ # check if it's a native histogram
+ if re_nh_without_labels.match(text):
+ nh_value_start = labels_start
+ nh_value = text[nh_value_start:]
+ name_end = nh_value_start - 1
+ name = text[:name_end]
+ if name.endswith(suffixes):
+ raise ValueError("the sample name of a native histogram should have no suffixes", name)
+ nat_hist_value = _parse_nh_struct(nh_value)
+ return Sample(name, None, None, None, None, nat_hist_value)
+ else:
+ # it's not a native histogram
+ return
+
+
+def _parse_nh_struct(text):
+ pattern = r'(\w+):\s*([^,}]+)'
+
+ re_spans = re.compile(r'(positive_spans|negative_spans):\[(\d+:\d+,\d+:\d+)\]')
+ re_deltas = re.compile(r'(positive_deltas|negative_deltas):\[(-?\d+(?:,-?\d+)*)\]')
+
+ items = dict(re.findall(pattern, text))
+ spans = dict(re_spans.findall(text))
+ deltas = dict(re_deltas.findall(text))
+
+ count_value = int(items['count'])
+ sum_value = int(items['sum'])
+ schema = int(items['schema'])
+ zero_threshold = float(items['zero_threshold'])
+ zero_count = int(items['zero_count'])
+
+ try:
+ pos_spans_text = spans['positive_spans']
+ elems = pos_spans_text.split(',')
+ arg1 = [int(x) for x in elems[0].split(':')]
+ arg2 = [int(x) for x in elems[1].split(':')]
+ pos_spans = (BucketSpan(arg1[0], arg1[1]), BucketSpan(arg2[0], arg2[1]))
+ except KeyError:
+ pos_spans = None
+
+ try:
+ neg_spans_text = spans['negative_spans']
+ elems = neg_spans_text.split(',')
+ arg1 = [int(x) for x in elems[0].split(':')]
+ arg2 = [int(x) for x in elems[1].split(':')]
+ neg_spans = (BucketSpan(arg1[0], arg1[1]), BucketSpan(arg2[0], arg2[1]))
+ except KeyError:
+ neg_spans = None
+
+ try:
+ pos_deltas_text = deltas['positive_deltas']
+ elems = pos_deltas_text.split(',')
+ pos_deltas = tuple([int(x) for x in elems])
+ except KeyError:
+ pos_deltas = None
+
+ try:
+ neg_deltas_text = deltas['negative_deltas']
+ elems = neg_deltas_text.split(',')
+ neg_deltas = tuple([int(x) for x in elems])
+ except KeyError:
+ neg_deltas = None
+
+ return NativeHistogram(
+ count_value=count_value,
+ sum_value=sum_value,
+ schema=schema,
+ zero_threshold=zero_threshold,
+ zero_count=zero_count,
+ pos_spans=pos_spans,
+ neg_spans=neg_spans,
+ pos_deltas=pos_deltas,
+ neg_deltas=neg_deltas
+ )
+
+
def _group_for_sample(sample, name, typ):
if typ == 'info':
# We can't distinguish between groups for info metrics.
@@ -406,6 +499,8 @@ def do_checks():
for s in samples:
suffix = s.name[len(name):]
g = _group_for_sample(s, name, 'histogram')
+ if len(suffix) == 0:
+ continue
if g != group or s.timestamp != timestamp:
if group is not None:
do_checks()
@@ -486,6 +581,8 @@ def build_metric(name, documentation, typ, unit, samples):
metric.samples = samples
return metric
+ is_nh = False
+ typ = None
for line in fd:
if line[-1] == '\n':
line = line[:-1]
@@ -518,7 +615,7 @@ def build_metric(name, documentation, typ, unit, samples):
group_timestamp_samples = set()
samples = []
allowed_names = [parts[2]]
-
+
if parts[1] == 'HELP':
if documentation is not None:
raise ValueError("More than one HELP for metric: " + line)
@@ -537,8 +634,18 @@ def build_metric(name, documentation, typ, unit, samples):
else:
raise ValueError("Invalid line: " + line)
else:
- sample = _parse_sample(line)
- if sample.name not in allowed_names:
+ if typ == 'histogram':
+ # set to true to account for native histograms naming exceptions/sanitizing differences
+ is_nh = True
+ sample = _parse_nh_sample(line, tuple(type_suffixes['histogram']))
+ # It's not a native histogram
+ if sample is None:
+ is_nh = False
+ sample = _parse_sample(line)
+ else:
+ is_nh = False
+ sample = _parse_sample(line)
+ if sample.name not in allowed_names and not is_nh:
if name is not None:
yield build_metric(name, documentation, typ, unit, samples)
# Start an unknown metric.
@@ -570,26 +677,29 @@ def build_metric(name, documentation, typ, unit, samples):
or _isUncanonicalNumber(sample.labels['quantile']))):
raise ValueError("Invalid quantile label: " + line)
- g = tuple(sorted(_group_for_sample(sample, name, typ).items()))
- if group is not None and g != group and g in seen_groups:
- raise ValueError("Invalid metric grouping: " + line)
- if group is not None and g == group:
- if (sample.timestamp is None) != (group_timestamp is None):
- raise ValueError("Mix of timestamp presence within a group: " + line)
- if group_timestamp is not None and group_timestamp > sample.timestamp and typ != 'info':
- raise ValueError("Timestamps went backwards within a group: " + line)
+ if not is_nh:
+ g = tuple(sorted(_group_for_sample(sample, name, typ).items()))
+ if group is not None and g != group and g in seen_groups:
+ raise ValueError("Invalid metric grouping: " + line)
+ if group is not None and g == group:
+ if (sample.timestamp is None) != (group_timestamp is None):
+ raise ValueError("Mix of timestamp presence within a group: " + line)
+ if group_timestamp is not None and group_timestamp > sample.timestamp and typ != 'info':
+ raise ValueError("Timestamps went backwards within a group: " + line)
+ else:
+ group_timestamp_samples = set()
+
+ series_id = (sample.name, tuple(sorted(sample.labels.items())))
+ if sample.timestamp != group_timestamp or series_id not in group_timestamp_samples:
+ # Not a duplicate due to timestamp truncation.
+ samples.append(sample)
+ group_timestamp_samples.add(series_id)
+
+ group = g
+ group_timestamp = sample.timestamp
+ seen_groups.add(g)
else:
- group_timestamp_samples = set()
-
- series_id = (sample.name, tuple(sorted(sample.labels.items())))
- if sample.timestamp != group_timestamp or series_id not in group_timestamp_samples:
- # Not a duplicate due to timestamp truncation.
samples.append(sample)
- group_timestamp_samples.add(series_id)
-
- group = g
- group_timestamp = sample.timestamp
- seen_groups.add(g)
if typ == 'stateset' and sample.value not in [0, 1]:
raise ValueError("Stateset samples can only have values zero and one: " + line)
@@ -606,7 +716,7 @@ def build_metric(name, documentation, typ, unit, samples):
(typ in ['histogram', 'gaugehistogram'] and sample.name.endswith('_bucket'))
or (typ in ['counter'] and sample.name.endswith('_total'))):
raise ValueError("Invalid line only histogram/gaugehistogram buckets and counters can have exemplars: " + line)
-
+
if name is not None:
yield build_metric(name, documentation, typ, unit, samples)
diff --git a/prometheus_client/samples.py b/prometheus_client/samples.py
index 53c47264..b57a5d48 100644
--- a/prometheus_client/samples.py
+++ b/prometheus_client/samples.py
@@ -1,4 +1,4 @@
-from typing import Dict, NamedTuple, Optional, Union
+from typing import Dict, NamedTuple, Optional, Sequence, Tuple, Union
class Timestamp:
@@ -34,6 +34,25 @@ def __lt__(self, other: "Timestamp") -> bool:
return self.nsec < other.nsec if self.sec == other.sec else self.sec < other.sec
+# BucketSpan is experimental and subject to change at any time.
+class BucketSpan(NamedTuple):
+ offset: int
+ length: int
+
+
+# NativeHistogram is experimental and subject to change at any time.
+class NativeHistogram(NamedTuple):
+ count_value: float
+ sum_value: float
+ schema: int
+ zero_threshold: float
+ zero_count: float
+ pos_spans: Optional[Tuple[BucketSpan, BucketSpan]] = None
+ neg_spans: Optional[Tuple[BucketSpan, BucketSpan]] = None
+ pos_deltas: Optional[Sequence[int]] = None
+ neg_deltas: Optional[Sequence[int]] = None
+
+
# Timestamp and exemplar are optional.
# Value can be an int or a float.
# Timestamp can be a float containing a unixtime in seconds,
@@ -51,3 +70,4 @@ class Sample(NamedTuple):
value: float
timestamp: Optional[Union[float, Timestamp]] = None
exemplar: Optional[Exemplar] = None
+ native_histogram: Optional[NativeHistogram] = None
| diff --git a/tests/openmetrics/test_parser.py b/tests/openmetrics/test_parser.py
index 937aef5c..dc5e9916 100644
--- a/tests/openmetrics/test_parser.py
+++ b/tests/openmetrics/test_parser.py
@@ -2,9 +2,9 @@
import unittest
from prometheus_client.core import (
- CollectorRegistry, CounterMetricFamily, Exemplar,
+ BucketSpan, CollectorRegistry, CounterMetricFamily, Exemplar,
GaugeHistogramMetricFamily, GaugeMetricFamily, HistogramMetricFamily,
- InfoMetricFamily, Metric, Sample, StateSetMetricFamily,
+ InfoMetricFamily, Metric, NativeHistogram, Sample, StateSetMetricFamily,
SummaryMetricFamily, Timestamp,
)
from prometheus_client.openmetrics.exposition import generate_latest
@@ -175,6 +175,80 @@ def test_histogram_exemplars(self):
Exemplar({"a": "2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"}, 4,
Timestamp(123, 0)))
self.assertEqual([hfm], list(families))
+
+ def test_native_histogram(self):
+ families = text_string_to_metric_families("""# TYPE nativehistogram histogram
+# HELP nativehistogram Is a basic example of a native histogram
+nativehistogram {count:24,sum:100,schema:0,zero_threshold:0.001,zero_count:4,positive_spans:[0:2,1:2],negative_spans:[0:2,1:2],positive_deltas:[2,1,-3,3],negative_deltas:[2,1,-2,3]}
+# EOF
+""")
+ families = list(families)
+
+ hfm = HistogramMetricFamily("nativehistogram", "Is a basic example of a native histogram")
+ hfm.add_sample("nativehistogram", None, None, None, None, NativeHistogram(24, 100, 0, 0.001, 4, (BucketSpan(0, 2), BucketSpan(1, 2)), (BucketSpan(0, 2), BucketSpan(1, 2)), (2, 1, -3, 3), (2, 1, -2, 3)))
+ self.assertEqual([hfm], families)
+
+ def test_native_histogram_with_labels(self):
+ families = text_string_to_metric_families("""# TYPE hist_w_labels histogram
+# HELP hist_w_labels Is a basic example of a native histogram with labels
+hist_w_labels{foo="bar",baz="qux"} {count:24,sum:100,schema:0,zero_threshold:0.001,zero_count:4,positive_spans:[0:2,1:2],negative_spans:[0:2,1:2],positive_deltas:[2,1,-3,3],negative_deltas:[2,1,-2,3]}
+# EOF
+""")
+ families = list(families)
+
+ hfm = HistogramMetricFamily("hist_w_labels", "Is a basic example of a native histogram with labels")
+ hfm.add_sample("hist_w_labels", {"foo": "bar", "baz": "qux"}, None, None, None, NativeHistogram(24, 100, 0, 0.001, 4, (BucketSpan(0, 2), BucketSpan(1, 2)), (BucketSpan(0, 2), BucketSpan(1, 2)), (2, 1, -3, 3), (2, 1, -2, 3)))
+ self.assertEqual([hfm], families)
+
+ def test_native_histogram_with_classic_histogram(self):
+ families = text_string_to_metric_families("""# TYPE hist_w_classic histogram
+# HELP hist_w_classic Is a basic example of a native histogram coexisting with a classic histogram
+hist_w_classic{foo="bar"} {count:24,sum:100,schema:0,zero_threshold:0.001,zero_count:4,positive_spans:[0:2,1:2],negative_spans:[0:2,1:2],positive_deltas:[2,1,-3,3],negative_deltas:[2,1,-2,3]}
+hist_w_classic_bucket{foo="bar",le="0.001"} 4
+hist_w_classic_bucket{foo="bar",le="+Inf"} 24
+hist_w_classic_count{foo="bar"} 24
+hist_w_classic_sum{foo="bar"} 100
+# EOF
+""")
+ families = list(families)
+
+ hfm = HistogramMetricFamily("hist_w_classic", "Is a basic example of a native histogram coexisting with a classic histogram")
+ hfm.add_sample("hist_w_classic", {"foo": "bar"}, None, None, None, NativeHistogram(24, 100, 0, 0.001, 4, (BucketSpan(0, 2), BucketSpan(1, 2)), (BucketSpan(0, 2), BucketSpan(1, 2)), (2, 1, -3, 3), (2, 1, -2, 3)))
+ hfm.add_sample("hist_w_classic_bucket", {"foo": "bar", "le": "0.001"}, 4.0, None, None, None)
+ hfm.add_sample("hist_w_classic_bucket", {"foo": "bar", "le": "+Inf"}, 24.0, None, None, None)
+ hfm.add_sample("hist_w_classic_count", {"foo": "bar"}, 24.0, None, None, None)
+ hfm.add_sample("hist_w_classic_sum", {"foo": "bar"}, 100.0, None, None, None)
+ self.assertEqual([hfm], families)
+
+ def test_native_plus_classic_histogram_two_labelsets(self):
+ families = text_string_to_metric_families("""# TYPE hist_w_classic_two_sets histogram
+# HELP hist_w_classic_two_sets Is an example of a native histogram plus a classic histogram with two label sets
+hist_w_classic_two_sets{foo="bar"} {count:24,sum:100,schema:0,zero_threshold:0.001,zero_count:4,positive_spans:[0:2,1:2],negative_spans:[0:2,1:2],positive_deltas:[2,1,-3,3],negative_deltas:[2,1,-2,3]}
+hist_w_classic_two_sets_bucket{foo="bar",le="0.001"} 4
+hist_w_classic_two_sets_bucket{foo="bar",le="+Inf"} 24
+hist_w_classic_two_sets_count{foo="bar"} 24
+hist_w_classic_two_sets_sum{foo="bar"} 100
+hist_w_classic_two_sets{foo="baz"} {count:24,sum:100,schema:0,zero_threshold:0.001,zero_count:4,positive_spans:[0:2,1:2],negative_spans:[0:2,1:2],positive_deltas:[2,1,-3,3],negative_deltas:[2,1,-2,3]}
+hist_w_classic_two_sets_bucket{foo="baz",le="0.001"} 4
+hist_w_classic_two_sets_bucket{foo="baz",le="+Inf"} 24
+hist_w_classic_two_sets_count{foo="baz"} 24
+hist_w_classic_two_sets_sum{foo="baz"} 100
+# EOF
+""")
+ families = list(families)
+
+ hfm = HistogramMetricFamily("hist_w_classic_two_sets", "Is an example of a native histogram plus a classic histogram with two label sets")
+ hfm.add_sample("hist_w_classic_two_sets", {"foo": "bar"}, None, None, None, NativeHistogram(24, 100, 0, 0.001, 4, (BucketSpan(0, 2), BucketSpan(1, 2)), (BucketSpan(0, 2), BucketSpan(1, 2)), (2, 1, -3, 3), (2, 1, -2, 3)))
+ hfm.add_sample("hist_w_classic_two_sets_bucket", {"foo": "bar", "le": "0.001"}, 4.0, None, None, None)
+ hfm.add_sample("hist_w_classic_two_sets_bucket", {"foo": "bar", "le": "+Inf"}, 24.0, None, None, None)
+ hfm.add_sample("hist_w_classic_two_sets_count", {"foo": "bar"}, 24.0, None, None, None)
+ hfm.add_sample("hist_w_classic_two_sets_sum", {"foo": "bar"}, 100.0, None, None, None)
+ hfm.add_sample("hist_w_classic_two_sets", {"foo": "baz"}, None, None, None, NativeHistogram(24, 100, 0, 0.001, 4, (BucketSpan(0, 2), BucketSpan(1, 2)), (BucketSpan(0, 2), BucketSpan(1, 2)), (2, 1, -3, 3), (2, 1, -2, 3)))
+ hfm.add_sample("hist_w_classic_two_sets_bucket", {"foo": "baz", "le": "0.001"}, 4.0, None, None, None)
+ hfm.add_sample("hist_w_classic_two_sets_bucket", {"foo": "baz", "le": "+Inf"}, 24.0, None, None, None)
+ hfm.add_sample("hist_w_classic_two_sets_count", {"foo": "baz"}, 24.0, None, None, None)
+ hfm.add_sample("hist_w_classic_two_sets_sum", {"foo": "baz"}, 100.0, None, None, None)
+ self.assertEqual([hfm], families)
def test_simple_gaugehistogram(self):
families = text_string_to_metric_families("""# TYPE a gaugehistogram
@@ -805,6 +879,7 @@ def test_invalid_input(self):
('# TYPE a histogram\na_bucket{le="+INF"} 0\n# EOF\n'),
('# TYPE a histogram\na_bucket{le="2"} 0\na_bucket{le="1"} 0\na_bucket{le="+Inf"} 0\n# EOF\n'),
('# TYPE a histogram\na_bucket{le="1"} 1\na_bucket{le="2"} 1\na_bucket{le="+Inf"} 0\n# EOF\n'),
+ ('# TYPE a histogram\na_bucket {} {}'),
# Bad grouping or ordering.
('# TYPE a histogram\na_sum{a="1"} 0\na_sum{a="2"} 0\na_count{a="1"} 0\n# EOF\n'),
('# TYPE a histogram\na_bucket{a="1",le="1"} 0\na_bucket{a="2",le="+Inf""} '
| [
{
"components": [
{
"doc": "",
"lines": [
367,
396
],
"name": "_parse_nh_sample",
"signature": "def _parse_nh_sample(text, suffixes):",
"type": "function"
},
{
"doc": "",
"lines": [
399,
456... | [
"tests/openmetrics/test_parser.py::TestParse::test_counter_exemplars",
"tests/openmetrics/test_parser.py::TestParse::test_counter_exemplars_empty_brackets",
"tests/openmetrics/test_parser.py::TestParse::test_duplicate_timestamps",
"tests/openmetrics/test_parser.py::TestParse::test_empty_brackets",
"tests/op... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add support for native histograms in OM parser
This PR adds an OM parser for native histograms, as a first step towards the implementation of the following proposal https://github.com/prometheus/proposals/pull/32 . The next steps (as far as this repo is concerned) would be the OM exposition and then obviously the implementation of native histograms generation/writing logic.
----------
</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 prometheus_client/openmetrics/parser.py]
(definition of _parse_nh_sample:)
def _parse_nh_sample(text, suffixes):
(definition of _parse_nh_struct:)
def _parse_nh_struct(text):
[end of new definitions in prometheus_client/openmetrics/parser.py]
[start of new definitions in prometheus_client/samples.py]
(definition of BucketSpan:)
class BucketSpan(NamedTuple):
(definition of NativeHistogram:)
class NativeHistogram(NamedTuple):
[end of new definitions in prometheus_client/samples.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>> | 09a5ae30602a7a81f6174dae4ba08b93ee7feed2 | ||
googleapis__python-aiplatform-3962 | 3,962 | googleapis/python-aiplatform | null | f6b6deed2a3973ed684898d30e209af4291b8f3a | 2024-06-17T23:22:56Z | diff --git a/samples/model-builder/feature_store/create_feature_group_sample.py b/samples/model-builder/feature_store/create_feature_group_sample.py
new file mode 100644
index 0000000000..7365b60cff
--- /dev/null
+++ b/samples/model-builder/feature_store/create_feature_group_sample.py
@@ -0,0 +1,33 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+# [START aiplatform_sdk_create_feature_group_sample]
+
+from google.cloud import aiplatform
+from vertexai.resources.preview import feature_store
+
+
+def create_feature_group_sample(
+ project: str,
+ location: str,
+ feature_group_id: str,
+):
+ aiplatform.init(project=project, location=location)
+ fg = feature_store.FeatureGroup.create(
+ feature_group_id
+ )
+ return fg
+
+
+# [END aiplatform_sdk_create_feature_group_sample]
| diff --git a/samples/model-builder/conftest.py b/samples/model-builder/conftest.py
index 16d9057046..55facdb363 100644
--- a/samples/model-builder/conftest.py
+++ b/samples/model-builder/conftest.py
@@ -716,6 +716,21 @@ def mock_create_optimized_public_online_store(mock_feature_online_store):
yield mock_create_optimized_store
+@pytest.fixture
+def mock_feature_group():
+ mock = MagicMock(preview_resources.FeatureGroup)
+ yield mock
+
+
+@pytest.fixture
+def mock_create_feature_group(mock_feature_group):
+ with patch.object(
+ preview_resources.FeatureGroup, "create"
+ ) as mock_create_feature_group:
+ mock_create_feature_group.return_value = mock_feature_group
+ yield mock_create_feature_group
+
+
@pytest.fixture
def mock_create_optimized_private_online_store(mock_feature_online_store):
with patch.object(
diff --git a/samples/model-builder/feature_store/create_feature_group_sample_test.py b/samples/model-builder/feature_store/create_feature_group_sample_test.py
new file mode 100644
index 0000000000..9beb6c0816
--- /dev/null
+++ b/samples/model-builder/feature_store/create_feature_group_sample_test.py
@@ -0,0 +1,35 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+from feature_store import create_feature_group_sample
+
+import test_constants as constants
+
+
+def test_create_feature_group_sample(
+ mock_sdk_init, mock_create_feature_group
+):
+ create_feature_group_sample.create_feature_group_sample(
+ project=constants.PROJECT,
+ location=constants.LOCATION,
+ feature_group_id=constants.FEATURE_GROUP_ID,
+ )
+
+ mock_sdk_init.assert_called_once_with(
+ project=constants.PROJECT, location=constants.LOCATION
+ )
+
+ mock_create_feature_group.assert_called_once_with(
+ constants.FEATURE_GROUP_ID
+ )
diff --git a/samples/model-builder/test_constants.py b/samples/model-builder/test_constants.py
index 3571e8d9cc..e17baa43a1 100644
--- a/samples/model-builder/test_constants.py
+++ b/samples/model-builder/test_constants.py
@@ -254,6 +254,7 @@
# Feature online store constants
FEATURE_ONLINE_STORE_ID = "sample_feature_online_store"
+FEATURE_GROUP_ID = "sample_feature_group"
PROJECT_ALLOWLISTED = ["test-project"]
TABULAR_TARGET_COLUMN = "target_column"
| [
{
"components": [
{
"doc": "",
"lines": [
21,
30
],
"name": "create_feature_group_sample",
"signature": "def create_feature_group_sample( project: str, location: str, feature_group_id: str, ):",
"type": "function"
}
],
"file... | [
"samples/model-builder/feature_store/create_feature_group_sample_test.py::test_create_feature_group_sample"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: sample code for Vertex AI Feature Store
feat: sample code for Vertex AI Feature Store
----------
</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/feature_store/create_feature_group_sample.py]
(definition of create_feature_group_sample:)
def create_feature_group_sample( project: str, location: str, feature_group_id: str, ):
[end of new definitions in samples/model-builder/feature_store/create_feature_group_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-3666 | 3,666 | tobymao/sqlglot | null | 468123e4b7612287e128529de62f3a88f4e1d579 | 2024-06-17T15:22:29Z | diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py
index 9ceeacc5a5..cc3e5150ce 100644
--- a/sqlglot/dialects/bigquery.py
+++ b/sqlglot/dialects/bigquery.py
@@ -13,7 +13,6 @@
date_add_interval_sql,
datestrtodate_sql,
build_formatted_time,
- build_timestamp_from_parts,
filter_array_using_unnest,
if_sql,
inline_array_unless_query,
@@ -202,10 +201,17 @@ def _unix_to_time_sql(self: BigQuery.Generator, expression: exp.UnixToTime) -> s
def _build_time(args: t.List) -> exp.Func:
if len(args) == 1:
return exp.TsOrDsToTime(this=args[0])
- if len(args) == 3:
- return exp.TimeFromParts.from_arg_list(args)
+ if len(args) == 2:
+ return exp.Time.from_arg_list(args)
+ return exp.TimeFromParts.from_arg_list(args)
- return exp.Anonymous(this="TIME", expressions=args)
+
+def _build_datetime(args: t.List) -> exp.Func:
+ if len(args) == 1:
+ return exp.TsOrDsToTimestamp.from_arg_list(args)
+ if len(args) == 2:
+ return exp.Datetime.from_arg_list(args)
+ return exp.TimestampFromParts.from_arg_list(args)
class BigQuery(Dialect):
@@ -323,7 +329,7 @@ class Parser(parser.Parser):
unit=exp.Literal.string(str(seq_get(args, 1))),
this=seq_get(args, 0),
),
- "DATETIME": build_timestamp_from_parts,
+ "DATETIME": _build_datetime,
"DATETIME_ADD": build_date_delta_with_interval(exp.DatetimeAdd),
"DATETIME_SUB": build_date_delta_with_interval(exp.DatetimeSub),
"DIV": binary_from_function(exp.IntDiv),
@@ -661,6 +667,7 @@ class Generator(generator.Generator):
exp.TsOrDsAdd: _ts_or_ds_add_sql,
exp.TsOrDsDiff: _ts_or_ds_diff_sql,
exp.TsOrDsToTime: rename_func("TIME"),
+ exp.TsOrDsToTimestamp: rename_func("DATETIME"),
exp.Unhex: rename_func("FROM_HEX"),
exp.UnixDate: rename_func("UNIX_DATE"),
exp.UnixToTime: _unix_to_time_sql,
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index 8e11050db6..4497430e4b 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -803,19 +803,45 @@ def _timestamptrunc_sql(self: Generator, expression: exp.TimestampTrunc) -> str:
def no_timestamp_sql(self: Generator, expression: exp.Timestamp) -> str:
- if not expression.expression:
+ zone = expression.args.get("zone")
+ if not zone:
from sqlglot.optimizer.annotate_types import annotate_types
target_type = annotate_types(expression).type or exp.DataType.Type.TIMESTAMP
return self.sql(exp.cast(expression.this, target_type))
- if expression.text("expression").lower() in TIMEZONES:
+ if zone.name.lower() in TIMEZONES:
return self.sql(
exp.AtTimeZone(
this=exp.cast(expression.this, exp.DataType.Type.TIMESTAMP),
- zone=expression.expression,
+ zone=zone,
)
)
- return self.func("TIMESTAMP", expression.this, expression.expression)
+ return self.func("TIMESTAMP", expression.this, zone)
+
+
+def no_time_sql(self: Generator, expression: exp.Time) -> str:
+ # Transpile BQ's TIME(timestamp, zone) to CAST(TIMESTAMPTZ <timestamp> AT TIME ZONE <zone> AS TIME)
+ this = exp.cast(expression.this, exp.DataType.Type.TIMESTAMPTZ)
+ expr = exp.cast(
+ exp.AtTimeZone(this=this, zone=expression.args.get("zone")), exp.DataType.Type.TIME
+ )
+ return self.sql(expr)
+
+
+def no_datetime_sql(self: Generator, expression: exp.Datetime) -> str:
+ this = expression.this
+ expr = expression.expression
+
+ if expr.name.lower() in TIMEZONES:
+ # Transpile BQ's DATETIME(timestamp, zone) to CAST(TIMESTAMPTZ <timestamp> AT TIME ZONE <zone> AS TIMESTAMP)
+ this = exp.cast(this, exp.DataType.Type.TIMESTAMPTZ)
+ this = exp.cast(exp.AtTimeZone(this=this, zone=expr), exp.DataType.Type.TIMESTAMP)
+ return self.sql(this)
+
+ this = exp.cast(this, exp.DataType.Type.DATE)
+ expr = exp.cast(expr, exp.DataType.Type.TIME)
+
+ return self.sql(exp.cast(exp.Add(this=this, expression=expr), exp.DataType.Type.TIMESTAMP))
def locate_to_strposition(args: t.List) -> exp.Expression:
diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index acf018060d..102f3e3ac8 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -15,11 +15,13 @@
build_default_decimal_type,
date_trunc_to_time,
datestrtodate_sql,
+ no_datetime_sql,
encode_decode_sql,
build_formatted_time,
inline_array_unless_query,
no_comment_column_constraint_sql,
no_safe_divide_sql,
+ no_time_sql,
no_timestamp_sql,
pivot_column_names,
regexp_extract_sql,
@@ -407,6 +409,7 @@ class Generator(generator.Generator):
"DATE_DIFF", f"'{e.args.get('unit') or 'DAY'}'", e.expression, e.this
),
exp.DateStrToDate: datestrtodate_sql,
+ exp.Datetime: no_datetime_sql,
exp.DateToDi: lambda self,
e: f"CAST(STRFTIME({self.sql(e, 'this')}, {DuckDB.DATEINT_FORMAT}) AS INT)",
exp.Decode: lambda self, e: encode_decode_sql(self, e, "DECODE", replace=False),
@@ -457,6 +460,7 @@ class Generator(generator.Generator):
),
exp.Struct: _struct_sql,
exp.TimeAdd: _date_delta_sql,
+ exp.Time: no_time_sql,
exp.Timestamp: no_timestamp_sql,
exp.TimestampDiff: lambda self, e: self.func(
"DATE_DIFF", exp.Literal.string(e.unit), e.expression, e.this
diff --git a/sqlglot/dialects/sqlite.py b/sqlglot/dialects/sqlite.py
index be62d9588d..f9e510cb84 100644
--- a/sqlglot/dialects/sqlite.py
+++ b/sqlglot/dialects/sqlite.py
@@ -111,6 +111,8 @@ class Parser(parser.Parser):
**parser.Parser.FUNCTIONS,
"EDITDIST3": exp.Levenshtein.from_arg_list,
"STRFTIME": _build_strftime,
+ "DATETIME": lambda args: exp.Anonymous(this="DATETIME", expressions=args),
+ "TIME": lambda args: exp.Anonymous(this="TIME", expressions=args),
}
STRING_ALIASES = True
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 9ce84c7676..92e70fede0 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -5065,6 +5065,12 @@ def unit(self) -> Expression:
return self.args["unit"]
+# https://cloud.google.com/bigquery/docs/reference/standard-sql/datetime_functions#datetime
+# expression can either be time_expr or time_zone
+class Datetime(Func):
+ arg_types = {"this": True, "expression": False}
+
+
class DatetimeAdd(Func, IntervalOp):
arg_types = {"this": True, "expression": True, "unit": False}
@@ -5115,7 +5121,7 @@ class Extract(Func):
class Timestamp(Func):
- arg_types = {"this": False, "expression": False, "with_tz": False}
+ arg_types = {"this": False, "zone": False, "with_tz": False}
class TimestampAdd(Func, TimeUnit):
@@ -5833,6 +5839,11 @@ class StddevSamp(AggFunc):
pass
+# https://cloud.google.com/bigquery/docs/reference/standard-sql/time_functions#time
+class Time(Func):
+ arg_types = {"this": False, "zone": False}
+
+
class TimeToStr(Func):
arg_types = {"this": True, "format": True, "culture": False, "timezone": False}
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index 9ef556d917..db4bbd9667 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -143,7 +143,7 @@ class Generator(metaclass=_Generator):
exp.TemporaryProperty: lambda *_: "TEMPORARY",
exp.TagColumnConstraint: lambda self, e: f"TAG ({self.expressions(e, flat=True)})",
exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
- exp.Timestamp: lambda self, e: self.func("TIMESTAMP", e.this, e.expression),
+ exp.Timestamp: lambda self, e: self.func("TIMESTAMP", e.this, e.args.get("zone")),
exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}",
exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions),
diff --git a/sqlglot/optimizer/annotate_types.py b/sqlglot/optimizer/annotate_types.py
index 09122eda19..5fb8fe351f 100644
--- a/sqlglot/optimizer/annotate_types.py
+++ b/sqlglot/optimizer/annotate_types.py
@@ -158,6 +158,7 @@ class TypeAnnotator(metaclass=_TypeAnnotator):
},
exp.DataType.Type.DATETIME: {
exp.CurrentDatetime,
+ exp.Datetime,
exp.DatetimeAdd,
exp.DatetimeSub,
},
@@ -196,6 +197,9 @@ class TypeAnnotator(metaclass=_TypeAnnotator):
exp.DataType.Type.JSON: {
exp.ParseJSON,
},
+ exp.DataType.Type.TIME: {
+ exp.Time,
+ },
exp.DataType.Type.TIMESTAMP: {
exp.CurrentTime,
exp.CurrentTimestamp,
diff --git a/sqlglot/optimizer/canonicalize.py b/sqlglot/optimizer/canonicalize.py
index 17a5089f66..a7b4b0292d 100644
--- a/sqlglot/optimizer/canonicalize.py
+++ b/sqlglot/optimizer/canonicalize.py
@@ -42,7 +42,7 @@ def replace_date_funcs(node: exp.Expression) -> exp.Expression:
and not node.args.get("zone")
):
return exp.cast(node.this, to=exp.DataType.Type.DATE)
- if isinstance(node, exp.Timestamp) and not node.expression:
+ if isinstance(node, exp.Timestamp) and not node.args.get("zone"):
if not node.type:
from sqlglot.optimizer.annotate_types import annotate_types
| diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py
index ae8ed166f9..42cb27f75d 100644
--- a/tests/dialects/test_bigquery.py
+++ b/tests/dialects/test_bigquery.py
@@ -1345,6 +1345,34 @@ def test_bigquery(self):
"bigquery": "SELECT CAST(x AS DATETIME)",
},
)
+ self.validate_all(
+ "SELECT TIME(foo, 'America/Los_Angeles')",
+ write={
+ "duckdb": "SELECT CAST(CAST(foo AS TIMESTAMPTZ) AT TIME ZONE 'America/Los_Angeles' AS TIME)",
+ "bigquery": "SELECT TIME(foo, 'America/Los_Angeles')",
+ },
+ )
+ self.validate_all(
+ "SELECT DATETIME('2020-01-01')",
+ write={
+ "duckdb": "SELECT CAST('2020-01-01' AS TIMESTAMP)",
+ "bigquery": "SELECT DATETIME('2020-01-01')",
+ },
+ )
+ self.validate_all(
+ "SELECT DATETIME('2020-01-01', TIME '23:59:59')",
+ write={
+ "duckdb": "SELECT CAST(CAST('2020-01-01' AS DATE) + CAST('23:59:59' AS TIME) AS TIMESTAMP)",
+ "bigquery": "SELECT DATETIME('2020-01-01', CAST('23:59:59' AS TIME))",
+ },
+ )
+ self.validate_all(
+ "SELECT DATETIME('2020-01-01', 'America/Los_Angeles')",
+ write={
+ "duckdb": "SELECT CAST(CAST('2020-01-01' AS TIMESTAMPTZ) AT TIME ZONE 'America/Los_Angeles' AS TIMESTAMP)",
+ "bigquery": "SELECT DATETIME('2020-01-01', 'America/Los_Angeles')",
+ },
+ )
def test_errors(self):
with self.assertRaises(TokenError):
| [] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery"
] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_errors",
"tests/dialects/test_bigquery.py::TestBigQuery::test_gap_fill",
"tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat",
"tests/dialects/test_bigquery.py::TestBigQuery::test_json_object",
"tests/dialects/test_bigquery.py::TestBigQuery:... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(bigquery)!: Time/Datetime/Timestamp function additions
The aim of this PR is to extend support for the following time functions in BigQuery and enable transpilation towards DuckDB:
`TIME`:
- Introduce `exp.Time` for `TIME(timestamp, [time_zone])` roundtrip
- Enable transpilation to other dialects by generating `<timestamp> AT TIME ZONE <time_zone>`
`TIMESTAMP`:
- Rename `expression` to `zone` as the 2nd parameter is always `time_zone`
`DATETIME`:
- Introduce `exp.Datetime` for `DATETIME(date_expr, [time_expr | time_zone])` roundtrip
- Enable transpilation to other dialects by generating `<date_expr> AT TIME ZONE <time_zone>` if the expression is `time_zone`, otherwise generate `<date_expr> + <time_expr>`
[BQ TIME](https://cloud.google.com/bigquery/docs/reference/standard-sql/time_functions#time) | [BQ TIMESTAMP](https://cloud.google.com/bigquery/docs/reference/standard-sql/timestamp_functions#timestamp) | [BQ DATETIME](https://cloud.google.com/bigquery/docs/reference/standard-sql/datetime_functions#datetime) | [DuckDB AT TIME ZONE](https://duckdb.org/docs/sql/functions/timestamptz.html#at-time-zone)
----------
</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>
</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 | ||
pvlib__pvlib-python-2088 | 2,088 | pvlib/pvlib-python | 0.10 | 1eecaa38e8cf07a013a6bf00ea7378c9b23ba65e | 2024-06-15T09:59:50Z | diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index 8dd74444a2..15fd1d09b8 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -15,5 +15,6 @@ Spectrum
spectrum.spectral_factor_firstsolar
spectrum.spectral_factor_sapm
spectrum.spectral_factor_pvspec
+ spectrum.spectral_factor_jrc
spectrum.sr_to_qe
spectrum.qe_to_sr
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 2fdcd1c444..fe137a92c7 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -44,9 +44,14 @@ Enhancements
efficiency ([unitless]) and vice versa. The conversion functions are
:py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
respectively. (:issue:`2040`, :pull:`2041`)
-* Add function :py:func:`pvlib.spectrum.spectral_factor_pvspec`, which calculates the
- spectral mismatch factor as a function of absolute airmass and clearsky index
- using the PVSPEC model. (:issue:`1950`, :issue:`2065`, :pull:`2072`)
+* Add function :py:func:`pvlib.spectrum.spectral_factor_pvspec`, which
+ calculates the spectral mismatch factor as a function of absolute airmass and
+ clearsky index using the PVSPEC model.
+ (:issue:`1950`, :issue:`2065`, :pull:`2072`)
+* Add function :py:func:`pvlib.spectrum.spectral_factor_jrc`, which calculates
+ the spectral mismatch factor as a function of airmass and clearsky
+ index using the JRC model.
+ (:issue:`1950`, :issue:`2065`, :issue:`2087`, :pull:`2088`)
* Added extraterrestrial and direct spectra of the ASTM G173-03 standard with
the new function :py:func:`pvlib.spectrum.get_reference_spectra`.
(:issue:`1963`, :pull:`2039`)
diff --git a/pvlib/spectrum/__init__.py b/pvlib/spectrum/__init__.py
index 3194fd17a2..b95f221066 100644
--- a/pvlib/spectrum/__init__.py
+++ b/pvlib/spectrum/__init__.py
@@ -8,6 +8,7 @@
spectral_factor_firstsolar,
spectral_factor_sapm,
spectral_factor_pvspec,
+ spectral_factor_jrc,
sr_to_qe,
qe_to_sr
)
diff --git a/pvlib/spectrum/mismatch.py b/pvlib/spectrum/mismatch.py
index 9b644b2ef9..d2fc4dcf1d 100644
--- a/pvlib/spectrum/mismatch.py
+++ b/pvlib/spectrum/mismatch.py
@@ -794,6 +794,116 @@ def spectral_factor_pvspec(airmass_absolute, clearsky_index,
return mismatch
+def spectral_factor_jrc(airmass, clearsky_index, module_type=None,
+ coefficients=None):
+ r"""
+ Estimate a technology-specific spectral mismatch modifier from
+ airmass and clear sky index using the JRC model.
+
+ The JRC spectral mismatch model includes the effects of cloud cover on
+ the irradiance spectrum. Model coefficients are derived using measurements
+ of irradiance and module performance at the Joint Research Centre (JRC) in
+ Ispra, Italy (45.80N, 8.62E). Coefficients for two module types are
+ available via the ``module_type`` parameter. More details on the model can
+ be found in [1]_.
+
+ Parameters
+ ----------
+ airmass : numeric
+ relative airmass. [unitless]
+
+ clearsky_index: numeric
+ clear sky index. [unitless]
+
+ module_type : str, optional
+ One of the following PV technology strings from [1]_:
+
+ * ``'cdte'`` - anonymous CdTe module.
+ * ``'multisi'`` - anonymous multicrystalline Si module.
+
+ coefficients : array-like, optional
+ user-defined coefficients, if not using one of the default coefficient
+ sets via the ``module_type`` parameter.
+
+ Returns
+ -------
+ mismatch: numeric
+ spectral mismatch factor (unitless) which is multiplied
+ with broadband irradiance reaching a module's cells to estimate
+ effective irradiance, i.e., the irradiance that is converted to
+ electrical current.
+
+ Notes
+ -----
+ The JRC model parameterises the spectral mismatch factor as a function
+ of air mass and the clear sky index as follows:
+
+ .. math::
+
+ M = 1 + a_1(e^{-k_c}-e^{-1}) + a_2(k_c-1)+a_3(AM-1.5),
+
+ where :math:`M` is the spectral mismatch factor, :math:`k_c` is the clear
+ sky index, :math:`AM` is the air mass, :math:`e` is Euler's number, and
+ :math:`a_1, a_2, a_3` are module-specific coefficients. The :math:`a_n`
+ coefficients available via the ``coefficients`` parameter differ from the
+ :math:`k_n` coefficients documented in [1]_ in that they are normalised by
+ the specific short-circuit current value, :math:`I_{sc0}^*`, which is the
+ expected short-circuit current at standard test conditions indoors. The
+ model used to estimate the air mass (denoted as :math:`AM`) is not stated
+ in the original publication. The authors of [1]_ used the ESRA model [2]_
+ to estimate the clear sky GHI for the clear sky index, which is the ratio
+ of GHI to clear sky GHI. Also, prior to the calculation of :math:`k_c`, the
+ irradiance measurements were corrected for angle of incidence using the
+ Martin and Ruiz model [3]_.
+
+ References
+ ----------
+ .. [1] Huld, T., Sample, T., and Dunlop, E., 2009. A simple model
+ for estimating the influence of spectrum variations on PV performance.
+ In Proceedings of the 24th European Photovoltaic Solar Energy
+ Conference, Hamburg, Germany pp. 3385-3389. 2009. Accessed at:
+ https://www.researchgate.net/publication/256080247
+ .. [2] Rigollier, C., Bauer, O., and Wald, L., 2000. On the clear sky model
+ of the ESRA—European Solar Radiation Atlas—with respect to the Heliosat
+ method. Solar energy, 68(1), pp.33-48.
+ :doi:`10.1016/S0038-092X(99)00055-9`
+ .. [3] Martin, N. and Ruiz, J. M., 2001. Calculation of the PV modules
+ angular losses under field conditions by means of an analytical model.
+ Solar Energy Materials and Solar Cells, 70(1), 25-38.
+ :doi:`10.1016/S0927-0248(00)00408-6`
+ """
+
+ _coefficients = {}
+ _coefficients['multisi'] = (0.00172, 0.000508, 0.00000357)
+ _coefficients['cdte'] = (0.000643, 0.000130, 0.0000108)
+ # normalise coefficients by I*sc0, see [1]
+ _coefficients = {
+ 'multisi': tuple(x / 0.00348 for x in _coefficients['multisi']),
+ 'cdte': tuple(x / 0.001150 for x in _coefficients['cdte'])
+ }
+ if module_type is not None and coefficients is None:
+ coefficients = _coefficients[module_type.lower()]
+ elif module_type is None and coefficients is not None:
+ pass
+ elif module_type is None and coefficients is None:
+ raise ValueError('No valid input provided, both module_type and ' +
+ 'coefficients are None. module_type can be one of ' +
+ ", ".join(_coefficients.keys()))
+ else:
+ raise ValueError('Cannot resolve input, must supply only one of ' +
+ 'module_type and coefficients. module_type can be ' +
+ 'one of' ", ".join(_coefficients.keys()))
+
+ coeff = coefficients
+ mismatch = (
+ 1
+ + coeff[0] * (np.exp(-clearsky_index) - np.exp(-1))
+ + coeff[1] * (clearsky_index - 1)
+ + coeff[2] * (airmass - 1.5)
+ )
+ return mismatch
+
+
def sr_to_qe(sr, wavelength=None, normalize=False):
"""
Convert spectral responsivities to quantum efficiencies.
| diff --git a/pvlib/tests/test_spectrum.py b/pvlib/tests/test_spectrum.py
index 5c89078bc1..969fb819b8 100644
--- a/pvlib/tests/test_spectrum.py
+++ b/pvlib/tests/test_spectrum.py
@@ -426,6 +426,54 @@ def test_spectral_factor_pvspec_supplied_ambiguous():
coefficients=None)
+@pytest.mark.parametrize("module_type,expected", [
+ ('multisi', np.array([1.06129, 1.03098, 1.01155, 0.99849])),
+ ('cdte', np.array([1.09657, 1.05594, 1.02763, 0.97740])),
+])
+def test_spectral_factor_jrc(module_type, expected):
+ ams = np.array([1.0, 1.5, 2.0, 1.5])
+ kcs = np.array([0.4, 0.6, 0.8, 1.4])
+ out = spectrum.spectral_factor_jrc(ams, kcs,
+ module_type=module_type)
+ assert np.allclose(expected, out, atol=1e-4)
+
+
+@pytest.mark.parametrize("module_type,expected", [
+ ('multisi', np.array([1.06129, 1.03098, 1.01155, 0.99849])),
+ ('cdte', np.array([1.09657, 1.05594, 1.02763, 0.97740])),
+])
+def test_spectral_factor_jrc_series(module_type, expected):
+ ams = pd.Series([1.0, 1.5, 2.0, 1.5])
+ kcs = pd.Series([0.4, 0.6, 0.8, 1.4])
+ out = spectrum.spectral_factor_jrc(ams, kcs,
+ module_type=module_type)
+ assert isinstance(out, pd.Series)
+ assert np.allclose(expected, out, atol=1e-4)
+
+
+def test_spectral_factor_jrc_supplied():
+ # use the multisi coeffs
+ coeffs = (0.494, 0.146, 0.00103)
+ out = spectrum.spectral_factor_jrc(1.0, 0.8, coefficients=coeffs)
+ expected = 1.01052106
+ assert_allclose(out, expected, atol=1e-4)
+
+
+def test_spectral_factor_jrc_supplied_redundant():
+ # Error when specifying both module_type and coefficients
+ coeffs = (0.494, 0.146, 0.00103)
+ with pytest.raises(ValueError, match='supply only one of'):
+ spectrum.spectral_factor_jrc(1.0, 0.8, module_type='multisi',
+ coefficients=coeffs)
+
+
+def test_spectral_factor_jrc_supplied_ambiguous():
+ # Error when specifying neither module_type nor coefficients
+ with pytest.raises(ValueError, match='No valid input provided'):
+ spectrum.spectral_factor_jrc(1.0, 0.8, module_type=None,
+ coefficients=None)
+
+
@pytest.fixture
def sr_and_eqe_fixture():
# Just some arbitrary data for testing the conversion functions
| diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index 8dd74444a2..15fd1d09b8 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -15,5 +15,6 @@ Spectrum
spectrum.spectral_factor_firstsolar
spectrum.spectral_factor_sapm
spectrum.spectral_factor_pvspec
+ spectrum.spectral_factor_jrc
spectrum.sr_to_qe
spectrum.qe_to_sr
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 2fdcd1c444..fe137a92c7 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -44,9 +44,14 @@ Enhancements
efficiency ([unitless]) and vice versa. The conversion functions are
:py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
respectively. (:issue:`2040`, :pull:`2041`)
-* Add function :py:func:`pvlib.spectrum.spectral_factor_pvspec`, which calculates the
- spectral mismatch factor as a function of absolute airmass and clearsky index
- using the PVSPEC model. (:issue:`1950`, :issue:`2065`, :pull:`2072`)
+* Add function :py:func:`pvlib.spectrum.spectral_factor_pvspec`, which
+ calculates the spectral mismatch factor as a function of absolute airmass and
+ clearsky index using the PVSPEC model.
+ (:issue:`1950`, :issue:`2065`, :pull:`2072`)
+* Add function :py:func:`pvlib.spectrum.spectral_factor_jrc`, which calculates
+ the spectral mismatch factor as a function of airmass and clearsky
+ index using the JRC model.
+ (:issue:`1950`, :issue:`2065`, :issue:`2087`, :pull:`2088`)
* Added extraterrestrial and direct spectra of the ASTM G173-03 standard with
the new function :py:func:`pvlib.spectrum.get_reference_spectra`.
(:issue:`1963`, :pull:`2039`)
| [
{
"components": [
{
"doc": "Estimate a technology-specific spectral mismatch modifier from\nairmass and clear sky index using the JRC model.\n\nThe JRC spectral mismatch model includes the effects of cloud cover on\nthe irradiance spectrum. Model coefficients are derived using measurements\nof irr... | [
"pvlib/tests/test_spectrum.py::test_spectral_factor_jrc[multisi-expected0]",
"pvlib/tests/test_spectrum.py::test_spectral_factor_jrc[cdte-expected1]",
"pvlib/tests/test_spectrum.py::test_spectral_factor_jrc_series[multisi-expected0]",
"pvlib/tests/test_spectrum.py::test_spectral_factor_jrc_series[cdte-expecte... | [
"pvlib/tests/test_spectrum.py::test_spectrl2",
"pvlib/tests/test_spectrum.py::test_spectrl2_array",
"pvlib/tests/test_spectrum.py::test_spectrl2_series",
"pvlib/tests/test_spectrum.py::test_dayofyear_missing",
"pvlib/tests/test_spectrum.py::test_aoi_gt_90",
"pvlib/tests/test_spectrum.py::test_get_example_... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add JRC spectral factor correction
<!-- 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] Closes #2087; partially closes #2065 and #1950
- [x] I am familiar with the [contributing guidelines](https://pvlib-python.readthedocs.io/en/latest/contributing.html)
- [x] Tests added
- [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): -->
Would like some advice on some questions raised in #2087 regarding citations and the `airmass` parameter.
Docs: https://pvlib-python--2088.org.readthedocs.build/en/2088/reference/generated/pvlib.spectrum.spectral_factor_jrc.html?highlight=jrc#pvlib.spectrum.spectral_factor_jrc
----------
</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/spectrum/mismatch.py]
(definition of spectral_factor_jrc:)
def spectral_factor_jrc(airmass, clearsky_index, module_type=None, coefficients=None):
"""Estimate a technology-specific spectral mismatch modifier from
airmass and clear sky index using the JRC model.
The JRC spectral mismatch model includes the effects of cloud cover on
the irradiance spectrum. Model coefficients are derived using measurements
of irradiance and module performance at the Joint Research Centre (JRC) in
Ispra, Italy (45.80N, 8.62E). Coefficients for two module types are
available via the ``module_type`` parameter. More details on the model can
be found in [1]_.
Parameters
----------
airmass : numeric
relative airmass. [unitless]
clearsky_index: numeric
clear sky index. [unitless]
module_type : str, optional
One of the following PV technology strings from [1]_:
* ``'cdte'`` - anonymous CdTe module.
* ``'multisi'`` - anonymous multicrystalline Si module.
coefficients : array-like, optional
user-defined coefficients, if not using one of the default coefficient
sets via the ``module_type`` parameter.
Returns
-------
mismatch: numeric
spectral mismatch factor (unitless) which is multiplied
with broadband irradiance reaching a module's cells to estimate
effective irradiance, i.e., the irradiance that is converted to
electrical current.
Notes
-----
The JRC model parameterises the spectral mismatch factor as a function
of air mass and the clear sky index as follows:
.. math::
M = 1 + a_1(e^{-k_c}-e^{-1}) + a_2(k_c-1)+a_3(AM-1.5),
where :math:`M` is the spectral mismatch factor, :math:`k_c` is the clear
sky index, :math:`AM` is the air mass, :math:`e` is Euler's number, and
:math:`a_1, a_2, a_3` are module-specific coefficients. The :math:`a_n`
coefficients available via the ``coefficients`` parameter differ from the
:math:`k_n` coefficients documented in [1]_ in that they are normalised by
the specific short-circuit current value, :math:`I_{sc0}^*`, which is the
expected short-circuit current at standard test conditions indoors. The
model used to estimate the air mass (denoted as :math:`AM`) is not stated
in the original publication. The authors of [1]_ used the ESRA model [2]_
to estimate the clear sky GHI for the clear sky index, which is the ratio
of GHI to clear sky GHI. Also, prior to the calculation of :math:`k_c`, the
irradiance measurements were corrected for angle of incidence using the
Martin and Ruiz model [3]_.
References
----------
.. [1] Huld, T., Sample, T., and Dunlop, E., 2009. A simple model
for estimating the influence of spectrum variations on PV performance.
In Proceedings of the 24th European Photovoltaic Solar Energy
Conference, Hamburg, Germany pp. 3385-3389. 2009. Accessed at:
https://www.researchgate.net/publication/256080247
.. [2] Rigollier, C., Bauer, O., and Wald, L., 2000. On the clear sky model
of the ESRA—European Solar Radiation Atlas—with respect to the Heliosat
method. Solar energy, 68(1), pp.33-48.
:doi:`10.1016/S0038-092X(99)00055-9`
.. [3] Martin, N. and Ruiz, J. M., 2001. Calculation of the PV modules
angular losses under field conditions by means of an analytical model.
Solar Energy Materials and Solar Cells, 70(1), 25-38.
:doi:`10.1016/S0927-0248(00)00408-6`"""
[end of new definitions in pvlib/spectrum/mismatch.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 JRC spectral factor model
**Is your feature request related to a problem? Please describe.**
The PVSPEC model for the spectral mismatch factor was recently merged (#2072) but an alternative parameterisation of the mismatch factor as a function of air mass and clear sky index is available, namely [the JRC model](https://www.researchgate.net/publication/256080247_A_simple_model_for_estimate_the_influence_of_spectrum_variations_on_PV_performance). I think providing pvlib users with a choice of model would be a valuable enhancement.
**Describe the solution you'd like**
Implement JRC model using the PVSPEC function as a template.
**Additional context**
Some questions:
1. Citation for the clear sky model in [the JRC publication](https://www.researchgate.net/publication/256080247_A_simple_model_for_estimate_the_influence_of_spectrum_variations_on_PV_performance) is:
>"K. Scharmer and J. Greif (eds.), “The European Solar Radiation Atlas, Vol 2: Database and Exploitation Software”, Presses de l’École des Mines, Paris (2000)"
and
>"M. Šúri and J. Hofierka. “A new GIS-based solar radiation model and its application to photovoltaic assessments”, Transactions in GIS, 8 (2004), pp. 175-190".
In [the PVSPEC paper](https://ieeexplore.ieee.org/document/9300932) and [the pvlib implementation](https://pvlib-python--2072.org.readthedocs.build/en/2072/reference/generated/pvlib.spectrum.spectral_factor_pvspec.html):
> "Rigollier, C., Bauer, O. and Wald, L., 2000. On the clear sky model of the ESRA—European Solar Radiation Atlas—with respect to the Heliosat method. Solar Energy, 68(1), pp.33-48.".
I think these are the same ESRA model (?) ---if so, which citation should I use?
2. As far as I can tell, the model used to estimate air mass is not stated, nor whether it is relative or absolute air mass. In the docs, would it suffice just to write something like "the model used to estimate the air mass (denoted AM) is not stated." ?
----
This issue links to my GSoC project (#2065) and this issue #1950
----------
--------------------Google Summer of Code project summary: Implementing new spectral corrections in pvlib
### **Introduction**
This issue summarises the ongoing and completed work for the [GSoC 2024 programme](https://summerofcode.withgoogle.com/) with pvlib.
The project I am undertaking relates to [an issue raised earlier this year](https://github.com/pvlib/pvlib-python/issues/1950). The official abstract for the project [can be found here](https://summerofcode.withgoogle.com/programs/2024/projects/TT5QrYqT). This project is being carried out under the supervision of @AdamRJensen and @kandersolar
In summary, the aim of the project is to implement new spectral correction models in pvlib, as well as examples of their application and use. In addition to updating this issue as the project progresses, detailed updates on the project will also be shared in [blog posts](https://rdaxini.github.io/). Major milestone updates will be shared on [my LinkedIn page](https://www.linkedin.com/in/rajiv-daxini-ba354a237/) as well.
### **Plan**
The current overall project plan is described below.
1. Three new models are planned for development and implementation:
- [Pelland 2020 PVSPEC model](https://ieeexplore.ieee.org/document/9300932)
- [Huld 2009 JRC model](https://www.researchgate.net/profile/Tony-Sample/publication/256080247_A_simple_model_for_estimate_the_influence_of_spectrum_variations_on_PV_performance/links/56e6df1108ae77cfe4bd1b0c/A-simple-model-for-estimate-the-influence-of-spectrum-variations-on-PV-performance.pdf)
- [Daxini 2023 APE/e model](https://www.sciencedirect.com/science/article/pii/S0360544223024404?pes=vor) (stretch goal, if time permits)
2. A combined example to demonstrate the use of the new models and application in the overall modelling pipeline will be developed.
As the project develops I will link these tasks to individual issues and pull requests.
### **Issues**
Open:
Closed:
#2065 (this one)
#2135 (create average photon energy function)
#2125 (suggestion to split `mismatch.py`)
#1950 (general issue, add new spectral factor models)
#2087 (add JRC spectral factor model)
#2115 (update SAPM spectral factor docs)
#2107 (add spectral factor example),
#2086 (update `spectral_factor_firstsolar`)
### **PRs**
- (merged) Split `test_spectrum.py` #2151
- (merged) Function to calculate APE #2140
- (merged) Restructure `pvlib/spectrum` #2136
- (merged) Update First Solar model #2100
- (merged) Spectral mismatch factor example #2114
- (merged) Update SAPM docs #2116
- (merged) JRC model (air mass and clearsky index) #2088
- (merged) PVSPEC model (air mass and clearsky index): #2072
- (closed) Add ape_e spectral factor model #2126
---------------
Any feedback on the project is certainly more than welcome. Using github and contributing to open-source software is completely new to me so I am looking forward to learning about this so that I can contribute to pvlib not only through this project but also in future.
Dax
----------
As part of the documentation of a growing number of methods, it might be helpful if a “overview” table of spectral-correction method vs. required+optional inputs were added. This way consumers would be able to get a quicker idea of what information/data is needed to apply each correction. The timescale over which the correction is applied could also be a factor (although maybe they are all the same at this point).
@markcampanelli I think that is a good suggestion. I tried to achieve something similar with Table 10 [in this study](https://www.sciencedirect.com/science/article/pii/S0360544223028554#tbl10); is that the sort of thing you had in mind? Timescale is a good point too. I have had a paper examining this issue under review for a while so maybe/hopefully something will come out of that soon that I can implement into this work.
@didierthevenard
> @markcampanelli I think that is a good suggestion. I tried to achieve something similar with Table 10 [in this study](https://www.sciencedirect.com/science/article/pii/S0360544223028554#tbl10); is that the sort of thing you had in mind? Timescale is a good point too. I have had a paper examining this issue under review for a while so maybe/hopefully something will come out of that soon that I can implement into this work.
@RDaxini Yes. Depending on your time, you could at a bare minimum reference your paper with table 10. If time permits, then you could perhaps provide a “translation” of that table into something more specific to pvlib’s variable names and functions.
BTW: Your timescale-focused paper also sounds like an interesting read 🙂. Good luck working it through the process!
--------------------
</issues> | 6af80da35a7c96059c534ee38be9123bcfc7f50f |
scikit-learn__scikit-learn-29260 | 29,260 | scikit-learn/scikit-learn | 1.6 | 156ef1b7fe9bc0ee5b281634cfd56b9c54e83277 | 2024-06-14T12:13:12Z | diff --git a/doc/metadata_routing.rst b/doc/metadata_routing.rst
index 31dae6813bda5..fec2cf610c02f 100644
--- a/doc/metadata_routing.rst
+++ b/doc/metadata_routing.rst
@@ -285,6 +285,7 @@ Meta-estimators and functions supporting metadata routing:
- :class:`sklearn.ensemble.BaggingClassifier`
- :class:`sklearn.ensemble.BaggingRegressor`
- :class:`sklearn.feature_selection.SelectFromModel`
+- :class:`sklearn.feature_selection.SequentialFeatureSelector`
- :class:`sklearn.impute.IterativeImputer`
- :class:`sklearn.linear_model.ElasticNetCV`
- :class:`sklearn.linear_model.LarsCV`
@@ -324,4 +325,3 @@ Meta-estimators and tools not supporting metadata routing yet:
- :class:`sklearn.ensemble.AdaBoostRegressor`
- :class:`sklearn.feature_selection.RFE`
- :class:`sklearn.feature_selection.RFECV`
-- :class:`sklearn.feature_selection.SequentialFeatureSelector`
diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst
index 5e44f716812e5..21f1042203211 100644
--- a/doc/whats_new/v1.6.rst
+++ b/doc/whats_new/v1.6.rst
@@ -83,6 +83,11 @@ more details.
params to the underlying regressor.
:pr:`29136` by :user:`Omar Salman <OmarManzoor>`.
+- |Feature| :class:`feature_selection.SequentialFeatureSelector` now supports
+ metadata routing in its `fit` method and passes the corresponding params to
+ the :func:`model_selection.cross_val_score` function.
+ :pr:`29260` by :user:`Omar Salman <OmarManzoor>`.
+
- |Feature| :func:`model_selection.validation_curve` now supports metadata routing for
the `fit` method of its estimator and for its underlying CV splitter and scorer.
:pr:`29329` by :user:`Stefanie Senger <StefanieSenger>`.
diff --git a/sklearn/feature_selection/_sequential.py b/sklearn/feature_selection/_sequential.py
index 471f9a373a3da..3888a5bbc7c8e 100644
--- a/sklearn/feature_selection/_sequential.py
+++ b/sklearn/feature_selection/_sequential.py
@@ -10,18 +10,22 @@
import numpy as np
from ..base import BaseEstimator, MetaEstimatorMixin, _fit_context, clone, is_classifier
-from ..metrics import get_scorer_names
+from ..metrics import check_scoring, get_scorer_names
from ..model_selection import check_cv, cross_val_score
+from ..utils._metadata_requests import (
+ MetadataRouter,
+ MethodMapping,
+ _raise_for_params,
+ _routing_enabled,
+ process_routing,
+)
from ..utils._param_validation import HasMethods, Interval, RealNotInt, StrOptions
from ..utils._tags import _safe_tags
-from ..utils.metadata_routing import _RoutingNotSupportedMixin
from ..utils.validation import check_is_fitted
from ._base import SelectorMixin
-class SequentialFeatureSelector(
- _RoutingNotSupportedMixin, SelectorMixin, MetaEstimatorMixin, BaseEstimator
-):
+class SequentialFeatureSelector(SelectorMixin, MetaEstimatorMixin, BaseEstimator):
"""Transformer that performs Sequential Feature Selection.
This Sequential Feature Selector adds (forward selection) or
@@ -191,7 +195,7 @@ def __init__(
# SequentialFeatureSelector.estimator is not validated yet
prefer_skip_nested_validation=False
)
- def fit(self, X, y=None):
+ def fit(self, X, y=None, **params):
"""Learn the features to select from X.
Parameters
@@ -204,11 +208,24 @@ def fit(self, X, y=None):
Target values. This parameter may be ignored for
unsupervised learning.
+ **params : dict, default=None
+ Parameters to be passed to the underlying `estimator`, `cv`
+ and `scorer` objects.
+
+ .. versionadded:: 1.6
+
+ Only available if `enable_metadata_routing=True`,
+ which can be set by using
+ ``sklearn.set_config(enable_metadata_routing=True)``.
+ See :ref:`Metadata Routing User Guide <metadata_routing>` for
+ more details.
+
Returns
-------
self : object
Returns the instance itself.
"""
+ _raise_for_params(params, self, "fit")
tags = self._get_tags()
X = self._validate_data(
X,
@@ -251,9 +268,15 @@ def fit(self, X, y=None):
old_score = -np.inf
is_auto_select = self.tol is not None and self.n_features_to_select == "auto"
+
+ # We only need to verify the routing here and not use the routed params
+ # because internally the actual routing will also take place inside the
+ # `cross_val_score` function.
+ if _routing_enabled():
+ process_routing(self, "fit", **params)
for _ in range(n_iterations):
new_feature_idx, new_score = self._get_best_new_feature_score(
- cloned_estimator, X, y, cv, current_mask
+ cloned_estimator, X, y, cv, current_mask, **params
)
if is_auto_select and ((new_score - old_score) < self.tol):
break
@@ -269,7 +292,7 @@ def fit(self, X, y=None):
return self
- def _get_best_new_feature_score(self, estimator, X, y, cv, current_mask):
+ def _get_best_new_feature_score(self, estimator, X, y, cv, current_mask, **params):
# Return the best new feature and its score to add to the current_mask,
# i.e. return the best new feature and its score to add (resp. remove)
# when doing forward selection (resp. backward selection).
@@ -290,6 +313,7 @@ def _get_best_new_feature_score(self, estimator, X, y, cv, current_mask):
cv=cv,
scoring=self.scoring,
n_jobs=self.n_jobs,
+ params=params,
).mean()
new_feature_idx = max(scores, key=lambda feature_idx: scores[feature_idx])
return new_feature_idx, scores[new_feature_idx]
@@ -302,3 +326,32 @@ def _more_tags(self):
return {
"allow_nan": _safe_tags(self.estimator, key="allow_nan"),
}
+
+ 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__)
+ router.add(
+ estimator=self.estimator,
+ method_mapping=MethodMapping().add(caller="fit", callee="fit"),
+ )
+ router.add(
+ splitter=check_cv(self.cv, classifier=is_classifier(self.estimator)),
+ method_mapping=MethodMapping().add(caller="fit", callee="split"),
+ )
+ router.add(
+ scorer=check_scoring(self.estimator, scoring=self.scoring),
+ method_mapping=MethodMapping().add(caller="fit", callee="score"),
+ )
+ return router
| diff --git a/sklearn/feature_selection/tests/test_sequential.py b/sklearn/feature_selection/tests/test_sequential.py
index 82d65c55a0195..c6fa9b15dc80a 100644
--- a/sklearn/feature_selection/tests/test_sequential.py
+++ b/sklearn/feature_selection/tests/test_sequential.py
@@ -321,3 +321,12 @@ def test_cv_generator_support():
sfs = SequentialFeatureSelector(knc, n_features_to_select=5, cv=splits)
sfs.fit(X, y)
+
+
+def test_fit_rejects_params_with_no_routing_enabled():
+ X, y = make_classification(random_state=42)
+ est = LinearRegression()
+ sfs = SequentialFeatureSelector(estimator=est)
+
+ with pytest.raises(ValueError, match="is only supported if"):
+ sfs.fit(X, y, sample_weight=np.ones_like(y))
diff --git a/sklearn/tests/test_metaestimators_metadata_routing.py b/sklearn/tests/test_metaestimators_metadata_routing.py
index 9aca241521ca0..5c31361163689 100644
--- a/sklearn/tests/test_metaestimators_metadata_routing.py
+++ b/sklearn/tests/test_metaestimators_metadata_routing.py
@@ -407,6 +407,18 @@ def enable_slep006():
],
"method_mapping": {"fit": ["fit", "score"]},
},
+ {
+ "metaestimator": SequentialFeatureSelector,
+ "estimator_name": "estimator",
+ "estimator": "classifier",
+ "X": X,
+ "y": y,
+ "estimator_routing_methods": ["fit"],
+ "scorer_name": "scoring",
+ "scorer_routing_methods": ["fit"],
+ "cv_name": "cv",
+ "cv_routing_methods": ["fit"],
+ },
]
"""List containing all metaestimators to be tested and their settings
@@ -450,7 +462,6 @@ def enable_slep006():
AdaBoostRegressor(),
RFE(ConsumingClassifier()),
RFECV(ConsumingClassifier()),
- SequentialFeatureSelector(ConsumingClassifier()),
]
| diff --git a/doc/metadata_routing.rst b/doc/metadata_routing.rst
index 31dae6813bda5..fec2cf610c02f 100644
--- a/doc/metadata_routing.rst
+++ b/doc/metadata_routing.rst
@@ -285,6 +285,7 @@ Meta-estimators and functions supporting metadata routing:
- :class:`sklearn.ensemble.BaggingClassifier`
- :class:`sklearn.ensemble.BaggingRegressor`
- :class:`sklearn.feature_selection.SelectFromModel`
+- :class:`sklearn.feature_selection.SequentialFeatureSelector`
- :class:`sklearn.impute.IterativeImputer`
- :class:`sklearn.linear_model.ElasticNetCV`
- :class:`sklearn.linear_model.LarsCV`
@@ -324,4 +325,3 @@ Meta-estimators and tools not supporting metadata routing yet:
- :class:`sklearn.ensemble.AdaBoostRegressor`
- :class:`sklearn.feature_selection.RFE`
- :class:`sklearn.feature_selection.RFECV`
-- :class:`sklearn.feature_selection.SequentialFeatureSelector`
diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst
index 5e44f716812e5..21f1042203211 100644
--- a/doc/whats_new/v1.6.rst
+++ b/doc/whats_new/v1.6.rst
@@ -83,6 +83,11 @@ more details.
params to the underlying regressor.
:pr:`29136` by :user:`Omar Salman <OmarManzoor>`.
+- |Feature| :class:`feature_selection.SequentialFeatureSelector` now supports
+ metadata routing in its `fit` method and passes the corresponding params to
+ the :func:`model_selection.cross_val_score` function.
+ :pr:`29260` by :user:`Omar Salman <OmarManzoor>`.
+
- |Feature| :func:`model_selection.validation_curve` now supports metadata routing for
the `fit` method of its estimator and for its underlying CV splitter and scorer.
:pr:`29329` by :user:`Stefanie Senger <StefanieSenger>`.
| [
{
"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` encapsula... | [
"sklearn/feature_selection/tests/test_sequential.py::test_fit_rejects_params_with_no_routing_enabled",
"sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[SequentialFeatureSelector]",
"sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimato... | [
"sklearn/feature_selection/tests/test_sequential.py::test_bad_n_features_to_select",
"sklearn/feature_selection/tests/test_sequential.py::test_n_features_to_select[1-forward]",
"sklearn/feature_selection/tests/test_sequential.py::test_n_features_to_select[1-backward]",
"sklearn/feature_selection/tests/test_se... | 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 SequentialFeatureSelector
<!--
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 for SequentialFeatureSelector
#### Any other comments?
CC: @adrinjalali @glemaitre
<!--
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/feature_selection/_sequential.py]
(definition of SequentialFeatureSelector.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."""
[end of new definitions in sklearn/feature_selection/_sequential.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 | |
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, \... | [
"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_t... | [
"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/met... | 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 | |
pvlib__pvlib-python-2079 | 2,079 | pvlib/pvlib-python | 0.10 | 1f361607037a1c9883de01d559ddfbf870f578bf | 2024-06-06T10:18:25Z | diff --git a/docs/sphinx/source/reference/irradiance/albedo.rst b/docs/sphinx/source/reference/irradiance/albedo.rst
new file mode 100644
index 0000000000..868a065d1a
--- /dev/null
+++ b/docs/sphinx/source/reference/irradiance/albedo.rst
@@ -0,0 +1,9 @@
+.. currentmodule:: pvlib
+
+Albedo
+------
+
+.. autosummary::
+ :toctree: ../generated/
+
+ albedo.inland_water_dvoracek
diff --git a/docs/sphinx/source/reference/irradiance/index.rst b/docs/sphinx/source/reference/irradiance/index.rst
index 2263a2d2c1..72064cccbc 100644
--- a/docs/sphinx/source/reference/irradiance/index.rst
+++ b/docs/sphinx/source/reference/irradiance/index.rst
@@ -11,3 +11,4 @@ Irradiance
transposition
decomposition
clearness-index
+ albedo
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 14694d0fc4..3fa2aa41df 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -28,6 +28,9 @@ Enhancements
shade perpendicular to ``axis_azimuth``. The function is applicable to both
fixed-tilt and one-axis tracking systems.
(:issue:`1689`, :pull:`1725`, :pull:`1962`)
+* Add function :py:func:`pvlib.albedo.inland_water_dvoracek`, to calculate the
+ albedo for inland water bodies.
+ (:pull:`2079`)
* Added conversion functions from spectral response ([A/W]) to quantum
efficiency ([unitless]) and vice versa. The conversion functions are
:py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
@@ -55,4 +58,5 @@ Contributors
* Cliff Hansen (:ghuser:`cwhanse`)
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
+* Ioannis Sifnaios (:ghuser:`IoannisSifnaios`)
* Mark Campanelli (:ghuser:`markcampanelli`)
diff --git a/pvlib/__init__.py b/pvlib/__init__.py
index 413af8f607..b5b07866a4 100644
--- a/pvlib/__init__.py
+++ b/pvlib/__init__.py
@@ -4,6 +4,7 @@
# list spectrum first so it's available for atmosphere & pvsystem (GH 1628)
spectrum,
+ albedo,
atmosphere,
bifacial,
clearsky,
diff --git a/pvlib/albedo.py b/pvlib/albedo.py
new file mode 100644
index 0000000000..98b920dddb
--- /dev/null
+++ b/pvlib/albedo.py
@@ -0,0 +1,149 @@
+"""
+The ``albedo`` module contains functions for modeling albedo.
+"""
+
+from pvlib.tools import sind
+import numpy as np
+import pandas as pd
+
+
+WATER_COLOR_COEFFS = {
+ 'clear_water_no_waves': 0.13,
+ 'clear_water_ripples_up_to_2.5cm': 0.16,
+ 'clear_water_ripples_larger_than_2.5cm_occasional_whitecaps': 0.23,
+ 'clear_water_frequent_whitecaps': 0.3,
+ 'green_water_ripples_up_to_2.5cm': 0.22,
+ 'muddy_water_no_waves': 0.19
+}
+
+WATER_ROUGHNESS_COEFFS = {
+ 'clear_water_no_waves': 0.29,
+ 'clear_water_ripples_up_to_2.5cm': 0.7,
+ 'clear_water_ripples_larger_than_2.5cm_occasional_whitecaps': 1.25,
+ 'clear_water_frequent_whitecaps': 2,
+ 'green_water_ripples_up_to_2.5cm': 0.7,
+ 'muddy_water_no_waves': 0.29
+}
+
+
+def inland_water_dvoracek(solar_elevation, surface_condition=None,
+ color_coeff=None, wave_roughness_coeff=None):
+ r"""
+ Estimation of albedo for inland water bodies.
+
+ The available surface conditions are for inland water bodies, e.g., lakes
+ and ponds. For ocean/open sea, see
+ :const:`pvlib.irradiance.SURFACE_ALBEDOS`.
+
+ Parameters
+ ----------
+ solar_elevation : numeric
+ Sun elevation angle. [degrees]
+
+ surface_condition : string, optional
+ If supplied, overrides ``color_coeff`` and ``wave_roughness_coeff``.
+ ``surface_condition`` can be one of the following:
+
+ * ``'clear_water_no_waves'``
+ * ``'clear_water_ripples_up_to_2.5cm'``
+ * ``'clear_water_ripples_larger_than_2.5cm_occasional_whitecaps'``
+ * ``'clear_water_frequent_whitecaps'``
+ * ``'green_water_ripples_up_to_2.5cm'``
+ * ``'muddy_water_no_waves'``
+
+ color_coeff : float, optional
+ Water color coefficient. [-]
+
+ wave_roughness_coeff : float, optional
+ Water wave roughness coefficient. [-]
+
+ Returns
+ -------
+ albedo : numeric
+ Albedo for inland water bodies. [-]
+
+ Raises
+ ------
+ ValueError
+ If neither of ``surface_condition`` nor a combination of
+ ``color_coeff`` and ``wave_roughness_coeff`` are given.
+ If ``surface_condition`` and any of ``color_coeff`` or
+ ``wave_roughness_coeff`` are given. These parameters are
+ mutually exclusive.
+
+ KeyError
+ If ``surface_condition`` is invalid.
+
+ Notes
+ -----
+ The equation for calculating the albedo :math:`\rho` is given by
+
+ .. math::
+ :label: albedo
+
+ \rho = c^{(r \cdot \sin(\alpha) + 1)}
+
+ Inputs to the model are the water color coefficient :math:`c` [-], the
+ water wave roughness coefficient :math:`r` [-] and the solar elevation
+ :math:`\alpha` [degrees]. Parameters are provided in [1]_ , and are coded
+ for convenience in :data:`~pvlib.albedo.WATER_COLOR_COEFFS` and
+ :data:`~pvlib.albedo.WATER_ROUGHNESS_COEFFS`. The values of these
+ coefficients are experimentally determined.
+
+ +------------------------+-------------------+-------------------------+
+ | Surface and condition | Color coefficient | Wave roughness |
+ | | (:math:`c`) | coefficient (:math:`r`) |
+ +========================+===================+=========================+
+ | Clear water, no waves | 0.13 | 0.29 |
+ +------------------------+-------------------+-------------------------+
+ | Clear water, ripples | 0.16 | 0.70 |
+ | up to 2.5 cm | | |
+ +------------------------+-------------------+-------------------------+
+ | Clear water, ripples | 0.23 | 1.25 |
+ | larger than 2.5 cm | | |
+ | (occasional whitecaps) | | |
+ +------------------------+-------------------+-------------------------+
+ | Clear water, | 0.30 | 2.00 |
+ | frequent whitecaps | | |
+ +------------------------+-------------------+-------------------------+
+ | Green water, ripples | 0.22 | 0.70 |
+ | up to 2.5cm | | |
+ +------------------------+-------------------+-------------------------+
+ | Muddy water, no waves | 0.19 | 0.29 |
+ +------------------------+-------------------+-------------------------+
+
+ References
+ ----------
+ .. [1] Dvoracek M.J., Hannabas B. (1990). "Prediction of albedo for use in
+ evapotranspiration and irrigation scheduling." IN: Visions of the Future
+ American Society of Agricultural Engineers 04-90: 692-699.
+ """
+
+ if surface_condition is not None and (
+ color_coeff is None and wave_roughness_coeff is None
+ ):
+ # use surface_condition
+ color_coeff = WATER_COLOR_COEFFS[surface_condition]
+ wave_roughness_coeff = WATER_ROUGHNESS_COEFFS[surface_condition]
+
+ elif surface_condition is None and not (
+ color_coeff is None or wave_roughness_coeff is None
+ ):
+ # use provided color_coeff and wave_roughness_coeff
+ pass
+ else:
+ raise ValueError(
+ "Either a `surface_condition` has to be chosen or"
+ " a combination of `color_coeff` and"
+ " `wave_roughness_coeff`.")
+
+ solar_elevation_positive = np.where(solar_elevation < 0, 0,
+ solar_elevation)
+
+ albedo = color_coeff ** (wave_roughness_coeff *
+ sind(solar_elevation_positive) + 1)
+
+ if isinstance(solar_elevation, pd.Series):
+ albedo = pd.Series(albedo, index=solar_elevation.index)
+
+ return albedo
| diff --git a/pvlib/tests/test_albedo.py b/pvlib/tests/test_albedo.py
new file mode 100644
index 0000000000..5e4c35258a
--- /dev/null
+++ b/pvlib/tests/test_albedo.py
@@ -0,0 +1,84 @@
+import numpy as np
+import pandas as pd
+import pytest
+from pvlib import albedo
+
+from .conftest import assert_series_equal
+from numpy.testing import assert_allclose
+
+
+def test_inland_water_dvoracek_default():
+ result = albedo.inland_water_dvoracek(solar_elevation=90,
+ color_coeff=0.13,
+ wave_roughness_coeff=0.29)
+ assert_allclose(result, 0.072, 0.001)
+
+
+def test_inland_water_dvoracek_negative_elevation():
+ result = albedo.inland_water_dvoracek(solar_elevation=-60,
+ color_coeff=0.13,
+ wave_roughness_coeff=0.29)
+ assert_allclose(result, 0.13, 0.01)
+
+
+def test_inland_water_dvoracek_string_surface_condition():
+ result = albedo.inland_water_dvoracek(solar_elevation=90,
+ surface_condition='clear_water_no_waves') # noqa: E501
+ assert_allclose(result, 0.072, 0.001)
+
+
+def test_inland_water_dvoracek_ndarray():
+ solar_elevs = np.array([-50, 0, 20, 60, 90])
+ color_coeffs = np.array([0.1, 0.1, 0.2, 0.3, 0.4])
+ roughness_coeffs = np.array([0.3, 0.3, 0.8, 1.5, 2])
+ result = albedo.inland_water_dvoracek(solar_elevation=solar_elevs,
+ color_coeff=color_coeffs,
+ wave_roughness_coeff=roughness_coeffs) # noqa: E501
+ expected = np.array([0.1, 0.1, 0.12875, 0.06278, 0.064])
+ assert_allclose(expected, result, atol=1e-5)
+
+
+def test_inland_water_dvoracek_series():
+ times = pd.date_range(start="2015-01-01 00:00", end="2015-01-02 00:00",
+ freq="6h")
+ solar_elevs = pd.Series([-50, 0, 20, 60, 90], index=times)
+ color_coeffs = pd.Series([0.1, 0.1, 0.2, 0.3, 0.4], index=times)
+ roughness_coeffs = pd.Series([0.1, 0.3, 0.8, 1.5, 2], index=times)
+ result = albedo.inland_water_dvoracek(solar_elevation=solar_elevs,
+ color_coeff=color_coeffs,
+ wave_roughness_coeff=roughness_coeffs) # noqa: E501
+ expected = pd.Series([0.1, 0.1, 0.12875, 0.06278, 0.064], index=times)
+ assert_series_equal(expected, result, atol=1e-5)
+
+
+def test_inland_water_dvoracek_series_mix_with_array():
+ times = pd.date_range(start="2015-01-01 00:00", end="2015-01-01 06:00",
+ freq="6h")
+ solar_elevs = pd.Series([45, 60], index=times)
+ color_coeffs = 0.13
+ roughness_coeffs = 0.29
+ result = albedo.inland_water_dvoracek(solar_elevation=solar_elevs,
+ color_coeff=color_coeffs,
+ wave_roughness_coeff=roughness_coeffs) # noqa: E501
+ expected = pd.Series([0.08555, 0.07787], index=times)
+ assert_series_equal(expected, result, atol=1e-5)
+
+
+def test_inland_water_dvoracek_invalid():
+ with pytest.raises(ValueError, match='Either a `surface_condition` has to '
+ 'be chosen or a combination of `color_coeff` and'
+ ' `wave_roughness_coeff`.'): # no surface info given
+ albedo.inland_water_dvoracek(solar_elevation=45)
+ with pytest.raises(KeyError, match='not_a_surface_type'): # invalid type
+ albedo.inland_water_dvoracek(solar_elevation=45,
+ surface_condition='not_a_surface_type')
+ with pytest.raises(ValueError, match='Either a `surface_condition` has to '
+ 'be chosen or a combination of `color_coeff` and'
+ ' `wave_roughness_coeff`.'): # only one coeff given
+ albedo.inland_water_dvoracek(solar_elevation=45,
+ color_coeff=0.13)
+ with pytest.raises(ValueError, match='Either a `surface_condition` has to '
+ 'be chosen or a combination of `color_coeff` and'
+ ' `wave_roughness_coeff`.'): # only one coeff given
+ albedo.inland_water_dvoracek(solar_elevation=45,
+ wave_roughness_coeff=0.29)
| diff --git a/docs/sphinx/source/reference/irradiance/albedo.rst b/docs/sphinx/source/reference/irradiance/albedo.rst
new file mode 100644
index 0000000000..868a065d1a
--- /dev/null
+++ b/docs/sphinx/source/reference/irradiance/albedo.rst
@@ -0,0 +1,9 @@
+.. currentmodule:: pvlib
+
+Albedo
+------
+
+.. autosummary::
+ :toctree: ../generated/
+
+ albedo.inland_water_dvoracek
diff --git a/docs/sphinx/source/reference/irradiance/index.rst b/docs/sphinx/source/reference/irradiance/index.rst
index 2263a2d2c1..72064cccbc 100644
--- a/docs/sphinx/source/reference/irradiance/index.rst
+++ b/docs/sphinx/source/reference/irradiance/index.rst
@@ -11,3 +11,4 @@ Irradiance
transposition
decomposition
clearness-index
+ albedo
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 14694d0fc4..3fa2aa41df 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -28,6 +28,9 @@ Enhancements
shade perpendicular to ``axis_azimuth``. The function is applicable to both
fixed-tilt and one-axis tracking systems.
(:issue:`1689`, :pull:`1725`, :pull:`1962`)
+* Add function :py:func:`pvlib.albedo.inland_water_dvoracek`, to calculate the
+ albedo for inland water bodies.
+ (:pull:`2079`)
* Added conversion functions from spectral response ([A/W]) to quantum
efficiency ([unitless]) and vice versa. The conversion functions are
:py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
@@ -55,4 +58,5 @@ Contributors
* Cliff Hansen (:ghuser:`cwhanse`)
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
+* Ioannis Sifnaios (:ghuser:`IoannisSifnaios`)
* Mark Campanelli (:ghuser:`markcampanelli`)
| [
{
"components": [
{
"doc": "Estimation of albedo for inland water bodies.\n\nThe available surface conditions are for inland water bodies, e.g., lakes\nand ponds. For ocean/open sea, see\n:const:`pvlib.irradiance.SURFACE_ALBEDOS`.\n\nParameters\n----------\nsolar_elevation : numeric\n Sun eleva... | [
"pvlib/tests/test_albedo.py::test_inland_water_dvoracek_default",
"pvlib/tests/test_albedo.py::test_inland_water_dvoracek_negative_elevation",
"pvlib/tests/test_albedo.py::test_inland_water_dvoracek_string_surface_condition",
"pvlib/tests/test_albedo.py::test_inland_water_dvoracek_ndarray",
"pvlib/tests/tes... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add albedo function for inland water bodies
- [X] Part of #2068
- [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.
This PR adds a function for calculating the albedo of inland water bodies as described in the paper: Dvoracek M.J., Hannabas B. (1990). "Prediction of albedo for use in evapotranspiration and irrigation scheduling." IN: Visions of the Future, American Society of Agricultural Engineers 04-90: 692-699.
You can contact me if you would like me to send you the paper.
----------
</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/albedo.py]
(definition of inland_water_dvoracek:)
def inland_water_dvoracek(solar_elevation, surface_condition=None, color_coeff=None, wave_roughness_coeff=None):
"""Estimation of albedo for inland water bodies.
The available surface conditions are for inland water bodies, e.g., lakes
and ponds. For ocean/open sea, see
:const:`pvlib.irradiance.SURFACE_ALBEDOS`.
Parameters
----------
solar_elevation : numeric
Sun elevation angle. [degrees]
surface_condition : string, optional
If supplied, overrides ``color_coeff`` and ``wave_roughness_coeff``.
``surface_condition`` can be one of the following:
* ``'clear_water_no_waves'``
* ``'clear_water_ripples_up_to_2.5cm'``
* ``'clear_water_ripples_larger_than_2.5cm_occasional_whitecaps'``
* ``'clear_water_frequent_whitecaps'``
* ``'green_water_ripples_up_to_2.5cm'``
* ``'muddy_water_no_waves'``
color_coeff : float, optional
Water color coefficient. [-]
wave_roughness_coeff : float, optional
Water wave roughness coefficient. [-]
Returns
-------
albedo : numeric
Albedo for inland water bodies. [-]
Raises
------
ValueError
If neither of ``surface_condition`` nor a combination of
``color_coeff`` and ``wave_roughness_coeff`` are given.
If ``surface_condition`` and any of ``color_coeff`` or
``wave_roughness_coeff`` are given. These parameters are
mutually exclusive.
KeyError
If ``surface_condition`` is invalid.
Notes
-----
The equation for calculating the albedo :math:`\rho` is given by
.. math::
:label: albedo
\rho = c^{(r \cdot \sin(\alpha) + 1)}
Inputs to the model are the water color coefficient :math:`c` [-], the
water wave roughness coefficient :math:`r` [-] and the solar elevation
:math:`\alpha` [degrees]. Parameters are provided in [1]_ , and are coded
for convenience in :data:`~pvlib.albedo.WATER_COLOR_COEFFS` and
:data:`~pvlib.albedo.WATER_ROUGHNESS_COEFFS`. The values of these
coefficients are experimentally determined.
+------------------------+-------------------+-------------------------+
| Surface and condition | Color coefficient | Wave roughness |
| | (:math:`c`) | coefficient (:math:`r`) |
+========================+===================+=========================+
| Clear water, no waves | 0.13 | 0.29 |
+------------------------+-------------------+-------------------------+
| Clear water, ripples | 0.16 | 0.70 |
| up to 2.5 cm | | |
+------------------------+-------------------+-------------------------+
| Clear water, ripples | 0.23 | 1.25 |
| larger than 2.5 cm | | |
| (occasional whitecaps) | | |
+------------------------+-------------------+-------------------------+
| Clear water, | 0.30 | 2.00 |
| frequent whitecaps | | |
+------------------------+-------------------+-------------------------+
| Green water, ripples | 0.22 | 0.70 |
| up to 2.5cm | | |
+------------------------+-------------------+-------------------------+
| Muddy water, no waves | 0.19 | 0.29 |
+------------------------+-------------------+-------------------------+
References
----------
.. [1] Dvoracek M.J., Hannabas B. (1990). "Prediction of albedo for use in
evapotranspiration and irrigation scheduling." IN: Visions of the Future
American Society of Agricultural Engineers 04-90: 692-699."""
[end of new definitions in pvlib/albedo.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>> | 6af80da35a7c96059c534ee38be9123bcfc7f50f | |
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(
| [] | [
"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_r... | 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>
</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 | |
googleapis__python-aiplatform-3863 | 3,863 | googleapis/python-aiplatform | null | 831c8e45ee88f70efcdaba7dfed1856837074357 | 2024-06-04T18:17:31Z | diff --git a/samples/model-builder/feature_store/create_optimized_private_feature_online_store_sample.py b/samples/model-builder/feature_store/create_optimized_private_feature_online_store_sample.py
new file mode 100644
index 0000000000..46165e8943
--- /dev/null
+++ b/samples/model-builder/feature_store/create_optimized_private_feature_online_store_sample.py
@@ -0,0 +1,38 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+# [START aiplatform_sdk_create_optimized_private_feature_online_store_sample]
+
+from typing import List
+
+from google.cloud import aiplatform
+from vertexai.resources.preview import feature_store
+
+
+def create_optimized_private_feature_online_store_sample(
+ project: str,
+ location: str,
+ feature_online_store_id: str,
+ project_allowlist: List[str],
+):
+ aiplatform.init(project=project, location=location)
+ fos = feature_store.FeatureOnlineStore.create_optimized_store(
+ name=feature_online_store_id,
+ enable_private_service_connect=True,
+ project_allowlist=project_allowlist,
+ )
+ return fos
+
+
+# [END aiplatform_sdk_create_optimized_private_feature_online_store_sample]
| diff --git a/samples/model-builder/conftest.py b/samples/model-builder/conftest.py
index 9350bec29b..16d9057046 100644
--- a/samples/model-builder/conftest.py
+++ b/samples/model-builder/conftest.py
@@ -716,6 +716,15 @@ def mock_create_optimized_public_online_store(mock_feature_online_store):
yield mock_create_optimized_store
+@pytest.fixture
+def mock_create_optimized_private_online_store(mock_feature_online_store):
+ with patch.object(
+ preview_resources.FeatureOnlineStore, "create_optimized_store"
+ ) as mock_create_optimized_store:
+ mock_create_optimized_store.return_value = mock_feature_online_store
+ yield mock_create_optimized_store
+
+
"""
----------------------------------------------------------------------------
Experiment Tracking Fixtures
diff --git a/samples/model-builder/feature_store/create_optimized_private_feature_online_store_sample_test.py b/samples/model-builder/feature_store/create_optimized_private_feature_online_store_sample_test.py
new file mode 100644
index 0000000000..657dc5eaee
--- /dev/null
+++ b/samples/model-builder/feature_store/create_optimized_private_feature_online_store_sample_test.py
@@ -0,0 +1,38 @@
+# Copyright 2024 Google LLC
+#
+# 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
+#
+# https://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.
+
+from feature_store import create_optimized_private_feature_online_store_sample
+import test_constants as constants
+
+
+def test_create_optimized_feature_online_store_sample(
+ mock_sdk_init, mock_create_optimized_private_online_store
+):
+
+ create_optimized_private_feature_online_store_sample.create_optimized_private_feature_online_store_sample(
+ project=constants.PROJECT,
+ location=constants.LOCATION,
+ feature_online_store_id=constants.FEATURE_ONLINE_STORE_ID,
+ project_allowlist=constants.PROJECT_ALLOWLISTED,
+ )
+
+ mock_sdk_init.assert_called_once_with(
+ project=constants.PROJECT, location=constants.LOCATION
+ )
+
+ mock_create_optimized_private_online_store.assert_called_once_with(
+ name=constants.FEATURE_ONLINE_STORE_ID,
+ enable_private_service_connect=True,
+ project_allowlist=constants.PROJECT_ALLOWLISTED,
+ )
diff --git a/samples/model-builder/test_constants.py b/samples/model-builder/test_constants.py
index 43e6b7b1de..3571e8d9cc 100644
--- a/samples/model-builder/test_constants.py
+++ b/samples/model-builder/test_constants.py
@@ -254,6 +254,7 @@
# Feature online store constants
FEATURE_ONLINE_STORE_ID = "sample_feature_online_store"
+PROJECT_ALLOWLISTED = ["test-project"]
TABULAR_TARGET_COLUMN = "target_column"
FORECASTNG_TIME_COLUMN = "date"
| [
{
"components": [
{
"doc": "",
"lines": [
23,
35
],
"name": "create_optimized_private_feature_online_store_sample",
"signature": "def create_optimized_private_feature_online_store_sample( project: str, location: str, feature_online_store_id: str,... | [
"samples/model-builder/feature_store/create_optimized_private_feature_online_store_sample_test.py::test_create_optimized_feature_online_store_sample"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Add sample code show how to create an optimized private online store in Vertex AI Feature Store.
feat: Add sample code show how to create an optimized private online store in Vertex AI Feature Store.
----------
</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/feature_store/create_optimized_private_feature_online_store_sample.py]
(definition of create_optimized_private_feature_online_store_sample:)
def create_optimized_private_feature_online_store_sample( project: str, location: str, feature_online_store_id: str, project_allowlist: List[str], ):
[end of new definitions in samples/model-builder/feature_store/create_optimized_private_feature_online_store_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 | ||
huggingface__huggingface_hub-2314 | 2,314 | huggingface/huggingface_hub | null | e43874a754e32eb1e3cc4c569f6471be12e7cd61 | 2024-06-04T16:00:46Z | diff --git a/docs/source/en/package_reference/serialization.md b/docs/source/en/package_reference/serialization.md
index f63d4e343a..c2a7388091 100644
--- a/docs/source/en/package_reference/serialization.md
+++ b/docs/source/en/package_reference/serialization.md
@@ -4,15 +4,17 @@ rendered properly in your Markdown viewer.
# Serialization
-`huggingface_hub` contains helpers to help ML libraries to serialize models weights in a standardized way. This part of the lib is still under development and will be improved in future releases. The goal is to harmonize how weights are serialized on the Hub, both to remove code duplication across libraries and to foster conventions on the Hub.
+`huggingface_hub` contains helpers to help ML libraries serialize models weights in a standardized way. This part of the lib is still under development and will be improved in future releases. The goal is to harmonize how weights are serialized on the Hub, both to remove code duplication across libraries and to foster conventions on the Hub.
-## Split state dict into shards
+## Save torch state dict
+
+The main helper of the `serialization` module takes a state dictionary as input (e.g. a mapping between layer names and related tensors), splits it into several shards while creating a proper index in the process and save everything to disk. At the moment, only `torch` tensors are supported. Under the hood, it delegates the logic to split the state dictionary to [`split_torch_state_dict_into_shards`].
-At the moment, this module contains a single helper that takes a state dictionary (e.g. a mapping between layer names and related tensors) and split it into several shards, while creating a proper index in the process. This helper is available for `torch`, `tensorflow` and `numpy` tensors and is designed to be easily extended to any other ML frameworks.
+[[autodoc]] huggingface_hub.save_torch_state_dict
-### split_numpy_state_dict_into_shards
+## Split state dict into shards
-[[autodoc]] huggingface_hub.split_numpy_state_dict_into_shards
+The `serialization` module also contains low-level helpers to split a state dictionary into several shards, while creating a proper index in the process. These helpers are available for `torch` and `tensorflow` tensors and are designed to be easily extended to any other ML frameworks.
### split_tf_state_dict_into_shards
diff --git a/docs/source/ko/package_reference/serialization.md b/docs/source/ko/package_reference/serialization.md
index a3b515c1e7..d026052eda 100644
--- a/docs/source/ko/package_reference/serialization.md
+++ b/docs/source/ko/package_reference/serialization.md
@@ -10,10 +10,6 @@ rendered properly in your Markdown viewer.
현재 이 모듈은 상태 딕셔너리(예: 레이어 이름과 관련 텐서 간의 매핑)를 받아 여러 샤드로 나누고, 이 과정에서 적절한 인덱스를 생성하는 단일 헬퍼를 포함하고 있습니다. 이 헬퍼는 `torch`, `tensorflow`, `numpy` 텐서에 사용 가능하며, 다른 ML 프레임워크로 쉽게 확장될 수 있도록 설계되었습니다.
-### split_numpy_state_dict_into_shards[[huggingface_hub.split_numpy_state_dict_into_shards]]
-
-[[autodoc]] huggingface_hub.split_numpy_state_dict_into_shards
-
### split_tf_state_dict_into_shards[[huggingface_hub.split_tf_state_dict_into_shards]]
[[autodoc]] huggingface_hub.split_tf_state_dict_into_shards
diff --git a/src/huggingface_hub/__init__.py b/src/huggingface_hub/__init__.py
index fdbd33d6a9..41d64f9f1b 100644
--- a/src/huggingface_hub/__init__.py
+++ b/src/huggingface_hub/__init__.py
@@ -424,7 +424,7 @@
"serialization": [
"StateDictSplit",
"get_torch_storage_id",
- "split_numpy_state_dict_into_shards",
+ "save_torch_state_dict",
"split_state_dict_into_shards_factory",
"split_tf_state_dict_into_shards",
"split_torch_state_dict_into_shards",
@@ -904,7 +904,7 @@ def __dir__():
from .serialization import (
StateDictSplit, # noqa: F401
get_torch_storage_id, # noqa: F401
- split_numpy_state_dict_into_shards, # noqa: F401
+ save_torch_state_dict, # noqa: F401
split_state_dict_into_shards_factory, # noqa: F401
split_tf_state_dict_into_shards, # noqa: F401
split_torch_state_dict_into_shards, # noqa: F401
diff --git a/src/huggingface_hub/constants.py b/src/huggingface_hub/constants.py
index fc6d8c5e44..4e999af621 100644
--- a/src/huggingface_hub/constants.py
+++ b/src/huggingface_hub/constants.py
@@ -37,6 +37,12 @@ def _as_int(value: Optional[str]) -> Optional[int]:
DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024
HF_TRANSFER_CONCURRENCY = 100
+# Constants for serialization
+
+PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors instead
+SAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors"
+TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5"
+
# Constants for safetensors repos
SAFETENSORS_SINGLE_FILE = "model.safetensors"
diff --git a/src/huggingface_hub/serialization/__init__.py b/src/huggingface_hub/serialization/__init__.py
index 2d3fe3aa37..2ae8f4aa1d 100644
--- a/src/huggingface_hub/serialization/__init__.py
+++ b/src/huggingface_hub/serialization/__init__.py
@@ -15,6 +15,5 @@
"""Contains helpers to serialize tensors."""
from ._base import StateDictSplit, split_state_dict_into_shards_factory
-from ._numpy import split_numpy_state_dict_into_shards
from ._tensorflow import split_tf_state_dict_into_shards
-from ._torch import get_torch_storage_id, split_torch_state_dict_into_shards
+from ._torch import get_torch_storage_id, save_torch_state_dict, split_torch_state_dict_into_shards
diff --git a/src/huggingface_hub/serialization/_base.py b/src/huggingface_hub/serialization/_base.py
index e16e4a8137..c08d39b5ae 100644
--- a/src/huggingface_hub/serialization/_base.py
+++ b/src/huggingface_hub/serialization/_base.py
@@ -23,8 +23,14 @@
TensorSizeFn_T = Callable[[TensorT], int]
StorageIDFn_T = Callable[[TensorT], Optional[Any]]
-MAX_SHARD_SIZE = 5_000_000_000 # 5GB
-FILENAME_PATTERN = "model{suffix}.safetensors"
+MAX_SHARD_SIZE = "5GB"
+SIZE_UNITS = {
+ "TB": 10**12,
+ "GB": 10**9,
+ "MB": 10**6,
+ "KB": 10**3,
+}
+
logger = logging.get_logger(__file__)
@@ -44,8 +50,8 @@ def split_state_dict_into_shards_factory(
state_dict: Dict[str, TensorT],
*,
get_tensor_size: TensorSizeFn_T,
+ filename_pattern: str,
get_storage_id: StorageIDFn_T = lambda tensor: None,
- filename_pattern: str = FILENAME_PATTERN,
max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
) -> StateDictSplit:
"""
@@ -75,7 +81,6 @@ def split_state_dict_into_shards_factory(
filename_pattern (`str`, *optional*):
The pattern to generate the files names in which the model will be saved. Pattern must be a string that
can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
- Defaults to `"model{suffix}.safetensors"`.
max_shard_size (`int` or `str`, *optional*):
The maximum size of each shard, in bytes. Defaults to 5GB.
@@ -172,14 +177,6 @@ def split_state_dict_into_shards_factory(
)
-SIZE_UNITS = {
- "TB": 10**12,
- "GB": 10**9,
- "MB": 10**6,
- "KB": 10**3,
-}
-
-
def parse_size_to_int(size_as_str: str) -> int:
"""
Parse a size expressed as a string with digits and unit (like `"5MB"`) to an integer (in bytes).
diff --git a/src/huggingface_hub/serialization/_numpy.py b/src/huggingface_hub/serialization/_numpy.py
deleted file mode 100644
index 19b5a26aef..0000000000
--- a/src/huggingface_hub/serialization/_numpy.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# Copyright 2024 The HuggingFace Team. 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.
-"""Contains numpy-specific helpers."""
-
-from typing import TYPE_CHECKING, Dict, Union
-
-from ._base import FILENAME_PATTERN, MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory
-
-
-if TYPE_CHECKING:
- import numpy as np
-
-
-def split_numpy_state_dict_into_shards(
- state_dict: Dict[str, "np.ndarray"],
- *,
- filename_pattern: str = FILENAME_PATTERN,
- max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
-) -> StateDictSplit:
- """
- Split a model state dictionary in shards so that each shard is smaller than a given size.
-
- The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization
- made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we
- have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not
- [6+2+2GB], [6+2GB], [6GB].
-
- <Tip warning={true}>
-
- If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
- size greater than `max_shard_size`.
-
- </Tip>
-
- Args:
- state_dict (`Dict[str, np.ndarray]`):
- The state dictionary to save.
- filename_pattern (`str`, *optional*):
- The pattern to generate the files names in which the model will be saved. Pattern must be a string that
- can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
- Defaults to `"model{suffix}.safetensors"`.
- max_shard_size (`int` or `str`, *optional*):
- The maximum size of each shard, in bytes. Defaults to 5GB.
-
- Returns:
- [`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them.
- """
- return split_state_dict_into_shards_factory(
- state_dict,
- max_shard_size=max_shard_size,
- filename_pattern=filename_pattern,
- get_tensor_size=get_tensor_size,
- )
-
-
-def get_tensor_size(tensor: "np.ndarray") -> int:
- return tensor.nbytes
diff --git a/src/huggingface_hub/serialization/_tensorflow.py b/src/huggingface_hub/serialization/_tensorflow.py
index f3818b0ae3..943ff296b4 100644
--- a/src/huggingface_hub/serialization/_tensorflow.py
+++ b/src/huggingface_hub/serialization/_tensorflow.py
@@ -17,6 +17,7 @@
import re
from typing import TYPE_CHECKING, Dict, Union
+from .. import constants
from ._base import MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory
@@ -27,7 +28,7 @@
def split_tf_state_dict_into_shards(
state_dict: Dict[str, "tf.Tensor"],
*,
- filename_pattern: str = "tf_model{suffix}.h5",
+ filename_pattern: str = constants.TF2_WEIGHTS_FILE_PATTERN,
max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
) -> StateDictSplit:
"""
diff --git a/src/huggingface_hub/serialization/_torch.py b/src/huggingface_hub/serialization/_torch.py
index 349e7312e4..36bac7b284 100644
--- a/src/huggingface_hub/serialization/_torch.py
+++ b/src/huggingface_hub/serialization/_torch.py
@@ -14,12 +14,19 @@
"""Contains pytorch-specific helpers."""
import importlib
+import json
+import os
+import re
from functools import lru_cache
-from typing import TYPE_CHECKING, Dict, Tuple, Union
+from pathlib import Path
+from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
-from ._base import FILENAME_PATTERN, MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory
+from .. import constants, logging
+from ._base import MAX_SHARD_SIZE, StateDictSplit, split_state_dict_into_shards_factory
+logger = logging.get_logger(__file__)
+
if TYPE_CHECKING:
import torch
@@ -27,7 +34,7 @@
def split_torch_state_dict_into_shards(
state_dict: Dict[str, "torch.Tensor"],
*,
- filename_pattern: str = FILENAME_PATTERN,
+ filename_pattern: str = constants.SAFETENSORS_WEIGHTS_FILE_PATTERN,
max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
) -> StateDictSplit:
"""
@@ -38,6 +45,14 @@ def split_torch_state_dict_into_shards(
have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not
[6+2+2GB], [6+2GB], [6GB].
+
+ <Tip>
+
+ To save a model state dictionary to the disk, see [`save_torch_state_dict`]. This helper uses
+ `split_torch_state_dict_into_shards` under the hood.
+
+ </Tip>
+
<Tip warning={true}>
If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
@@ -92,6 +107,125 @@ def split_torch_state_dict_into_shards(
)
+def save_torch_state_dict(
+ state_dict: Dict[str, "torch.Tensor"],
+ save_directory: Union[str, Path],
+ *,
+ safe_serialization: bool = True,
+ filename_pattern: Optional[str] = None,
+ max_shard_size: Union[int, str] = MAX_SHARD_SIZE,
+) -> None:
+ """
+ Save a model state dictionary to the disk.
+
+ The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
+ saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
+ an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
+ [`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
+ safetensors (the default). Otherwise, the shards are saved as pickle.
+
+ Before saving the model, the `save_directory` is cleaned from any previous shard files.
+
+ <Tip warning={true}>
+
+ If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
+ size greater than `max_shard_size`.
+
+ </Tip>
+
+ Args:
+ state_dict (`Dict[str, torch.Tensor]`):
+ The state dictionary to save.
+ save_directory (`str` or `Path`):
+ The directory in which the model will be saved.
+ safe_serialization (`bool`, *optional*):
+ Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
+ Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
+ in a future version.
+ filename_pattern (`str`, *optional*):
+ The pattern to generate the files names in which the model will be saved. Pattern must be a string that
+ can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
+ Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
+ parameter.
+ max_shard_size (`int` or `str`, *optional*):
+ The maximum size of each shard, in bytes. Defaults to 5GB.
+
+ Example:
+
+ ```py
+ >>> from huggingface_hub import save_torch_state_dict
+ >>> model = ... # A PyTorch model
+
+ # Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
+ >>> state_dict = model_to_save.state_dict()
+ >>> save_torch_state_dict(state_dict, "path/to/folder")
+ ```
+ """
+ save_directory = str(save_directory)
+
+ if filename_pattern is None:
+ filename_pattern = (
+ constants.SAFETENSORS_WEIGHTS_FILE_PATTERN
+ if safe_serialization
+ else constants.PYTORCH_WEIGHTS_FILE_PATTERN
+ )
+
+ # Imports correct library
+ if safe_serialization:
+ try:
+ from safetensors.torch import save_file as save_file_fn
+ except ImportError as e:
+ raise ImportError(
+ "Please install `safetensors` to use safe serialization. "
+ "You can install it with `pip install safetensors`."
+ ) from e
+
+ else:
+ from torch import save as save_file_fn # type: ignore[assignment]
+
+ logger.warning(
+ "You are using unsafe serialization. Due to security reasons, it is recommended not to load "
+ "pickled models from untrusted sources. If you intend to share your model, we strongly recommend "
+ "using safe serialization by installing `safetensors` with `pip install safetensors`."
+ )
+
+ # Split dict
+ state_dict_split = split_torch_state_dict_into_shards(
+ state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size
+ )
+
+ # Clean the folder from previous save
+ existing_files_regex = re.compile(filename_pattern.format(suffix=r"(-\d{5}-of-\d{5})?") + r"(\.index\.json)?")
+ for filename in os.listdir(save_directory):
+ if existing_files_regex.match(filename):
+ try:
+ logger.debug(f"Removing existing file '{filename}' from folder.")
+ os.remove(os.path.join(save_directory, filename))
+ except Exception as e:
+ logger.warning(f"Error when trying to remove existing '{filename}' from folder: {e}. Continuing...")
+
+ # Save each shard
+ safe_file_kwargs = {"metadata": {"format": "pt"}} if safe_serialization else {}
+ for filename, tensors in state_dict_split.filename_to_tensors.items():
+ shard = {tensor: state_dict[tensor] for tensor in tensors}
+ save_file_fn(shard, os.path.join(save_directory, filename), **safe_file_kwargs)
+ logger.debug(f"Shard saved to {filename}")
+
+ # Save the index (if any)
+ if state_dict_split.is_sharded:
+ index_path = filename_pattern.format(suffix="") + ".index.json"
+ index = {"metadata": state_dict_split.metadata, "weight_map": state_dict_split.tensor_to_filename}
+ with open(os.path.join(save_directory, index_path), "w") as f:
+ json.dump(index, f, indent=2)
+ logger.info(
+ f"The model is bigger than the maximum size per checkpoint ({max_shard_size}). "
+ f"Model weighs have been saved in {len(state_dict_split.filename_to_tensors)} checkpoint shards. "
+ f"You can find where each parameters has been saved in the index located at {index_path}."
+ )
+
+ logger.info(f"Model weights successfully saved to {save_directory}!")
+
+
def get_torch_storage_id(tensor: "torch.Tensor") -> Tuple["torch.device", int, int]:
"""
Return unique identifier to a tensor storage.
| diff --git a/tests/test_serialization.py b/tests/test_serialization.py
index 47a78d5e2e..9af9256389 100644
--- a/tests/test_serialization.py
+++ b/tests/test_serialization.py
@@ -1,21 +1,19 @@
+import json
+from pathlib import Path
+from typing import TYPE_CHECKING, Dict, List
+
import pytest
-from huggingface_hub.serialization import split_state_dict_into_shards_factory
+from huggingface_hub.serialization import save_torch_state_dict, split_state_dict_into_shards_factory
from huggingface_hub.serialization._base import parse_size_to_int
-from huggingface_hub.serialization._numpy import get_tensor_size as get_tensor_size_numpy
from huggingface_hub.serialization._tensorflow import get_tensor_size as get_tensor_size_tensorflow
from huggingface_hub.serialization._torch import get_tensor_size as get_tensor_size_torch
from .testing_utils import requires
-DUMMY_STATE_DICT = {
- "layer_1": [6],
- "layer_2": [10],
- "layer_3": [30],
- "layer_4": [2],
- "layer_5": [2],
-}
+if TYPE_CHECKING:
+ import torch
def _dummy_get_storage_id(item):
@@ -26,9 +24,36 @@ def _dummy_get_tensor_size(item):
return sum(item)
-def test_single_shard():
+@pytest.fixture
+def dummy_state_dict() -> Dict[str, List[int]]:
+ return {
+ "layer_1": [6],
+ "layer_2": [10],
+ "layer_3": [30],
+ "layer_4": [2],
+ "layer_5": [2],
+ }
+
+
+@pytest.fixture
+def torch_state_dict() -> Dict[str, "torch.Tensor"]:
+ try:
+ import torch
+
+ return {
+ "layer_1": torch.tensor([4]),
+ "layer_2": torch.tensor([10]),
+ "layer_3": torch.tensor([30]),
+ "layer_4": torch.tensor([2]),
+ "layer_5": torch.tensor([2]),
+ }
+ except ImportError:
+ pytest.skip("torch is not available")
+
+
+def test_single_shard(dummy_state_dict):
state_dict_split = split_state_dict_into_shards_factory(
- DUMMY_STATE_DICT,
+ dummy_state_dict,
get_storage_id=_dummy_get_storage_id,
get_tensor_size=_dummy_get_tensor_size,
max_shard_size=100, # large shard size => only one shard
@@ -49,9 +74,9 @@ def test_single_shard():
assert state_dict_split.metadata == {"total_size": 50}
-def test_multiple_shards():
+def test_multiple_shards(dummy_state_dict):
state_dict_split = split_state_dict_into_shards_factory(
- DUMMY_STATE_DICT,
+ dummy_state_dict,
get_storage_id=_dummy_get_storage_id,
get_tensor_size=_dummy_get_tensor_size,
max_shard_size=10, # small shard size => multiple shards
@@ -88,6 +113,7 @@ def test_tensor_same_storage():
get_storage_id=lambda x: (x[0]), # dummy for test: storage id based on first element
get_tensor_size=_dummy_get_tensor_size,
max_shard_size=1,
+ filename_pattern="model{suffix}.safetensors",
)
assert state_dict_split.is_sharded
assert state_dict_split.filename_to_tensors == {
@@ -104,14 +130,6 @@ def test_tensor_same_storage():
assert state_dict_split.metadata == {"total_size": 3} # count them once
-@requires("numpy")
-def test_get_tensor_size_numpy():
- import numpy as np
-
- assert get_tensor_size_numpy(np.array([1, 2, 3, 4, 5], dtype=np.float64)) == 5 * 8
- assert get_tensor_size_numpy(np.array([1, 2, 3, 4, 5], dtype=np.float16)) == 5 * 2
-
-
@requires("tensorflow")
def test_get_tensor_size_tensorflow():
import tensorflow as tf
@@ -140,3 +158,116 @@ def test_parse_size_to_int():
with pytest.raises(ValueError, match="Could not parse the size value"):
parse_size_to_int("1ooKB") # not a float
+
+
+def test_save_torch_state_dict_not_sharded(tmp_path: Path, torch_state_dict: Dict[str, "torch.Tensor"]) -> None:
+ """Save as safetensors without sharding."""
+ save_torch_state_dict(torch_state_dict, tmp_path, max_shard_size="1GB")
+ assert (tmp_path / "model.safetensors").is_file()
+ assert not (tmp_path / "model.safetensors.index.json").is_file()
+
+
+def test_save_torch_state_dict_sharded(tmp_path: Path, torch_state_dict: Dict[str, "torch.Tensor"]) -> None:
+ """Save as safetensors with sharding."""
+ save_torch_state_dict(torch_state_dict, tmp_path, max_shard_size=30)
+ assert not (tmp_path / "model.safetensors").is_file()
+ assert (tmp_path / "model.safetensors.index.json").is_file()
+ assert (tmp_path / "model-00001-of-00002.safetensors").is_file()
+ assert (tmp_path / "model-00001-of-00002.safetensors").is_file()
+
+ assert json.loads((tmp_path / "model.safetensors.index.json").read_text("utf-8")) == {
+ "metadata": {"total_size": 40},
+ "weight_map": {
+ "layer_1": "model-00001-of-00002.safetensors",
+ "layer_2": "model-00001-of-00002.safetensors",
+ "layer_3": "model-00001-of-00002.safetensors",
+ "layer_4": "model-00002-of-00002.safetensors",
+ "layer_5": "model-00002-of-00002.safetensors",
+ },
+ }
+
+
+def test_save_torch_state_dict_unsafe_not_sharded(
+ tmp_path: Path, caplog: pytest.LogCaptureFixture, torch_state_dict: Dict[str, "torch.Tensor"]
+) -> None:
+ """Save as pickle without sharding."""
+ with caplog.at_level("WARNING"):
+ save_torch_state_dict(torch_state_dict, tmp_path, max_shard_size="1GB", safe_serialization=False)
+ assert "we strongly recommend using safe serialization" in caplog.text
+
+ assert (tmp_path / "pytorch_model.bin").is_file()
+ assert not (tmp_path / "pytorch_model.bin.index.json").is_file()
+
+
+def test_save_torch_state_dict_unsafe_sharded(
+ tmp_path: Path, caplog: pytest.LogCaptureFixture, torch_state_dict: Dict[str, "torch.Tensor"]
+) -> None:
+ """Save as pickle with sharding."""
+ # Check logs
+ with caplog.at_level("WARNING"):
+ save_torch_state_dict(torch_state_dict, tmp_path, max_shard_size=30, safe_serialization=False)
+ assert "we strongly recommend using safe serialization" in caplog.text
+
+ assert not (tmp_path / "pytorch_model.bin").is_file()
+ assert (tmp_path / "pytorch_model.bin.index.json").is_file()
+ assert (tmp_path / "pytorch_model-00001-of-00002.bin").is_file()
+ assert (tmp_path / "pytorch_model-00001-of-00002.bin").is_file()
+
+ assert json.loads((tmp_path / "pytorch_model.bin.index.json").read_text("utf-8")) == {
+ "metadata": {"total_size": 40},
+ "weight_map": {
+ "layer_1": "pytorch_model-00001-of-00002.bin",
+ "layer_2": "pytorch_model-00001-of-00002.bin",
+ "layer_3": "pytorch_model-00001-of-00002.bin",
+ "layer_4": "pytorch_model-00002-of-00002.bin",
+ "layer_5": "pytorch_model-00002-of-00002.bin",
+ },
+ }
+
+
+def test_save_torch_state_dict_custom_filename(tmp_path: Path, torch_state_dict: Dict[str, "torch.Tensor"]) -> None:
+ """Custom filename pattern is respected."""
+ # Not sharded
+ save_torch_state_dict(torch_state_dict, tmp_path, filename_pattern="model.variant{suffix}.safetensors")
+ assert (tmp_path / "model.variant.safetensors").is_file()
+
+ # Sharded
+ save_torch_state_dict(
+ torch_state_dict, tmp_path, filename_pattern="model.variant{suffix}.safetensors", max_shard_size=30
+ )
+ assert (tmp_path / "model.variant.safetensors.index.json").is_file()
+ assert (tmp_path / "model.variant-00001-of-00002.safetensors").is_file()
+ assert (tmp_path / "model.variant-00002-of-00002.safetensors").is_file()
+
+
+def test_save_torch_state_dict_delete_existing_files(
+ tmp_path: Path, torch_state_dict: Dict[str, "torch.Tensor"]
+) -> None:
+ """Directory is cleaned before saving new files."""
+ (tmp_path / "model.safetensors").touch()
+ (tmp_path / "model.safetensors.index.json").touch()
+ (tmp_path / "model-00001-of-00003.safetensors").touch()
+ (tmp_path / "model-00002-of-00003.safetensors").touch()
+ (tmp_path / "model-00003-of-00003.safetensors").touch()
+
+ (tmp_path / "pytorch_model.bin").touch()
+ (tmp_path / "pytorch_model.bin.index.json").touch()
+ (tmp_path / "pytorch_model-00001-of-00003.bin").touch()
+ (tmp_path / "pytorch_model-00002-of-00003.bin").touch()
+ (tmp_path / "pytorch_model-00003-of-00003.bin").touch()
+
+ save_torch_state_dict(torch_state_dict, tmp_path)
+ assert (tmp_path / "model.safetensors").stat().st_size > 0 # new file
+
+ # Previous shards have been deleted
+ assert not (tmp_path / "model.safetensors.index.json").is_file() # deleted
+ assert not (tmp_path / "model-00001-of-00003.safetensors").is_file() # deleted
+ assert not (tmp_path / "model-00002-of-00003.safetensors").is_file() # deleted
+ assert not (tmp_path / "model-00003-of-00003.safetensors").is_file() # deleted
+
+ # But not previous pickle files (since saving as safetensors)
+ assert (tmp_path / "pytorch_model.bin").is_file() # not deleted
+ assert (tmp_path / "pytorch_model.bin.index.json").is_file()
+ assert (tmp_path / "pytorch_model-00001-of-00003.bin").is_file()
+ assert (tmp_path / "pytorch_model-00002-of-00003.bin").is_file()
+ assert (tmp_path / "pytorch_model-00003-of-00003.bin").is_file()
| diff --git a/docs/source/en/package_reference/serialization.md b/docs/source/en/package_reference/serialization.md
index f63d4e343a..c2a7388091 100644
--- a/docs/source/en/package_reference/serialization.md
+++ b/docs/source/en/package_reference/serialization.md
@@ -4,15 +4,17 @@ rendered properly in your Markdown viewer.
# Serialization
-`huggingface_hub` contains helpers to help ML libraries to serialize models weights in a standardized way. This part of the lib is still under development and will be improved in future releases. The goal is to harmonize how weights are serialized on the Hub, both to remove code duplication across libraries and to foster conventions on the Hub.
+`huggingface_hub` contains helpers to help ML libraries serialize models weights in a standardized way. This part of the lib is still under development and will be improved in future releases. The goal is to harmonize how weights are serialized on the Hub, both to remove code duplication across libraries and to foster conventions on the Hub.
-## Split state dict into shards
+## Save torch state dict
+
+The main helper of the `serialization` module takes a state dictionary as input (e.g. a mapping between layer names and related tensors), splits it into several shards while creating a proper index in the process and save everything to disk. At the moment, only `torch` tensors are supported. Under the hood, it delegates the logic to split the state dictionary to [`split_torch_state_dict_into_shards`].
-At the moment, this module contains a single helper that takes a state dictionary (e.g. a mapping between layer names and related tensors) and split it into several shards, while creating a proper index in the process. This helper is available for `torch`, `tensorflow` and `numpy` tensors and is designed to be easily extended to any other ML frameworks.
+[[autodoc]] huggingface_hub.save_torch_state_dict
-### split_numpy_state_dict_into_shards
+## Split state dict into shards
-[[autodoc]] huggingface_hub.split_numpy_state_dict_into_shards
+The `serialization` module also contains low-level helpers to split a state dictionary into several shards, while creating a proper index in the process. These helpers are available for `torch` and `tensorflow` tensors and are designed to be easily extended to any other ML frameworks.
### split_tf_state_dict_into_shards
diff --git a/docs/source/ko/package_reference/serialization.md b/docs/source/ko/package_reference/serialization.md
index a3b515c1e7..d026052eda 100644
--- a/docs/source/ko/package_reference/serialization.md
+++ b/docs/source/ko/package_reference/serialization.md
@@ -10,10 +10,6 @@ rendered properly in your Markdown viewer.
현재 이 모듈은 상태 딕셔너리(예: 레이어 이름과 관련 텐서 간의 매핑)를 받아 여러 샤드로 나누고, 이 과정에서 적절한 인덱스를 생성하는 단일 헬퍼를 포함하고 있습니다. 이 헬퍼는 `torch`, `tensorflow`, `numpy` 텐서에 사용 가능하며, 다른 ML 프레임워크로 쉽게 확장될 수 있도록 설계되었습니다.
-### split_numpy_state_dict_into_shards[[huggingface_hub.split_numpy_state_dict_into_shards]]
-
-[[autodoc]] huggingface_hub.split_numpy_state_dict_into_shards
-
### split_tf_state_dict_into_shards[[huggingface_hub.split_tf_state_dict_into_shards]]
[[autodoc]] huggingface_hub.split_tf_state_dict_into_shards
| [
{
"components": [
{
"doc": "Save a model state dictionary to the disk.\n\nThe model state dictionary is split into shards so that each shard is smaller than a given size. The shards are\nsaved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single sha... | [
"tests/test_serialization.py::test_single_shard",
"tests/test_serialization.py::test_multiple_shards",
"tests/test_serialization.py::test_tensor_same_storage",
"tests/test_serialization.py::test_parse_size_to_int"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Serialization: support saving torch state dict to disk
Implement `save_torch_state_dict` to save a torch state dictionary to disk (first part of https://github.com/huggingface/huggingface_hub/issues/2065). It uses `split_torch_state_dict_into_shards` under the hood (https://github.com/huggingface/huggingface_hub/pull/1938).
State dict is saved either to a single file (if less than 5GB) or to shards with the corresponding index.json. By default, shards are saved as `safetensors` but `safe_serialization=False` can be passed to save as pickle. A warning is logged when saving as pickle and hopefully we should be able to dropped support for it when transformers/diffusers/accelerate/... completely phase out from `.bin` saving. cc @LysandreJik I'd like to get your opinion on this. I'm fine with not adding support for .bin files at all but worry it would slow down adoption in our libraries.
For the implementation, I took inspiration from https://github.com/huggingface/diffusers/pull/7830 + accelerate/transformers. What it does:
1. Split state dict into shard (logic already exists)
2. Clean existing directory (remove previous shard/index files)
3. Write shards to disk
4. Write index to disk (optional)
**Example:**
```py
>>> from huggingface_hub import save_torch_state_dict
>>> model = ... # A PyTorch model
# Save state dict to "path/to/folder"
# The model is split into shards of 5GB each and saved as safetensors.
>>> state_dict = model_to_save.state_dict()
>>> save_torch_state_dict(state_dict, "path/to/folder")
```
cc @amyeroberts / @ArthurZucker for transformers, @sayakpaul for diffusers, @SunMarc @muellerzr for accelerate
Happy to get feedback on this type of critical part. The goal is to standardize things to be consistent across libraries so please let me know if you want to add/remove something!
([documentation has also been updated](https://moon-ci-docs.huggingface.co/docs/huggingface_hub/pr_2314/en/package_reference/serialization))
---
note: I also removed `split_numpy_state_dict_into_shards` which is a breaking change but I don't expect anything to break in the wild. Better to just remove it to avoid future maintenance (I shouldn't have added it in the first place).
(failing CI is unrelated)
----------
</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/serialization/_torch.py]
(definition of save_torch_state_dict:)
def save_torch_state_dict( state_dict: Dict[str, "torch.Tensor"], save_directory: Union[str, Path], *, safe_serialization: bool = True, filename_pattern: Optional[str] = None, max_shard_size: Union[int, str] = MAX_SHARD_SIZE, ) -> None:
"""Save a model state dictionary to the disk.
The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
[`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
safetensors (the default). Otherwise, the shards are saved as pickle.
Before saving the model, the `save_directory` is cleaned from any previous shard files.
<Tip warning={true}>
If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
size greater than `max_shard_size`.
</Tip>
Args:
state_dict (`Dict[str, torch.Tensor]`):
The state dictionary to save.
save_directory (`str` or `Path`):
The directory in which the model will be saved.
safe_serialization (`bool`, *optional*):
Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
in a future version.
filename_pattern (`str`, *optional*):
The pattern to generate the files names in which the model will be saved. Pattern must be a string that
can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
parameter.
max_shard_size (`int` or `str`, *optional*):
The maximum size of each shard, in bytes. Defaults to 5GB.
Example:
```py
>>> from huggingface_hub import save_torch_state_dict
>>> model = ... # A PyTorch model
# Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
>>> state_dict = model_to_save.state_dict()
>>> save_torch_state_dict(state_dict, "path/to/folder")
```"""
[end of new definitions in src/huggingface_hub/serialization/_torch.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 | |
deepset-ai__haystack-7795 | 7,795 | deepset-ai/haystack | null | 74df8ed9371d24dd788c4290f5b68348cc1a8896 | 2024-06-04T06:52:54Z | diff --git a/haystack/components/retrievers/in_memory/bm25_retriever.py b/haystack/components/retrievers/in_memory/bm25_retriever.py
index f94186085f..bfbef60e79 100644
--- a/haystack/components/retrievers/in_memory/bm25_retriever.py
+++ b/haystack/components/retrievers/in_memory/bm25_retriever.py
@@ -6,6 +6,7 @@
from haystack import DeserializationError, Document, component, default_from_dict, default_to_dict
from haystack.document_stores.in_memory import InMemoryDocumentStore
+from haystack.document_stores.types import FilterPolicy
@component
@@ -40,6 +41,7 @@ def __init__(
filters: Optional[Dict[str, Any]] = None,
top_k: int = 10,
scale_score: bool = False,
+ filter_policy: FilterPolicy = FilterPolicy.REPLACE,
):
"""
Create the InMemoryBM25Retriever component.
@@ -52,7 +54,7 @@ def __init__(
The maximum number of documents to retrieve.
:param scale_score:
Scales the BM25 score to a unit interval in the range of 0 to 1, where 1 means extremely relevant. If set to `False`, uses raw similarity scores.
-
+ :param filter_policy: The filter policy to apply during retrieval.
:raises ValueError:
If the specified `top_k` is not > 0.
"""
@@ -67,6 +69,7 @@ def __init__(
self.filters = filters
self.top_k = top_k
self.scale_score = scale_score
+ self.filter_policy = filter_policy
def _get_telemetry_data(self) -> Dict[str, Any]:
"""
@@ -83,7 +86,12 @@ def to_dict(self) -> Dict[str, Any]:
"""
docstore = self.document_store.to_dict()
return default_to_dict(
- self, document_store=docstore, filters=self.filters, top_k=self.top_k, scale_score=self.scale_score
+ self,
+ document_store=docstore,
+ filters=self.filters,
+ top_k=self.top_k,
+ scale_score=self.scale_score,
+ filter_policy=self.filter_policy.value,
)
@classmethod
@@ -101,6 +109,8 @@ def from_dict(cls, data: Dict[str, Any]) -> "InMemoryBM25Retriever":
raise DeserializationError("Missing 'document_store' in serialization data")
if "type" not in init_params["document_store"]:
raise DeserializationError("Missing 'type' in document store's serialization data")
+ if "filter_policy" in init_params:
+ init_params["filter_policy"] = FilterPolicy.from_str(init_params["filter_policy"])
data["init_parameters"]["document_store"] = InMemoryDocumentStore.from_dict(
data["init_parameters"]["document_store"]
)
@@ -132,8 +142,10 @@ def run(
:raises ValueError:
If the specified DocumentStore is not found or is not a InMemoryDocumentStore instance.
"""
- if filters is None:
- filters = self.filters
+ if self.filter_policy == FilterPolicy.MERGE and filters:
+ filters = {**(self.filters or {}), **filters}
+ else:
+ filters = filters or self.filters
if top_k is None:
top_k = self.top_k
if scale_score is None:
diff --git a/haystack/components/retrievers/in_memory/embedding_retriever.py b/haystack/components/retrievers/in_memory/embedding_retriever.py
index 97d2ed5914..091de8c12c 100644
--- a/haystack/components/retrievers/in_memory/embedding_retriever.py
+++ b/haystack/components/retrievers/in_memory/embedding_retriever.py
@@ -6,6 +6,7 @@
from haystack import DeserializationError, Document, component, default_from_dict, default_to_dict
from haystack.document_stores.in_memory import InMemoryDocumentStore
+from haystack.document_stores.types import FilterPolicy
@component
@@ -50,6 +51,7 @@ def __init__(
top_k: int = 10,
scale_score: bool = False,
return_embedding: bool = False,
+ filter_policy: FilterPolicy = FilterPolicy.REPLACE,
):
"""
Create the InMemoryEmbeddingRetriever component.
@@ -64,7 +66,7 @@ def __init__(
Scales the BM25 score to a unit interval in the range of 0 to 1, where 1 means extremely relevant. If set to `False`, uses raw similarity scores.
:param return_embedding:
Whether to return the embedding of the retrieved Documents.
-
+ :param filter_policy: The filter policy to apply during retrieval.
:raises ValueError:
If the specified top_k is not > 0.
"""
@@ -80,6 +82,7 @@ def __init__(
self.top_k = top_k
self.scale_score = scale_score
self.return_embedding = return_embedding
+ self.filter_policy = filter_policy
def _get_telemetry_data(self) -> Dict[str, Any]:
"""
@@ -102,6 +105,7 @@ def to_dict(self) -> Dict[str, Any]:
top_k=self.top_k,
scale_score=self.scale_score,
return_embedding=self.return_embedding,
+ filter_policy=self.filter_policy.value,
)
@classmethod
@@ -119,6 +123,8 @@ def from_dict(cls, data: Dict[str, Any]) -> "InMemoryEmbeddingRetriever":
raise DeserializationError("Missing 'document_store' in serialization data")
if "type" not in init_params["document_store"]:
raise DeserializationError("Missing 'type' in document store's serialization data")
+ if "filter_policy" in init_params:
+ init_params["filter_policy"] = FilterPolicy.from_str(init_params["filter_policy"])
data["init_parameters"]["document_store"] = InMemoryDocumentStore.from_dict(
data["init_parameters"]["document_store"]
)
@@ -153,8 +159,10 @@ def run(
:raises ValueError:
If the specified DocumentStore is not found or is not an InMemoryDocumentStore instance.
"""
- if filters is None:
- filters = self.filters
+ if self.filter_policy == FilterPolicy.MERGE and filters:
+ filters = {**(self.filters or {}), **filters}
+ else:
+ filters = filters or self.filters
if top_k is None:
top_k = self.top_k
if scale_score is None:
diff --git a/haystack/document_stores/types/__init__.py b/haystack/document_stores/types/__init__.py
index 635f430d4c..df2032f79c 100644
--- a/haystack/document_stores/types/__init__.py
+++ b/haystack/document_stores/types/__init__.py
@@ -2,7 +2,8 @@
#
# SPDX-License-Identifier: Apache-2.0
+from .filter_policy import FilterPolicy
from .policy import DuplicatePolicy
from .protocol import DocumentStore
-__all__ = ["DocumentStore", "DuplicatePolicy"]
+__all__ = ["DocumentStore", "DuplicatePolicy", "FilterPolicy"]
diff --git a/haystack/document_stores/types/filter_policy.py b/haystack/document_stores/types/filter_policy.py
new file mode 100644
index 0000000000..b30b9d3352
--- /dev/null
+++ b/haystack/document_stores/types/filter_policy.py
@@ -0,0 +1,35 @@
+# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
+#
+# SPDX-License-Identifier: Apache-2.0
+
+from enum import Enum
+
+
+class FilterPolicy(Enum):
+ """
+ Policy to determine how filters are applied in retrievers interacting with document stores.
+ """
+
+ # Runtime filters replace init filters during retriever run invocation.
+ REPLACE = "replace"
+
+ # Runtime filters are merged with init filters, with runtime filters overwriting init values.
+ MERGE = "merge"
+
+ def __str__(self):
+ return self.value
+
+ @staticmethod
+ def from_str(filter_policy: str) -> "FilterPolicy":
+ """
+ Convert a string to a FilterPolicy enum.
+
+ :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)
+ if policy is None:
+ msg = f"Unknown FilterPolicy type '{filter_policy}'. Supported types are: {list(enum_map.keys())}"
+ raise ValueError(msg)
+ return policy
diff --git a/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml b/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml
index 540c959446..7eb656a571 100644
--- a/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml
+++ b/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml
@@ -1,4 +1,4 @@
---
enhancements:
- |
- Provides users the ability to customize text extraction from PDF files. It is particularly useful for PDFs with unusual layouts, such as those containing multiple text columns. For instance, users can configure the object to retain the reading order.
\ No newline at end of file
+ Provides users the ability to customize text extraction from PDF files. It is particularly useful for PDFs with unusual layouts, such as those containing multiple text columns. For instance, users can configure the object to retain the reading order.
diff --git a/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml b/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml
new file mode 100644
index 0000000000..5f9b023339
--- /dev/null
+++ b/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml
@@ -0,0 +1,4 @@
+---
+enhancements:
+ - |
+ Introduced a 'filter_policy' init parameter for both InMemoryBM25Retriever and InMemoryEmbeddingRetriever, allowing users to define how runtime filters should be applied with options to either 'replace' the initial filters or 'merge' them, providing greater flexibility in filtering query results.
| diff --git a/test/components/retrievers/test_in_memory_bm25_retriever.py b/test/components/retrievers/test_in_memory_bm25_retriever.py
index 59a88a8e88..ed1ba1887c 100644
--- a/test/components/retrievers/test_in_memory_bm25_retriever.py
+++ b/test/components/retrievers/test_in_memory_bm25_retriever.py
@@ -6,6 +6,7 @@
import pytest
from haystack import Pipeline, DeserializationError
+from haystack.document_stores.types import FilterPolicy
from haystack.testing.factory import document_store_class
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.dataclasses import Document
@@ -56,6 +57,7 @@ def test_to_dict(self):
"filters": None,
"top_k": 10,
"scale_score": False,
+ "filter_policy": "replace",
},
}
@@ -77,6 +79,7 @@ def test_to_dict_with_custom_init_parameters(self):
"filters": {"name": "test.txt"},
"top_k": 5,
"scale_score": True,
+ "filter_policy": "replace",
},
}
@@ -99,6 +102,7 @@ def test_from_dict(self):
assert component.filters == {"name": "test.txt"}
assert component.top_k == 5
assert component.scale_score is False
+ assert component.filter_policy == FilterPolicy.REPLACE
def test_from_dict_without_docstore(self):
data = {"type": "InMemoryBM25Retriever", "init_parameters": {}}
diff --git a/test/components/retrievers/test_in_memory_embedding_retriever.py b/test/components/retrievers/test_in_memory_embedding_retriever.py
index a55f6ba5ef..7fe8387d68 100644
--- a/test/components/retrievers/test_in_memory_embedding_retriever.py
+++ b/test/components/retrievers/test_in_memory_embedding_retriever.py
@@ -7,6 +7,7 @@
import numpy as np
from haystack import Pipeline, DeserializationError
+from haystack.document_stores.types import FilterPolicy
from haystack.testing.factory import document_store_class
from haystack.components.retrievers.in_memory.embedding_retriever import InMemoryEmbeddingRetriever
from haystack.dataclasses import Document
@@ -47,6 +48,7 @@ def test_to_dict(self):
"top_k": 10,
"scale_score": False,
"return_embedding": False,
+ "filter_policy": "replace",
},
}
@@ -70,6 +72,7 @@ def test_to_dict_with_custom_init_parameters(self):
"top_k": 5,
"scale_score": True,
"return_embedding": True,
+ "filter_policy": "replace",
},
}
@@ -83,6 +86,7 @@ def test_from_dict(self):
},
"filters": {"name": "test.txt"},
"top_k": 5,
+ "filter_policy": "merge",
},
}
component = InMemoryEmbeddingRetriever.from_dict(data)
@@ -90,6 +94,7 @@ def test_from_dict(self):
assert component.filters == {"name": "test.txt"}
assert component.top_k == 5
assert component.scale_score is False
+ assert component.filter_policy == FilterPolicy.MERGE
def test_from_dict_without_docstore(self):
data = {
| diff --git a/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml b/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml
index 540c959446..7eb656a571 100644
--- a/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml
+++ b/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml
@@ -1,4 +1,4 @@
---
enhancements:
- |
- Provides users the ability to customize text extraction from PDF files. It is particularly useful for PDFs with unusual layouts, such as those containing multiple text columns. For instance, users can configure the object to retain the reading order.
\ No newline at end of file
+ Provides users the ability to customize text extraction from PDF files. It is particularly useful for PDFs with unusual layouts, such as those containing multiple text columns. For instance, users can configure the object to retain the reading order.
diff --git a/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml b/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml
new file mode 100644
index 0000000000..5f9b023339
--- /dev/null
+++ b/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml
@@ -0,0 +1,4 @@
+---
+enhancements:
+ - |
+ Introduced a 'filter_policy' init parameter for both InMemoryBM25Retriever and InMemoryEmbeddingRetriever, allowing users to define how runtime filters should be applied with options to either 'replace' the initial filters or 'merge' them, providing greater flexibility in filtering query results.
| [
{
"components": [
{
"doc": "Policy to determine how filters are applied in retrievers interacting with document stores.",
"lines": [
8,
35
],
"name": "FilterPolicy",
"signature": "class FilterPolicy(Enum):",
"type": "class"
},
... | [
"test/components/retrievers/test_in_memory_bm25_retriever.py::TestMemoryBM25Retriever::test_init_default",
"test/components/retrievers/test_in_memory_bm25_retriever.py::TestMemoryBM25Retriever::test_init_with_parameters",
"test/components/retrievers/test_in_memory_bm25_retriever.py::TestMemoryBM25Retriever::tes... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Add filter_policy init parameter to in memory retrievers
A companion PR for https://github.com/deepset-ai/haystack-core-integrations/pull/781 adding `filter_policy` parameter with options replace and merge for in memory retrievers.
*Do not merge* before we understand how to proceed with https://github.com/deepset-ai/haystack-core-integrations/pull/781 and this PR in sync.
----------
</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 FilterPolicy:)
class FilterPolicy(Enum):
"""Policy to determine how filters are applied in retrievers interacting with document stores."""
(definition of FilterPolicy.__str__:)
def __str__(self):
(definition of FilterPolicy.from_str:)
def from_str(filter_policy: str) -> "FilterPolicy":
"""Convert a string to a FilterPolicy enum.
:param filter_policy: The string to convert.
:return: The corresponding FilterPolicy enum."""
[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 | |
astronomer__astronomer-cosmos-1016 | 1,016 | astronomer/astronomer-cosmos | null | 0e4ca97ec7860fb843d227134692899df72a4272 | 2024-06-03T16:24:18Z | diff --git a/cosmos/profiles/__init__.py b/cosmos/profiles/__init__.py
index fa8e5c370..5cc3109cc 100644
--- a/cosmos/profiles/__init__.py
+++ b/cosmos/profiles/__init__.py
@@ -9,6 +9,7 @@
from .bigquery.oauth import GoogleCloudOauthProfileMapping
from .bigquery.service_account_file import GoogleCloudServiceAccountFileProfileMapping
from .bigquery.service_account_keyfile_dict import GoogleCloudServiceAccountDictProfileMapping
+from .clickhouse.user_pass import ClickhouseUserPasswordProfileMapping
from .databricks.token import DatabricksTokenProfileMapping
from .exasol.user_pass import ExasolUserPasswordProfileMapping
from .postgres.user_pass import PostgresUserPasswordProfileMapping
@@ -25,6 +26,7 @@
profile_mappings: list[Type[BaseProfileMapping]] = [
AthenaAccessKeyProfileMapping,
+ ClickhouseUserPasswordProfileMapping,
GoogleCloudServiceAccountFileProfileMapping,
GoogleCloudServiceAccountDictProfileMapping,
GoogleCloudOauthProfileMapping,
diff --git a/cosmos/profiles/clickhouse/__init__.py b/cosmos/profiles/clickhouse/__init__.py
new file mode 100644
index 000000000..bd94af5fe
--- /dev/null
+++ b/cosmos/profiles/clickhouse/__init__.py
@@ -0,0 +1,5 @@
+"""Generic Airflow connection -> dbt profile mappings"""
+
+from .user_pass import ClickhouseUserPasswordProfileMapping
+
+__all__ = ["ClickhouseUserPasswordProfileMapping"]
diff --git a/cosmos/profiles/clickhouse/user_pass.py b/cosmos/profiles/clickhouse/user_pass.py
new file mode 100644
index 000000000..7d168895a
--- /dev/null
+++ b/cosmos/profiles/clickhouse/user_pass.py
@@ -0,0 +1,70 @@
+"""Maps Airflow Postgres connections using user + password authentication to dbt profiles."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from ..base import BaseProfileMapping
+
+
+class ClickhouseUserPasswordProfileMapping(BaseProfileMapping):
+ """
+ Maps Airflow generic connections using user + password authentication to dbt Clickhouse profiles.
+ https://docs.getdbt.com/docs/core/connect-data-platform/clickhouse-setup
+ """
+
+ airflow_connection_type: str = "generic"
+ dbt_profile_type: str = "clickhouse"
+ default_port = 9000
+ is_community = True
+
+ required_fields = [
+ "host",
+ "login",
+ "schema",
+ "clickhouse",
+ ]
+ secret_fields = [
+ "password",
+ ]
+ airflow_param_mapping = {
+ "host": "host",
+ "login": "login",
+ "password": "password",
+ "port": "port",
+ "schema": "schema",
+ "clickhouse": "extra.clickhouse",
+ }
+
+ def _set_default_param(self, profile_dict: dict[str, Any]) -> dict[str, Any]:
+ if not profile_dict.get("driver"):
+ profile_dict["driver"] = "native"
+
+ if not profile_dict.get("port"):
+ profile_dict["port"] = self.default_port
+
+ if not profile_dict.get("secure"):
+ profile_dict["secure"] = False
+ return profile_dict
+
+ @property
+ def profile(self) -> dict[str, Any | None]:
+ """Gets profile. The password is stored in an environment variable."""
+ profile_dict = {
+ **self.mapped_params,
+ **self.profile_args,
+ # password should always get set as env var
+ "password": self.get_env_var_format("password"),
+ }
+
+ return self.filter_null(self._set_default_param(profile_dict))
+
+ @property
+ def mock_profile(self) -> dict[str, Any | None]:
+ """Gets mock profile."""
+
+ profile_dict = {
+ **super().mock_profile,
+ }
+
+ return self._set_default_param(profile_dict)
diff --git a/pyproject.toml b/pyproject.toml
index 238b877e4..ea97a9c0c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -43,6 +43,7 @@ dependencies = [
dbt-all = [
"dbt-athena",
"dbt-bigquery",
+ "dbt-clickhouse",
"dbt-databricks",
"dbt-exasol",
"dbt-postgres",
@@ -53,6 +54,7 @@ dbt-all = [
]
dbt-athena = ["dbt-athena-community", "apache-airflow-providers-amazon>=8.0.0"]
dbt-bigquery = ["dbt-bigquery"]
+dbt-clickhouse = ["dbt-clickhouse"]
dbt-databricks = ["dbt-databricks"]
dbt-exasol = ["dbt-exasol"]
dbt-postgres = ["dbt-postgres"]
| diff --git a/tests/profiles/clickhouse/__init__.py b/tests/profiles/clickhouse/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/profiles/clickhouse/test_clickhouse_userpass.py b/tests/profiles/clickhouse/test_clickhouse_userpass.py
new file mode 100644
index 000000000..1f623c803
--- /dev/null
+++ b/tests/profiles/clickhouse/test_clickhouse_userpass.py
@@ -0,0 +1,117 @@
+"""Tests for the clickhouse profile."""
+
+from unittest.mock import patch
+
+import pytest
+from airflow.models.connection import Connection
+
+from cosmos.profiles import get_automatic_profile_mapping
+from cosmos.profiles.clickhouse.user_pass import (
+ ClickhouseUserPasswordProfileMapping,
+)
+
+
+@pytest.fixture()
+def mock_clickhouse_conn(): # type: ignore
+ """Sets the connection as an environment variable."""
+ conn = Connection(
+ conn_id="clickhouse_connection",
+ conn_type="generic",
+ host="my_host",
+ login="my_user",
+ password="my_password",
+ schema="my_database",
+ extra='{"clickhouse": "True"}',
+ )
+
+ with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn):
+ yield conn
+
+
+def test_connection_claiming1() -> None:
+ """
+ Tests that the clickhouse profile mapping claims the correct connection type.
+
+ should only claim when:
+ - conn_type == generic
+ And the following exist:
+ - host
+ - login
+ - password
+ - schema
+ - extra.clickhouse
+ """
+ required_values = {
+ "conn_type": "generic",
+ "host": "my_host",
+ "login": "my_user",
+ "schema": "my_database",
+ "extra": '{"clickhouse": "True"}',
+ }
+
+ def can_claim_with_missing_key(missing_key: str) -> bool:
+ values = required_values.copy()
+ del values[missing_key]
+ conn = Connection(**values) # type: ignore
+ with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn):
+ profile_mapping = ClickhouseUserPasswordProfileMapping(conn, {})
+ return profile_mapping.can_claim_connection()
+
+ # if we're missing any of the required values, it shouldn't claim
+ for key in required_values:
+ assert not can_claim_with_missing_key(key), f"Failed when missing {key}"
+
+ # if we have all the required values, it should claim
+ conn = Connection(**required_values) # type: ignore
+ with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn):
+ profile_mapping = ClickhouseUserPasswordProfileMapping(conn, {})
+ assert profile_mapping.can_claim_connection()
+
+
+def test_profile_mapping_selected(
+ mock_clickhouse_conn: Connection,
+) -> None:
+ """Tests that the correct profile mapping is selected."""
+ profile_mapping = get_automatic_profile_mapping(mock_clickhouse_conn.conn_id, {})
+ assert isinstance(profile_mapping, ClickhouseUserPasswordProfileMapping)
+
+
+def test_profile_args(mock_clickhouse_conn: Connection) -> None:
+ """Tests that the profile values get set correctly."""
+ profile_mapping = get_automatic_profile_mapping(mock_clickhouse_conn.conn_id, profile_args={})
+
+ assert profile_mapping.profile == {
+ "type": "clickhouse",
+ "schema": mock_clickhouse_conn.schema,
+ "login": mock_clickhouse_conn.login,
+ "password": "{{ env_var('COSMOS_CONN_GENERIC_PASSWORD') }}",
+ "driver": "native",
+ "port": 9000,
+ "host": mock_clickhouse_conn.host,
+ "secure": False,
+ "clickhouse": "True",
+ }
+
+
+def test_mock_profile() -> None:
+ """Tests that the mock_profile values get set correctly."""
+ profile_mapping = ClickhouseUserPasswordProfileMapping(
+ "conn_id"
+ ) # get_automatic_profile_mapping("mock_clickhouse_conn.conn_id", profile_args={})
+
+ assert profile_mapping.mock_profile == {
+ "type": "clickhouse",
+ "schema": "mock_value",
+ "login": "mock_value",
+ "driver": "native",
+ "port": 9000,
+ "host": "mock_value",
+ "secure": False,
+ "clickhouse": "mock_value",
+ }
+
+
+def test_profile_env_vars(mock_clickhouse_conn: Connection) -> None:
+ """Tests that the environment variables get set correctly."""
+ profile_mapping = get_automatic_profile_mapping(mock_clickhouse_conn.conn_id, profile_args={})
+ assert profile_mapping.env_vars == {"COSMOS_CONN_GENERIC_PASSWORD": mock_clickhouse_conn.password}
| diff --git a/pyproject.toml b/pyproject.toml
index 238b877e4..ea97a9c0c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -43,6 +43,7 @@ dependencies = [
dbt-all = [
"dbt-athena",
"dbt-bigquery",
+ "dbt-clickhouse",
"dbt-databricks",
"dbt-exasol",
"dbt-postgres",
@@ -53,6 +54,7 @@ dbt-all = [
]
dbt-athena = ["dbt-athena-community", "apache-airflow-providers-amazon>=8.0.0"]
dbt-bigquery = ["dbt-bigquery"]
+dbt-clickhouse = ["dbt-clickhouse"]
dbt-databricks = ["dbt-databricks"]
dbt-exasol = ["dbt-exasol"]
dbt-postgres = ["dbt-postgres"]
| [
{
"components": [
{
"doc": "Maps Airflow generic connections using user + password authentication to dbt Clickhouse profiles.\nhttps://docs.getdbt.com/docs/core/connect-data-platform/clickhouse-setup",
"lines": [
10,
70
],
"name": "ClickhouseUserPassword... | [
"tests/profiles/clickhouse/test_clickhouse_userpass.py::test_connection_claiming1",
"tests/profiles/clickhouse/test_clickhouse_userpass.py::test_profile_mapping_selected",
"tests/profiles/clickhouse/test_clickhouse_userpass.py::test_profile_args",
"tests/profiles/clickhouse/test_clickhouse_userpass.py::test_m... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add Clickhouse profile mapping
## Description
This PR adds Clickhouse profile mapping using a `generic` connection type. To prevent cosmos from attaching all generic connections, it uses a required field named `clickhouse` mapped to `extra.clickhouse`.
To ensure the profile is claimed, users must add the following JSON to the extra field in the connection:
```JSON
{
"clickhouse": "True"
}
```
Co-authored-by: Yaniv Rodenski <roadan@gmail.com>
Original PR by @roadan: https://github.com/astronomer/astronomer-cosmos/pull/353
## Related Issue(s)
closes #95
## Breaking Change?
## Checklist
[ x] 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/clickhouse/user_pass.py]
(definition of ClickhouseUserPasswordProfileMapping:)
class ClickhouseUserPasswordProfileMapping(BaseProfileMapping):
"""Maps Airflow generic connections using user + password authentication to dbt Clickhouse profiles.
https://docs.getdbt.com/docs/core/connect-data-platform/clickhouse-setup"""
(definition of ClickhouseUserPasswordProfileMapping._set_default_param:)
def _set_default_param(self, profile_dict: dict[str, Any]) -> dict[str, Any]:
(definition of ClickhouseUserPasswordProfileMapping.profile:)
def profile(self) -> dict[str, Any | None]:
"""Gets profile. The password is stored in an environment variable."""
(definition of ClickhouseUserPasswordProfileMapping.mock_profile:)
def mock_profile(self) -> dict[str, Any | None]:
"""Gets mock profile."""
[end of new definitions in cosmos/profiles/clickhouse/user_pass.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 support for dbt-clickhouse adapter
Requested via LinkedIn comment.
- See dbt docs [here](https://docs.getdbt.com/reference/warehouse-setups/clickhouse-setup)
- See clickhouse home page [here](https://clickhouse.com/)
----------
Hi, is anyone solving this problem?
This is a very desirable feature actually
We'd love to have support to it
Hi @pohek321 could u help me ? Wich parts of the project i need to look/change to solve this issue ?
I know providers and profiles are the main ones to look at
I am willing to submit a PR!
> Hi @pohek321 could u help me ? Wich parts of the project i need to look/change to solve this issue ?
>
> I know providers and profiles are the main ones to look at
>
>
>
>
>
> I am willing to submit a PR!
Hey @vargacypher - I have a PR open that should simplify the process of adding new profiles quite a bit. I'd recommend waiting until it's merged to contribute a new profile! In the meantime, give the PR a look and let me know what you think of the profile/connection definitions.
https://github.com/astronomer/astronomer-cosmos/pull/271
@jlaneve I actually have an initial working version of this using your refactored code which I'd love to PR, however, as far as I can see there is no clickhouse connection so my local version is using the generic connection which I think is not a great solution. Any thoughts on how it's best to progress with this?
@roadan do you mind creating a PR so I may be able to check it out? This is also a PR that interests me quite a lot. And about the connection type, there is no clickhouse connection for airflow, therefore using a generic connection type is how clickhouse users have been doing so far, which makes your approach totally correct ✅
@CorsettiS will do, I just want to add some tests before I do that. The PR should be ready tomorrow.
My concern with the current PR is that the required fields are few so essentially my connector will be able to claim most generic connections. Maybe I can add an extra just for `can_claim_connection` to match on?
@roadan sounds feasible IMO
Hi, @chrishronek. I'm Dosu, and I'm helping the Cosmos team manage their backlog. I wanted to let you know that we are marking this issue as stale.
From what I understand, this issue is a request to add support for the dbt-clickhouse adapter. There has been some discussion in the comments, with roadan mentioning that they have an initial working version using refactored code. CorsettiS has requested roadan to create a pull request (PR) so they can review it. Roadan has mentioned that they will add tests before creating the PR. Additionally, there is a suggestion from CorsettiS to add an extra field for `can_claim_connection` to address a concern about the current PR claiming most generic connections.
Before we close this issue, we wanted to check with you if it is still relevant to the latest version of the Cosmos repository. If it is, please let the Cosmos team know by commenting on the issue. Otherwise, feel free to close the issue yourself or it will be automatically closed in 7 days.
Thank you for your understanding and contributions to the Cosmos repository. Let us know if you have any further questions or concerns.
--------------------
</issues> | c5edba07d2265d5185eaba149a639e8a0740e498 |
tobymao__sqlglot-3577 | 3,577 | tobymao/sqlglot | null | 13009ca5c14d81b7a07311a38f329b967f909926 | 2024-05-31T21:23:44Z | diff --git a/sqlglot/dialects/__init__.py b/sqlglot/dialects/__init__.py
index 29c6580012..0c5e6110da 100644
--- a/sqlglot/dialects/__init__.py
+++ b/sqlglot/dialects/__init__.py
@@ -70,6 +70,7 @@ class Generator(Generator):
from sqlglot.dialects.drill import Drill
from sqlglot.dialects.duckdb import DuckDB
from sqlglot.dialects.hive import Hive
+from sqlglot.dialects.materialize import Materialize
from sqlglot.dialects.mysql import MySQL
from sqlglot.dialects.oracle import Oracle
from sqlglot.dialects.postgres import Postgres
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index 0421e4e8da..c5b6dbbd01 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -50,6 +50,7 @@ class Dialects(str, Enum):
DRILL = "drill"
DUCKDB = "duckdb"
HIVE = "hive"
+ MATERIALIZE = "materialize"
MYSQL = "mysql"
ORACLE = "oracle"
POSTGRES = "postgres"
diff --git a/sqlglot/dialects/materialize.py b/sqlglot/dialects/materialize.py
new file mode 100644
index 0000000000..ea6ef627c4
--- /dev/null
+++ b/sqlglot/dialects/materialize.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+from sqlglot import exp
+from sqlglot.helper import seq_get
+from sqlglot.dialects.postgres import Postgres
+
+from sqlglot.tokens import TokenType
+from sqlglot.transforms import (
+ remove_unique_constraints,
+ ctas_with_tmp_tables_to_create_tmp_view,
+ preprocess,
+)
+import typing as t
+
+
+class Materialize(Postgres):
+ class Parser(Postgres.Parser):
+ NO_PAREN_FUNCTION_PARSERS = {
+ **Postgres.Parser.NO_PAREN_FUNCTION_PARSERS,
+ "MAP": lambda self: self._parse_map(),
+ }
+
+ def _parse_map(self) -> exp.ToMap:
+ if self._match(TokenType.L_PAREN):
+ to_map = self.expression(exp.ToMap, this=self._parse_select())
+ self._match_r_paren()
+ return to_map
+
+ if not self._match(TokenType.L_BRACKET):
+ self.raise_error("Expecting [")
+ entries = self._parse_csv(self._parse_map_entry)
+ if not self._match(TokenType.R_BRACKET):
+ self.raise_error("Expecting ]")
+ return self.expression(exp.ToMap, this=self.expression(exp.Struct, expressions=entries))
+
+ def _parse_map_entry(self) -> t.Optional[exp.PropertyEQ]:
+ key = self._parse_conjunction()
+ if not key:
+ return None
+ if not self._match(TokenType.FARROW):
+ self.raise_error("Expected =>")
+ value = self._parse_conjunction()
+ return self.expression(exp.PropertyEQ, this=key, expression=value)
+
+ class Generator(Postgres.Generator):
+ SUPPORTS_CREATE_TABLE_LIKE = False
+
+ TRANSFORMS = {
+ **Postgres.Generator.TRANSFORMS,
+ exp.AutoIncrementColumnConstraint: lambda self, e: "",
+ exp.Create: preprocess(
+ [
+ remove_unique_constraints,
+ ctas_with_tmp_tables_to_create_tmp_view,
+ ]
+ ),
+ exp.GeneratedAsIdentityColumnConstraint: lambda self, e: "",
+ exp.OnConflict: lambda self, e: "",
+ exp.PrimaryKeyColumnConstraint: lambda self, e: "",
+ exp.List: lambda self, e: self._list_sql(e),
+ exp.ToMap: lambda self, e: self._to_map_sql(e),
+ }
+
+ def datatype_sql(self, expression: exp.DataType) -> str:
+ if expression.is_type(exp.DataType.Type.LIST):
+ if expression.expressions:
+ return f"{self.expressions(expression, flat=True)} LIST"
+ return "LIST"
+ if expression.is_type(exp.DataType.Type.MAP) and len(expression.expressions) == 2:
+ key, value = expression.expressions
+ return f"MAP[{self.sql(key)} => {self.sql(value)}]"
+ return super().datatype_sql(expression)
+
+ def _list_sql(self, expression: exp.List) -> str:
+ if isinstance(seq_get(expression.expressions, 0), exp.Select):
+ return self.func("LIST", seq_get(expression.expressions, 0))
+
+ return f"{self.normalize_func('LIST')}[{self.expressions(expression, flat=True)}]"
+
+ def _to_map_sql(self, expression: exp.ToMap) -> str:
+ if isinstance(expression.this, exp.Select):
+ return self.func("MAP", expression.this)
+
+ entries = ", ".join(
+ f"{self.sql(e.this)} => {self.sql(e.expression)}"
+ for e in expression.this.expressions
+ )
+ return f"{self.normalize_func('MAP')}[{entries}]"
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py
index 249a04ca54..04c1d9ca4d 100644
--- a/sqlglot/dialects/postgres.py
+++ b/sqlglot/dialects/postgres.py
@@ -623,3 +623,11 @@ def alterset_sql(self, expression: exp.AlterSet) -> str:
option = self.sql(expression, "option")
return f"SET {exprs}{access_method}{tablespace}{option}"
+
+ def datatype_sql(self, expression: exp.DataType) -> str:
+ if expression.is_type("array"):
+ if expression.expressions:
+ values = self.expressions(expression, key="values", flat=True)
+ return f"{self.expressions(expression, flat=True)}[{values}]"
+ return "ARRAY"
+ return super().datatype_sql(expression)
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index f9bc6eea08..fd0535447b 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -3977,6 +3977,7 @@ class Type(AutoName):
IPV6 = auto()
JSON = auto()
JSONB = auto()
+ LIST = auto()
LONGBLOB = auto()
LONGTEXT = auto()
LOWCARDINALITY = auto()
@@ -4768,6 +4769,12 @@ class ToArray(Func):
pass
+# https://materialize.com/docs/sql/types/list/
+class List(Func):
+ arg_types = {"expressions": False}
+ is_var_len_args = True
+
+
# https://docs.snowflake.com/en/sql-reference/functions/to_char
# https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/TO_CHAR-number.html
class ToChar(Func):
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index c2cb3a14f1..9ed7e0b55c 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -193,6 +193,7 @@ class Parser(metaclass=_Parser):
NESTED_TYPE_TOKENS = {
TokenType.ARRAY,
+ TokenType.LIST,
TokenType.LOWCARDINALITY,
TokenType.MAP,
TokenType.NULLABLE,
@@ -456,6 +457,11 @@ class Parser(metaclass=_Parser):
ALIAS_TOKENS = ID_VAR_TOKENS
+ ARRAY_CONSTRUCTORS = {
+ "ARRAY": exp.Array,
+ "LIST": exp.List,
+ }
+
COMMENT_TABLE_ALIAS_TOKENS = TABLE_ALIAS_TOKENS - {TokenType.IS}
UPDATE_ALIAS_TOKENS = TABLE_ALIAS_TOKENS - {TokenType.SET}
@@ -4291,6 +4297,27 @@ def _parse_types(
if type_token == TokenType.OBJECT_IDENTIFIER:
return self.expression(exp.ObjectIdentifier, this=self._prev.text.upper())
+ # https://materialize.com/docs/sql/types/map/
+ if type_token == TokenType.MAP and self._match(TokenType.L_BRACKET):
+ key_type = self._parse_types(
+ check_func=check_func, schema=schema, allow_identifiers=allow_identifiers
+ )
+ if not self._match(TokenType.FARROW):
+ self._retreat(index)
+ return None
+ value_type = self._parse_types(
+ check_func=check_func, schema=schema, allow_identifiers=allow_identifiers
+ )
+ if not self._match(TokenType.R_BRACKET):
+ self._retreat(index)
+ return None
+ return exp.DataType(
+ this=exp.DataType.Type.MAP,
+ expressions=[key_type, value_type],
+ nested=True,
+ prefix=prefix,
+ )
+
nested = type_token in self.NESTED_TYPE_TOKENS
is_struct = type_token in self.STRUCT_TYPE_TOKENS
is_aggregate = type_token in self.AGGREGATE_TYPE_TOKENS
@@ -4400,6 +4427,10 @@ def _parse_types(
elif expressions:
this.set("expressions", expressions)
+ # https://materialize.com/docs/sql/types/list/#type-name
+ while self._match(TokenType.LIST):
+ this = exp.DataType(this=exp.DataType.Type.LIST, expressions=[this], nested=True)
+
index = self._index
# Postgres supports the INT ARRAY[3] syntax as a synonym for INT[3]
@@ -5172,9 +5203,13 @@ def _parse_bracket(self, this: t.Optional[exp.Expression] = None) -> t.Optional[
# https://duckdb.org/docs/sql/data_types/struct.html#creating-structs
if bracket_kind == TokenType.L_BRACE:
this = self.expression(exp.Struct, expressions=self._kv_to_prop_eq(expressions))
- elif not this or this.name.upper() == "ARRAY":
+ elif not this:
this = self.expression(exp.Array, expressions=expressions)
else:
+ constructor_type = self.ARRAY_CONSTRUCTORS.get(this.name.upper())
+ if constructor_type:
+ return self.expression(constructor_type, expressions=expressions)
+
expressions = apply_index_offset(this, expressions, -self.dialect.INDEX_OFFSET)
this = self.expression(exp.Bracket, this=this, expressions=expressions)
diff --git a/sqlglot/tokens.py b/sqlglot/tokens.py
index 6586667f81..5b2f2415bb 100644
--- a/sqlglot/tokens.py
+++ b/sqlglot/tokens.py
@@ -294,6 +294,7 @@ class TokenType(AutoName):
LIKE = auto()
LIKE_ANY = auto()
LIMIT = auto()
+ LIST = auto()
LOAD = auto()
LOCK = auto()
MAP = auto()
@@ -813,6 +814,7 @@ class Tokenizer(metaclass=_Tokenizer):
"DECIMAL": TokenType.DECIMAL,
"BIGDECIMAL": TokenType.BIGDECIMAL,
"BIGNUMERIC": TokenType.BIGDECIMAL,
+ "LIST": TokenType.LIST,
"MAP": TokenType.MAP,
"NULLABLE": TokenType.NULLABLE,
"NUMBER": TokenType.DECIMAL,
| diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py
index 9888a5d66a..55753e5139 100644
--- a/tests/dialects/test_dialect.py
+++ b/tests/dialects/test_dialect.py
@@ -155,6 +155,7 @@ def test_cast(self):
"clickhouse": "CAST(a AS String)",
"drill": "CAST(a AS VARCHAR)",
"duckdb": "CAST(a AS TEXT)",
+ "materialize": "CAST(a AS TEXT)",
"mysql": "CAST(a AS CHAR)",
"hive": "CAST(a AS STRING)",
"oracle": "CAST(a AS CLOB)",
@@ -175,6 +176,7 @@ def test_cast(self):
"clickhouse": "CAST(a AS BINARY(4))",
"drill": "CAST(a AS VARBINARY(4))",
"duckdb": "CAST(a AS BLOB(4))",
+ "materialize": "CAST(a AS BYTEA(4))",
"mysql": "CAST(a AS BINARY(4))",
"hive": "CAST(a AS BINARY(4))",
"oracle": "CAST(a AS BLOB(4))",
@@ -193,6 +195,7 @@ def test_cast(self):
"bigquery": "CAST(a AS BYTES)",
"clickhouse": "CAST(a AS String)",
"duckdb": "CAST(a AS BLOB(4))",
+ "materialize": "CAST(a AS BYTEA(4))",
"mysql": "CAST(a AS VARBINARY(4))",
"hive": "CAST(a AS BINARY(4))",
"oracle": "CAST(a AS BLOB(4))",
@@ -236,6 +239,7 @@ def test_cast(self):
"bigquery": "CAST(a AS STRING)",
"drill": "CAST(a AS VARCHAR)",
"duckdb": "CAST(a AS TEXT)",
+ "materialize": "CAST(a AS TEXT)",
"mysql": "CAST(a AS CHAR)",
"hive": "CAST(a AS STRING)",
"oracle": "CAST(a AS CLOB)",
@@ -255,6 +259,7 @@ def test_cast(self):
"bigquery": "CAST(a AS STRING)",
"drill": "CAST(a AS VARCHAR)",
"duckdb": "CAST(a AS TEXT)",
+ "materialize": "CAST(a AS VARCHAR)",
"mysql": "CAST(a AS CHAR)",
"hive": "CAST(a AS STRING)",
"oracle": "CAST(a AS VARCHAR2)",
@@ -274,6 +279,7 @@ def test_cast(self):
"bigquery": "CAST(a AS STRING)",
"drill": "CAST(a AS VARCHAR(3))",
"duckdb": "CAST(a AS TEXT(3))",
+ "materialize": "CAST(a AS VARCHAR(3))",
"mysql": "CAST(a AS CHAR(3))",
"hive": "CAST(a AS VARCHAR(3))",
"oracle": "CAST(a AS VARCHAR2(3))",
@@ -293,6 +299,7 @@ def test_cast(self):
"bigquery": "CAST(a AS INT64)",
"drill": "CAST(a AS INTEGER)",
"duckdb": "CAST(a AS SMALLINT)",
+ "materialize": "CAST(a AS SMALLINT)",
"mysql": "CAST(a AS SIGNED)",
"hive": "CAST(a AS SMALLINT)",
"oracle": "CAST(a AS NUMBER)",
@@ -328,6 +335,7 @@ def test_cast(self):
"clickhouse": "CAST(a AS Float64)",
"drill": "CAST(a AS DOUBLE)",
"duckdb": "CAST(a AS DOUBLE)",
+ "materialize": "CAST(a AS DOUBLE PRECISION)",
"mysql": "CAST(a AS DOUBLE)",
"hive": "CAST(a AS DOUBLE)",
"oracle": "CAST(a AS DOUBLE PRECISION)",
@@ -599,6 +607,7 @@ def test_time(self):
"drill": "TO_TIMESTAMP(x, 'yy')",
"duckdb": "STRPTIME(x, '%y')",
"hive": "CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(x, 'yy')) AS TIMESTAMP)",
+ "materialize": "TO_TIMESTAMP(x, 'YY')",
"presto": "DATE_PARSE(x, '%y')",
"oracle": "TO_TIMESTAMP(x, 'YY')",
"postgres": "TO_TIMESTAMP(x, 'YY')",
@@ -655,6 +664,7 @@ def test_time(self):
"drill": "TO_CHAR(x, 'yyyy-MM-dd')",
"duckdb": "STRFTIME(x, '%Y-%m-%d')",
"hive": "DATE_FORMAT(x, 'yyyy-MM-dd')",
+ "materialize": "TO_CHAR(x, 'YYYY-MM-DD')",
"oracle": "TO_CHAR(x, 'YYYY-MM-DD')",
"postgres": "TO_CHAR(x, 'YYYY-MM-DD')",
"presto": "DATE_FORMAT(x, '%Y-%m-%d')",
@@ -698,6 +708,7 @@ def test_time(self):
"bigquery": "CAST(x AS DATE)",
"duckdb": "CAST(x AS DATE)",
"hive": "TO_DATE(x)",
+ "materialize": "CAST(x AS DATE)",
"postgres": "CAST(x AS DATE)",
"presto": "CAST(CAST(x AS TIMESTAMP) AS DATE)",
"snowflake": "TO_DATE(x)",
@@ -730,6 +741,7 @@ def test_time(self):
"duckdb": "TO_TIMESTAMP(x)",
"hive": "FROM_UNIXTIME(x)",
"oracle": "TO_DATE('1970-01-01', 'YYYY-MM-DD') + (x / 86400)",
+ "materialize": "TO_TIMESTAMP(x)",
"postgres": "TO_TIMESTAMP(x)",
"presto": "FROM_UNIXTIME(x)",
"starrocks": "FROM_UNIXTIME(x)",
@@ -790,6 +802,7 @@ def test_time(self):
"drill": "DATE_ADD(x, INTERVAL 1 DAY)",
"duckdb": "x + INTERVAL 1 DAY",
"hive": "DATE_ADD(x, 1)",
+ "materialize": "x + INTERVAL '1 DAY'",
"mysql": "DATE_ADD(x, INTERVAL 1 DAY)",
"postgres": "x + INTERVAL '1 DAY'",
"presto": "DATE_ADD('DAY', 1, x)",
@@ -826,6 +839,7 @@ def test_time(self):
"duckdb": "DATE_TRUNC('DAY', x)",
"mysql": "DATE(x)",
"presto": "DATE_TRUNC('DAY', x)",
+ "materialize": "DATE_TRUNC('DAY', x)",
"postgres": "DATE_TRUNC('DAY', x)",
"snowflake": "DATE_TRUNC('DAY', x)",
"starrocks": "DATE_TRUNC('DAY', x)",
@@ -838,6 +852,7 @@ def test_time(self):
read={
"bigquery": "TIMESTAMP_TRUNC(x, day)",
"duckdb": "DATE_TRUNC('day', x)",
+ "materialize": "DATE_TRUNC('day', x)",
"presto": "DATE_TRUNC('day', x)",
"postgres": "DATE_TRUNC('day', x)",
"snowflake": "DATE_TRUNC('day', x)",
@@ -899,6 +914,7 @@ def test_time(self):
},
write={
"bigquery": "DATE_TRUNC(x, YEAR)",
+ "materialize": "DATE_TRUNC('YEAR', x)",
"mysql": "STR_TO_DATE(CONCAT(YEAR(x), ' 1 1'), '%Y %c %e')",
"postgres": "DATE_TRUNC('YEAR', x)",
"snowflake": "DATE_TRUNC('YEAR', x)",
@@ -911,6 +927,7 @@ def test_time(self):
"TIMESTAMP_TRUNC(x, YEAR)",
read={
"bigquery": "TIMESTAMP_TRUNC(x, year)",
+ "materialize": "DATE_TRUNC('YEAR', x)",
"postgres": "DATE_TRUNC(year, x)",
"spark": "DATE_TRUNC('year', x)",
"snowflake": "DATE_TRUNC(year, x)",
@@ -1024,6 +1041,7 @@ def test_time(self):
write={
"": "TIMESTAMP_TRUNC(x, DAY, 'UTC')",
"duckdb": "DATE_TRUNC('DAY', x)",
+ "materialize": "DATE_TRUNC('DAY', x, 'UTC')",
"presto": "DATE_TRUNC('DAY', x)",
"postgres": "DATE_TRUNC('DAY', x, 'UTC')",
"snowflake": "DATE_TRUNC('DAY', x)",
diff --git a/tests/dialects/test_materialize.py b/tests/dialects/test_materialize.py
new file mode 100644
index 0000000000..0747680167
--- /dev/null
+++ b/tests/dialects/test_materialize.py
@@ -0,0 +1,71 @@
+from tests.dialects.test_dialect import Validator
+
+
+class TestMaterialize(Validator):
+ dialect = "materialize"
+
+ def test_materialize(self):
+ self.validate_all(
+ "CREATE TABLE example (id INT PRIMARY KEY, name TEXT)",
+ write={
+ "materialize": "CREATE TABLE example (id INT, name TEXT)",
+ "postgres": "CREATE TABLE example (id INT PRIMARY KEY, name TEXT)",
+ },
+ )
+ self.validate_all(
+ "INSERT INTO example (id, name) VALUES (1, 'Alice') ON CONFLICT(id) DO NOTHING",
+ write={
+ "materialize": "INSERT INTO example (id, name) VALUES (1, 'Alice')",
+ "postgres": "INSERT INTO example (id, name) VALUES (1, 'Alice') ON CONFLICT(id) DO NOTHING",
+ },
+ )
+ self.validate_all(
+ "CREATE TABLE example (id SERIAL, name TEXT)",
+ write={
+ "materialize": "CREATE TABLE example (id INT NOT NULL, name TEXT)",
+ "postgres": "CREATE TABLE example (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, name TEXT)",
+ },
+ )
+ self.validate_all(
+ "CREATE TABLE example (id INT AUTO_INCREMENT, name TEXT)",
+ write={
+ "materialize": "CREATE TABLE example (id INT NOT NULL, name TEXT)",
+ "postgres": "CREATE TABLE example (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, name TEXT)",
+ },
+ )
+ self.validate_all(
+ 'SELECT JSON_EXTRACT_PATH_TEXT(\'{ "farm": {"barn": { "color": "red", "feed stocked": true }}}\', \'farm\', \'barn\', \'color\')',
+ write={
+ "materialize": 'SELECT JSON_EXTRACT_PATH_TEXT(\'{ "farm": {"barn": { "color": "red", "feed stocked": true }}}\', \'farm\', \'barn\', \'color\')',
+ "postgres": 'SELECT JSON_EXTRACT_PATH_TEXT(\'{ "farm": {"barn": { "color": "red", "feed stocked": true }}}\', \'farm\', \'barn\', \'color\')',
+ },
+ )
+
+ # Test now functions.
+ self.validate_identity("CURRENT_TIMESTAMP")
+ self.validate_identity("NOW()", write_sql="CURRENT_TIMESTAMP")
+ self.validate_identity("MZ_NOW()")
+
+ # Test custom timestamp type.
+ self.validate_identity("SELECT CAST(1 AS mz_timestamp)")
+
+ # Test DDL.
+ self.validate_identity("CREATE TABLE example (id INT, name LIST)")
+
+ # Test list types.
+ self.validate_identity("SELECT LIST[]")
+ self.validate_identity("SELECT LIST[1, 2, 3]")
+ self.validate_identity("SELECT LIST[LIST[1], LIST[2], NULL]")
+ self.validate_identity("SELECT CAST(LIST[1, 2, 3] AS INT LIST)")
+ self.validate_identity("SELECT CAST(NULL AS INT LIST)")
+ self.validate_identity("SELECT CAST(NULL AS INT LIST LIST LIST)")
+ self.validate_identity("SELECT LIST(SELECT 1)")
+
+ # Test map types.
+ self.validate_identity("SELECT MAP[]")
+ self.validate_identity("SELECT MAP['a' => 1]")
+ self.validate_identity("SELECT MAP['a' => MAP['b' => 'c']]")
+ self.validate_identity("SELECT CAST(MAP['a' => 1] AS MAP[TEXT => INT])")
+ self.validate_identity("SELECT CAST(NULL AS MAP[TEXT => INT])")
+ self.validate_identity("SELECT CAST(NULL AS MAP[TEXT => MAP[TEXT => INT]])")
+ self.validate_identity("SELECT MAP(SELECT 'a', 1)")
| [] | [
"tests/dialects/test_dialect.py::TestDialect::test_cast",
"tests/dialects/test_dialect.py::TestDialect::test_time",
"tests/dialects/test_materialize.py::TestMaterialize::test_materialize"
] | [
"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_to_user_defined_type",
"tests/dialects/test_dialect.py::TestDialect::te... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add Materialize dialect (WIP)
This is an attempt to add initial support for a [Materialize](https://materialize.com/docs/) dialect.
Any feedback is welcome! I'm planning to add more features soon.
----------
</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>
</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 | ||
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, ... | [
"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/... | 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 | |
embeddings-benchmark__mteb-854 | 854 | embeddings-benchmark/mteb | null | 4bded5a653a806d9068cfb9f246c86d75c3e4c55 | 2024-05-30T11:37:43Z | diff --git a/.gitignore b/.gitignore
index 119770cdb8..dd9c7ea386 100644
--- a/.gitignore
+++ b/.gitignore
@@ -137,3 +137,6 @@ error_logs.txt
# tests
tests/results
tmp.py
+
+# sandbox
+sb.ipynb
\ No newline at end of file
diff --git a/docs/mmteb/points.md b/docs/mmteb/points.md
index 7f4af0226a..d8a3a3e09a 100644
--- a/docs/mmteb/points.md
+++ b/docs/mmteb/points.md
@@ -88,4 +88,6 @@ Please also add your first name and last name are as you want them to appear in
| ShawonAshraf | Shawon | Ashraf | shawon@ellamind.com | ~Shawon_Ashraf1 | ellamind, Germany |
| bjoernpl | Björn | Plüster | bjoern@ellamind.com | ~Björn_Plüster1 | ellamind, Germany |
| jphme | Jan Philipp| Harries | jan@ellamind.com |~Jan_Philipp_Harries1 | ellamind, Germany |
-| malteos | Malte | Ostendorff | malte@occiglot.eu | ~Malte_Ostendorff1| Occiglot |
\ No newline at end of file
+| malteos | Malte | Ostendorff | malte@occiglot.eu | ~Malte_Ostendorff1| Occiglot |
+| ManuelFay | Manuel | Faysse | manuel.faysse@centralesupelec.fr | ~Manuel_Faysse1 | CentraleSupélec & Illuin Technology |
+| hgissbkh | Hippolyte | Gisserot-Boukhlef | hippolyte.gisserot-boukhlef@centralesupelec.fr | ~Hippolyte_Gisserot-Boukhlef1 | CentraleSupélec & Artefact |
\ No newline at end of file
diff --git a/docs/mmteb/points/854.jsonl b/docs/mmteb/points/854.jsonl
new file mode 100644
index 0000000000..a86907c26c
--- /dev/null
+++ b/docs/mmteb/points/854.jsonl
@@ -0,0 +1,5 @@
+{"GitHub": "ManuelFay", "Bug fixes": 13, "New task": 5}
+{"GitHub": "hgissbkh", "Bug fixes": 13, "New task": 5}
+{"GitHub": "KennethEnevoldsen", "PR Review": 2}
+{"GitHub": "imenelydiaker", "Review PR": 2}
+{"GitHub": "orionw", "Review PR": 2}
\ No newline at end of file
diff --git a/mteb/abstasks/AbsTaskRetrieval.py b/mteb/abstasks/AbsTaskRetrieval.py
index e29f03e32f..2bc0b13151 100644
--- a/mteb/abstasks/AbsTaskRetrieval.py
+++ b/mteb/abstasks/AbsTaskRetrieval.py
@@ -308,13 +308,13 @@ def _evaluate_subset(
with open(qrels_save_path, "w") as f:
json.dump(results, f)
- ndcg, _map, recall, precision = retriever.evaluate(
+ ndcg, _map, recall, precision, naucs = retriever.evaluate(
relevant_docs,
results,
retriever.k_values,
ignore_identical_ids=kwargs.get("ignore_identical_ids", True),
)
- mrr = retriever.evaluate_custom(
+ mrr, naucs_mrr = retriever.evaluate_custom(
relevant_docs, results, retriever.k_values, "mrr"
)
scores = {
@@ -323,6 +323,14 @@ def _evaluate_subset(
**{f"recall_at_{k.split('@')[1]}": v for (k, v) in recall.items()},
**{f"precision_at_{k.split('@')[1]}": v for (k, v) in precision.items()},
**{f"mrr_at_{k.split('@')[1]}": v for (k, v) in mrr.items()},
+ **{
+ k.replace("@", "_at_").replace("_P", "_precision").lower(): v
+ for k, v in naucs.items()
+ },
+ **{
+ k.replace("@", "_at_").replace("_P", "_precision").lower(): v
+ for k, v in naucs_mrr.items()
+ },
}
self._add_main_score(scores)
return scores
diff --git a/mteb/evaluation/evaluators/RerankingEvaluator.py b/mteb/evaluation/evaluators/RerankingEvaluator.py
index 67dccbba98..2572e34dcf 100644
--- a/mteb/evaluation/evaluators/RerankingEvaluator.py
+++ b/mteb/evaluation/evaluators/RerankingEvaluator.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import logging
+from typing import Dict, List
import numpy as np
import torch
@@ -8,7 +9,7 @@
from sklearn.metrics import average_precision_score
from .Evaluator import Evaluator
-from .utils import cos_sim
+from .utils import confidence_scores, cos_sim, nAUC
logger = logging.getLogger(__name__)
@@ -72,6 +73,7 @@ def compute_metrics_batched(self, model):
"""
all_mrr_scores = []
all_ap_scores = []
+ all_conf_scores = []
# using encode_queries and encode_corpus functions if they exists,
# which can be defined by users to add different instructions for query and passage conveniently
@@ -111,7 +113,7 @@ def compute_metrics_batched(self, model):
all_docs_embs = self._encode_unique_texts(all_docs, encode_corpus_func)
- # Compute scores
+ # Compute scores and confidence scores
logger.info("Evaluating...")
query_idx, docs_idx = 0, 0
for instance in self.samples:
@@ -131,14 +133,22 @@ def compute_metrics_batched(self, model):
is_relevant = [True] * num_pos + [False] * num_neg
- scores = self._compute_metrics_instance(query_emb, docs_emb, is_relevant)
+ sim_scores = self._compute_sim_scores_instance(query_emb, docs_emb)
+ scores = self._compute_metrics_instance(sim_scores, is_relevant)
+ conf_scores = self.conf_scores(sim_scores.tolist())
+
all_mrr_scores.append(scores["mrr"])
all_ap_scores.append(scores["ap"])
+ all_conf_scores.append(conf_scores)
mean_ap = np.mean(all_ap_scores)
mean_mrr = np.mean(all_mrr_scores)
- return {"map": mean_ap, "mrr": mean_mrr}
+ # Compute nAUCs
+ naucs_map = self.nAUC_scores(all_conf_scores, all_ap_scores, "map")
+ naucs_mrr = self.nAUC_scores(all_conf_scores, all_mrr_scores, "mrr")
+
+ return {**{"map": mean_ap, "mrr": mean_mrr}, **naucs_map, **naucs_mrr}
def compute_metrics_individual(self, model):
"""Embeds every (query, positive, negative) tuple individually.
@@ -148,6 +158,7 @@ def compute_metrics_individual(self, model):
"""
all_mrr_scores = []
all_ap_scores = []
+ all_conf_scores = []
# using encode_queries and encode_corpus functions if they exists,
# which can be defined by users to add different instructions for query and passage conveniently
@@ -177,14 +188,22 @@ def compute_metrics_individual(self, model):
)
docs_emb = np.asarray(encode_corpus_func(docs, batch_size=self.batch_size))
- scores = self._compute_metrics_instance(query_emb, docs_emb, is_relevant)
+ sim_scores = self._compute_sim_scores_instance(query_emb, docs_emb)
+ scores = self._compute_metrics_instance(sim_scores, is_relevant)
+ conf_scores = self.conf_scores(sim_scores.tolist())
+
all_mrr_scores.append(scores["mrr"])
all_ap_scores.append(scores["ap"])
+ all_conf_scores.append(conf_scores)
mean_ap = np.mean(all_ap_scores)
mean_mrr = np.mean(all_mrr_scores)
- return {"map": mean_ap, "mrr": mean_mrr}
+ # Compute nAUCs
+ naucs_map = self.nAUC_scores(all_conf_scores, all_ap_scores, "map")
+ naucs_mrr = self.nAUC_scores(all_conf_scores, all_mrr_scores, "mrr")
+
+ return {**{"map": mean_ap, "mrr": mean_mrr}, **naucs_map, **naucs_mrr}
def _encode_unique_texts(self, all_texts, encode_queries_func):
index_map, all_unique_texts, all_texts_indexes = {}, [], []
@@ -202,30 +221,86 @@ def _encode_unique_texts(self, all_texts, encode_queries_func):
)
return all_unique_texts_embs[all_texts_indexes]
- def _compute_metrics_instance(self, query_emb, docs_emb, is_relevant):
- """Computes metrics for a single instance = (query, positives, negatives)
+ def _compute_sim_scores_instance(
+ self, query_emb: torch.Tensor, docs_emb: torch.Tensor
+ ) -> torch.Tensor:
+ """Computes similarity scores for a single instance = (query, positives, negatives)
Args:
- query_emb (`torch.Tensor` of shape `(num_queries, hidden_size)`): Query embedding
+ query_emb: Query embedding, with shape `(num_queries, hidden_size)`
if `num_queries` > 0: we take the closest document to any of the queries
- docs_emb (`torch.Tensor` of shape `(num_pos+num_neg, hidden_size)`): Candidates documents embeddings
- is_relevant (`List[bool]` of length `num_pos+num_neg`): True if the document is relevant
+ docs_emb: Candidates documents embeddings, with shape `(num_pos+num_neg, hidden_size)`
Returns:
- scores (`Dict[str, float]`):
- - `mrr`: Mean Reciprocal Rank @ `self.mrr_at_k`
- - `ap`: Average Precision
+ sim_scores: Query-documents similarity scores, with shape `(num_pos+num_neg,)`
"""
- pred_scores = self.similarity_fct(query_emb, docs_emb)
- if len(pred_scores.shape) > 1:
- pred_scores = torch.amax(pred_scores, dim=0)
+ sim_scores = self.similarity_fct(query_emb, docs_emb)
+ if len(sim_scores.shape) > 1:
+ sim_scores = torch.amax(sim_scores, dim=0)
- pred_scores_argsort = torch.argsort(-pred_scores) # Sort in decreasing order
+ return sim_scores
+ def _compute_metrics_instance(
+ self, sim_scores: torch.Tensor, is_relevant: List[bool]
+ ) -> Dict[str, float]:
+ """Computes metrics for a single instance = (query, positives, negatives)
+
+ Args:
+ sim_scores: Query-documents similarity scores, with shape `(num_pos+num_neg,)`
+ is_relevant: True if the document is relevant, with length `num_pos+num_neg`
+
+ Returns:
+ scores:
+ - `mrr`: Mean Reciprocal Rank @ `self.mrr_at_k`
+ - `ap`: Average Precision
+ """
+ pred_scores_argsort = torch.argsort(-sim_scores) # Sort in decreasing order
mrr = self.mrr_at_k_score(is_relevant, pred_scores_argsort, self.mrr_at_k)
- ap = self.ap_score(is_relevant, pred_scores.cpu().tolist())
+ ap = self.ap_score(is_relevant, sim_scores.cpu().tolist())
return {"mrr": mrr, "ap": ap}
+ @staticmethod
+ def conf_scores(sim_scores: torch.Tensor) -> Dict[str, float]:
+ """Computes confidence scores for a single instance = (query, positives, negatives)
+
+ Args:
+ sim_scores: Query-documents similarity scores, with shape `(num_pos+num_neg,)`
+
+ Returns:
+ conf_scores:
+ - `max`: Maximum similarity score
+ - `std`: Standard deviation of similarity scores
+ - `diff1`: Difference between highest and second highest similarity scores
+ """
+ return confidence_scores(sim_scores)
+
+ @staticmethod
+ def nAUC_scores(
+ all_conf_scores: List[Dict[str, float]],
+ metrics: List[float],
+ metric_name: str,
+ ) -> Dict[str, float]:
+ """Computes normalized Area Under the Curve on a set of evaluated instances as presented in the paper https://arxiv.org/abs/2402.12997
+
+ Args:
+ all_conf_scores: Confidence scores for all instances, with length `len(samples)`
+ metrics: Metric scores for all instances, with length `len(samples)`
+ metric_name: Name of the metric (mrr or ap)
+
+ Returns:
+ naucs: nAUCs for each confidence function
+ """
+ conf_fcts = list(all_conf_scores[0].keys())
+ all_conf_scores = {
+ fct: np.array([x[fct] for x in all_conf_scores]) for fct in conf_fcts
+ }
+ metrics = np.array(metrics)
+ naucs = {
+ f"nAUC_{metric_name}_{fct}": nAUC(all_conf_scores[fct], metrics)
+ for fct in conf_fcts
+ }
+ return naucs
+
@staticmethod
def mrr_at_k_score(
is_relevant: list[bool], pred_ranking: list[int], k: int
diff --git a/mteb/evaluation/evaluators/RetrievalEvaluator.py b/mteb/evaluation/evaluators/RetrievalEvaluator.py
index c24ed5268c..112d3c9e80 100644
--- a/mteb/evaluation/evaluators/RetrievalEvaluator.py
+++ b/mteb/evaluation/evaluators/RetrievalEvaluator.py
@@ -7,6 +7,7 @@
from collections import defaultdict
from typing import Dict, List, Tuple, Union
+import numpy as np
import pytrec_eval
import torch
import tqdm
@@ -14,7 +15,17 @@
from sentence_transformers.models import Transformer, WordEmbeddings
from .Evaluator import Evaluator
-from .utils import cos_sim, dot_score, download, hole, mrr, recall_cap, top_k_accuracy
+from .utils import (
+ confidence_scores,
+ cos_sim,
+ dot_score,
+ download,
+ hole,
+ mrr,
+ nAUC,
+ recall_cap,
+ top_k_accuracy,
+)
logger = logging.getLogger(__name__)
@@ -501,8 +512,8 @@ def __call__(
corpus, queries, self.top_k, self.score_function
)
- @staticmethod
def evaluate(
+ self,
qrels: dict[str, dict[str, int]],
results: dict[str, dict[str, float]],
k_values: List[int],
@@ -519,16 +530,13 @@ def evaluate(
results[qid].pop(pid)
popped.append(pid)
- ndcg = {}
- _map = {}
- recall = {}
- precision = {}
+ all_ndcgs, all_aps, all_recalls, all_precisions = {}, {}, {}, {}
for k in k_values:
- ndcg[f"NDCG@{k}"] = 0.0
- _map[f"MAP@{k}"] = 0.0
- recall[f"Recall@{k}"] = 0.0
- precision[f"P@{k}"] = 0.0
+ all_ndcgs[f"NDCG@{k}"] = []
+ all_aps[f"MAP@{k}"] = []
+ all_recalls[f"Recall@{k}"] = []
+ all_precisions[f"P@{k}"] = []
map_string = "map_cut." + ",".join([str(k) for k in k_values])
ndcg_string = "ndcg_cut." + ",".join([str(k) for k in k_values])
@@ -541,37 +549,47 @@ def evaluate(
for query_id in scores.keys():
for k in k_values:
- ndcg[f"NDCG@{k}"] += scores[query_id]["ndcg_cut_" + str(k)]
- _map[f"MAP@{k}"] += scores[query_id]["map_cut_" + str(k)]
- recall[f"Recall@{k}"] += scores[query_id]["recall_" + str(k)]
- precision[f"P@{k}"] += scores[query_id]["P_" + str(k)]
+ all_ndcgs[f"NDCG@{k}"].append(scores[query_id]["ndcg_cut_" + str(k)])
+ all_aps[f"MAP@{k}"].append(scores[query_id]["map_cut_" + str(k)])
+ all_recalls[f"Recall@{k}"].append(scores[query_id]["recall_" + str(k)])
+ all_precisions[f"P@{k}"].append(scores[query_id]["P_" + str(k)])
+
+ ndcg, _map, recall, precision = (
+ all_ndcgs.copy(),
+ all_aps.copy(),
+ all_recalls.copy(),
+ all_precisions.copy(),
+ )
for k in k_values:
- ndcg[f"NDCG@{k}"] = round(ndcg[f"NDCG@{k}"] / len(scores), 5)
- _map[f"MAP@{k}"] = round(_map[f"MAP@{k}"] / len(scores), 5)
- recall[f"Recall@{k}"] = round(recall[f"Recall@{k}"] / len(scores), 5)
- precision[f"P@{k}"] = round(precision[f"P@{k}"] / len(scores), 5)
+ ndcg[f"NDCG@{k}"] = round(sum(ndcg[f"NDCG@{k}"]) / len(scores), 5)
+ _map[f"MAP@{k}"] = round(sum(_map[f"MAP@{k}"]) / len(scores), 5)
+ recall[f"Recall@{k}"] = round(sum(recall[f"Recall@{k}"]) / len(scores), 5)
+ precision[f"P@{k}"] = round(sum(precision[f"P@{k}"]) / len(scores), 5)
- for eval in [ndcg, _map, recall, precision]:
- logger.info("\n")
- for k in eval.keys():
- logger.info("{}: {:.4f}".format(k, eval[k]))
+ naucs = self.evaluate_abstention(
+ results, {**all_ndcgs, **all_aps, **all_recalls, **all_precisions}
+ )
- return ndcg, _map, recall, precision
+ return ndcg, _map, recall, precision, naucs
- @staticmethod
def evaluate_custom(
+ self,
qrels: dict[str, dict[str, int]],
results: dict[str, dict[str, float]],
k_values: List[int],
metric: str,
+ output_type: str = "all",
) -> Tuple[Dict[str, float]]:
if metric.lower() in ["mrr", "mrr@k", "mrr_cut"]:
- return mrr(qrels, results, k_values)
+ metric_scores = mrr(qrels, results, k_values, output_type)
+
elif metric.lower() in ["recall_cap", "r_cap", "r_cap@k"]:
- return recall_cap(qrels, results, k_values)
+ metric_scores = recall_cap(qrels, results, k_values, output_type)
+
elif metric.lower() in ["hole", "hole@k"]:
- return hole(qrels, results, k_values)
+ metric_scores = hole(qrels, results, k_values, output_type)
+
elif metric.lower() in [
"acc",
"top_k_acc",
@@ -579,4 +597,32 @@ def evaluate_custom(
"accuracy@k",
"top_k_accuracy",
]:
- return top_k_accuracy(qrels, results, k_values)
+ metric_scores = top_k_accuracy(qrels, results, k_values, output_type)
+
+ naucs = self.evaluate_abstention(results, metric_scores)
+ metric_scores_avg = {k: sum(v) / len(v) for k, v in metric_scores.items()}
+
+ return metric_scores_avg, naucs
+
+ @staticmethod
+ def evaluate_abstention(
+ results: dict[str, dict[str, float]],
+ metric_scores: dict[str, list[float]],
+ ) -> Dict[str, float]:
+ """Computes normalized Area Under the Curve on a set of evaluated instances as presented in the paper https://arxiv.org/abs/2402.12997"""
+ all_sim_scores = [list(results[qid].values()) for qid in list(results.keys())]
+ all_conf_scores = [
+ confidence_scores(sim_scores) for sim_scores in all_sim_scores
+ ]
+ conf_fcts = list(all_conf_scores[0].keys())
+ all_conf_scores = {
+ fct: np.array([x[fct] for x in all_conf_scores]) for fct in conf_fcts
+ }
+ metric_scores = {k: np.array(v) for k, v in metric_scores.items()}
+ naucs = {}
+
+ for metric_name, scores in metric_scores.items():
+ for fct, conf_scores in all_conf_scores.items():
+ naucs[f"nAUC_{metric_name}_{fct}"] = nAUC(conf_scores, scores)
+
+ return naucs
diff --git a/mteb/evaluation/evaluators/utils.py b/mteb/evaluation/evaluators/utils.py
index 1103d4f801..d42da153b6 100644
--- a/mteb/evaluation/evaluators/utils.py
+++ b/mteb/evaluation/evaluators/utils.py
@@ -3,10 +3,12 @@
import logging
from typing import Dict, List, Tuple
+import numpy as np
import pandas as pd
import requests
import torch
import tqdm
+from sklearn.metrics import auc
def cos_sim(a, b):
@@ -56,11 +58,12 @@ def mrr(
qrels: dict[str, dict[str, int]],
results: dict[str, dict[str, float]],
k_values: List[int],
+ output_type: str = "mean",
) -> Tuple[Dict[str, float]]:
MRR = {}
for k in k_values:
- MRR[f"MRR@{k}"] = 0.0
+ MRR[f"MRR@{k}"] = []
k_max, top_hits = max(k_values), {}
logging.info("\n")
@@ -75,14 +78,20 @@ def mrr(
[doc_id for doc_id in qrels[query_id] if qrels[query_id][doc_id] > 0]
)
for k in k_values:
+ rr = 0
for rank, hit in enumerate(top_hits[query_id][0:k]):
if hit[0] in query_relevant_docs:
- MRR[f"MRR@{k}"] += 1.0 / (rank + 1)
+ rr = 1.0 / (rank + 1)
break
+ MRR[f"MRR@{k}"].append(rr)
- for k in k_values:
- MRR[f"MRR@{k}"] = round(MRR[f"MRR@{k}"] / len(qrels), 5)
- logging.info("MRR@{}: {:.4f}".format(k, MRR[f"MRR@{k}"]))
+ if output_type == "mean":
+ for k in k_values:
+ MRR[f"MRR@{k}"] = round(sum(MRR[f"MRR@{k}"]) / len(qrels), 5)
+ logging.info("MRR@{}: {:.4f}".format(k, MRR[f"MRR@{k}"]))
+
+ elif output_type == "all":
+ pass
return MRR
@@ -91,11 +100,12 @@ def recall_cap(
qrels: dict[str, dict[str, int]],
results: dict[str, dict[str, float]],
k_values: List[int],
+ output_type: str = "mean",
) -> Tuple[Dict[str, float]]:
capped_recall = {}
for k in k_values:
- capped_recall[f"R_cap@{k}"] = 0.0
+ capped_recall[f"R_cap@{k}"] = []
k_max = max(k_values)
logging.info("\n")
@@ -112,11 +122,17 @@ def recall_cap(
row[0] for row in top_hits[0:k] if qrels[query_id].get(row[0], 0) > 0
]
denominator = min(len(query_relevant_docs), k)
- capped_recall[f"R_cap@{k}"] += len(retrieved_docs) / denominator
+ capped_recall[f"R_cap@{k}"].append(len(retrieved_docs) / denominator)
- for k in k_values:
- capped_recall[f"R_cap@{k}"] = round(capped_recall[f"R_cap@{k}"] / len(qrels), 5)
- logging.info("R_cap@{}: {:.4f}".format(k, capped_recall[f"R_cap@{k}"]))
+ if output_type == "mean":
+ for k in k_values:
+ capped_recall[f"R_cap@{k}"] = round(
+ sum(capped_recall[f"R_cap@{k}"]) / len(qrels), 5
+ )
+ logging.info("R_cap@{}: {:.4f}".format(k, capped_recall[f"R_cap@{k}"]))
+
+ elif output_type == "all":
+ pass
return capped_recall
@@ -125,11 +141,12 @@ def hole(
qrels: dict[str, dict[str, int]],
results: dict[str, dict[str, float]],
k_values: List[int],
+ output_type: str = "mean",
) -> Tuple[Dict[str, float]]:
Hole = {}
for k in k_values:
- Hole[f"Hole@{k}"] = 0.0
+ Hole[f"Hole@{k}"] = []
annotated_corpus = set()
for _, docs in qrels.items():
@@ -147,11 +164,15 @@ def hole(
hole_docs = [
row[0] for row in top_hits[0:k] if row[0] not in annotated_corpus
]
- Hole[f"Hole@{k}"] += len(hole_docs) / k
+ Hole[f"Hole@{k}"].append(len(hole_docs) / k)
- for k in k_values:
- Hole[f"Hole@{k}"] = round(Hole[f"Hole@{k}"] / len(qrels), 5)
- logging.info("Hole@{}: {:.4f}".format(k, Hole[f"Hole@{k}"]))
+ if output_type == "mean":
+ for k in k_values:
+ Hole[f"Hole@{k}"] = round(Hole[f"Hole@{k}"] / len(qrels), 5)
+ logging.info("Hole@{}: {:.4f}".format(k, Hole[f"Hole@{k}"]))
+
+ elif output_type == "all":
+ pass
return Hole
@@ -160,11 +181,12 @@ def top_k_accuracy(
qrels: dict[str, dict[str, int]],
results: dict[str, dict[str, float]],
k_values: List[int],
+ output_type: str = "mean",
) -> Tuple[Dict[str, float]]:
top_k_acc = {}
for k in k_values:
- top_k_acc[f"Accuracy@{k}"] = 0.0
+ top_k_acc[f"Accuracy@{k}"] = []
k_max, top_hits = max(k_values), {}
logging.info("\n")
@@ -184,12 +206,18 @@ def top_k_accuracy(
for k in k_values:
for relevant_doc_id in query_relevant_docs:
if relevant_doc_id in top_hits[query_id][0:k]:
- top_k_acc[f"Accuracy@{k}"] += 1.0
+ top_k_acc[f"Accuracy@{k}"].append(1.0)
break
- for k in k_values:
- top_k_acc[f"Accuracy@{k}"] = round(top_k_acc[f"Accuracy@{k}"] / len(qrels), 5)
- logging.info("Accuracy@{}: {:.4f}".format(k, top_k_acc[f"Accuracy@{k}"]))
+ if output_type == "mean":
+ for k in k_values:
+ top_k_acc[f"Accuracy@{k}"] = round(
+ top_k_acc[f"Accuracy@{k}"] / len(qrels), 5
+ )
+ logging.info("Accuracy@{}: {:.4f}".format(k, top_k_acc[f"Accuracy@{k}"]))
+
+ elif output_type == "all":
+ pass
return top_k_acc
@@ -264,3 +292,107 @@ def download(url: str, fname: str):
for data in resp.iter_content(chunk_size=1024):
size = file.write(data)
bar.update(size)
+
+
+def confidence_scores(sim_scores: List[float]) -> Dict[str, float]:
+ """Computes confidence scores for a single instance = (query, positives, negatives)
+
+ Args:
+ sim_scores: Query-documents similarity scores with length `num_pos+num_neg`
+
+ Returns:
+ conf_scores:
+ - `max`: Maximum similarity score
+ - `std`: Standard deviation of similarity scores
+ - `diff1`: Difference between highest and second highest similarity scores
+ """
+ sim_scores_sorted = sorted(sim_scores)[::-1]
+
+ cs_max = sim_scores_sorted[0]
+ cs_std = np.std(sim_scores)
+ if len(sim_scores) > 1:
+ cs_diff1 = sim_scores_sorted[0] - sim_scores_sorted[1]
+ elif len(sim_scores) == 1:
+ cs_diff1 = 0.
+
+ conf_scores = {"max": cs_max, "std": cs_std, "diff1": cs_diff1}
+
+ return conf_scores
+
+
+def nAUC(
+ conf_scores: np.ndarray,
+ metrics: np.ndarray,
+ abstention_rates: np.ndarray = np.linspace(0,1,11)[:-1],
+) -> float:
+ """Computes normalized Area Under the Curve on a set of evaluated instances as presented in the paper https://arxiv.org/abs/2402.12997
+ 1/ Computes the raw abstention curve, i.e., the average evaluation metric at different abstention rates determined by the confidence scores
+ 2/ Computes the oracle abstention curve, i.e., the best theoretical abstention curve (e.g.: at a 10% abstention rate, the oracle abstains on the bottom-10% instances with regard to the evaluation metric)
+ 3/ Computes the flat abstention curve, i.e., the one remains flat for all abstention rates (ineffective abstention)
+ 4/ Computes the area under the three curves
+ 5/ Finally scales the raw AUC between the oracle and the flat AUCs to get normalized AUC
+
+ Args:
+ conf_scores: Instance confidence scores used for abstention thresholding, with shape `(num_test_instances,)`
+ metrics: Metric evaluations at instance-level (e.g.: average precision, NDCG...), with shape `(num_test_instances,)`
+ abstention_rates: Target rates for the computation of the abstention curve
+
+ Returns:
+ abst_nauc: Normalized area under the abstention curve (upper-bounded by 1)
+ """
+
+ def abstention_curve(
+ conf_scores: np.ndarray,
+ metrics: np.ndarray,
+ abstention_rates: np.ndarray = np.linspace(0,1,11)[:-1],
+ ) -> np.ndarray:
+ """Computes the raw abstention curve for a given set of evaluated instances and corresponding confidence scores
+
+ Args:
+ conf_scores: Instance confidence scores used for abstention thresholding, with shape `(num_test_instances,)`
+ metrics: Metric evaluations at instance-level (e.g.: average precision, NDCG...), with shape `(num_test_instances,)`
+ abstention_rates: Target rates for the computation of the abstention curve
+
+ Returns:
+ abst_curve: Abstention curve of length `len(abstention_rates)`
+ """
+ abst_curve = np.zeros(len(abstention_rates))
+ abstention_thresholds = np.quantile(conf_scores, abstention_rates)
+
+ for i, abstention_threshold in enumerate(abstention_thresholds):
+ abst_curve[i] = metrics[conf_scores >= abstention_threshold].mean()
+
+ return abst_curve
+
+ def oracle_curve(
+ metrics: np.ndaray, abstention_rates: np.ndarray = np.linspace(0,1,11)[:-1]
+ ) -> np.ndarray:
+ """Computes the oracle curve for a given set of evaluated instances
+
+ Args:
+ metrics: Metric evaluations at instance-level, with shape `(num_test_instances,)`
+ abstention_rates: Target rates for the computation of the abstention curve
+
+ Returns:
+ or_curve: Oracle curve of length `len(abstention_rates)`
+ """
+ metrics_argsort = np.argsort(metrics)
+ or_curve = np.zeros(len(abstention_rates))
+
+ for i, rate in enumerate(abstention_rates):
+ or_curve[i] = metrics[metrics_argsort[round(rate * len(metrics)) :]].mean()
+
+ return or_curve
+
+ abst_curve = abstention_curve(conf_scores, metrics, abstention_rates)
+ or_curve = oracle_curve(metrics, abstention_rates)
+ abst_auc = auc(abstention_rates, abst_curve)
+ or_auc = auc(abstention_rates, or_curve)
+ flat_auc = or_curve[0] * (abstention_rates[-1] - abstention_rates[0])
+
+ if or_auc == flat_auc:
+ abst_nauc = np.nan
+ else:
+ abst_nauc = (abst_auc - flat_auc) / (or_auc - flat_auc)
+
+ return abst_nauc
| diff --git a/tests/test_RerankingEvaluator.py b/tests/test_RerankingEvaluator.py
index 5c0cb20584..94e43695f8 100644
--- a/tests/test_RerankingEvaluator.py
+++ b/tests/test_RerankingEvaluator.py
@@ -36,3 +36,21 @@ def test_map(self):
assert self.evaluator.ap_score(is_relevant, pred_scores) == pytest.approx(
0.86666, TOL
)
+
+ def test_nAUC(self):
+ is_relevant = [[1, 1, 0, 0, 0], [1, 0, 0], [1, 1, 1, 0], [1, 0], [1, 1, 0, 0]]
+ pred_scores = [
+ [0.8, 0.3, 0.4, 0.6, 0.5],
+ [0.5, 0.8, 0.4],
+ [0.9, 0.3, 0.3, 0.1],
+ [0.1, 0.2],
+ [0.5, 0.4, 0.5, 0.2],
+ ]
+
+ ap_scores = [self.evaluator.ap_score(y, x) for x, y in zip(pred_scores, is_relevant)]
+ conf_scores = [self.evaluator.conf_scores(x) for x in pred_scores]
+ nauc_scores_map = self.evaluator.nAUC_scores(conf_scores, ap_scores, "map")
+
+ assert nauc_scores_map["nAUC_map_max"] == pytest.approx(0.69555, TOL)
+ assert nauc_scores_map["nAUC_map_std"] == pytest.approx(0.86172, TOL)
+ assert nauc_scores_map["nAUC_map_diff1"] == pytest.approx(0.68961, TOL)
diff --git a/tests/test_RetrievalEvaluator.py b/tests/test_RetrievalEvaluator.py
index 81b6dc9227..f01cae7659 100644
--- a/tests/test_RetrievalEvaluator.py
+++ b/tests/test_RetrievalEvaluator.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import pytest
+
from mteb.evaluation.evaluators import RetrievalEvaluator
TOL = 0.0001
@@ -24,7 +26,7 @@ def test_metrics_at_k(self):
"1": {"0": 0.0, "1": 1.0, "2": 0.0},
}
- ndcg, _map, recall, precision = self.evaluator.evaluate(
+ ndcg, _map, recall, precision, _ = self.evaluator.evaluate(
relevant_docs,
results,
[1, 2, 3],
@@ -34,3 +36,29 @@ def test_metrics_at_k(self):
assert _map == {"MAP@1": 0.25, "MAP@2": 0.25, "MAP@3": 0.25}
assert recall == {"Recall@1": 0.25, "Recall@2": 0.25, "Recall@3": 0.25}
assert precision == {"P@1": 0.5, "P@2": 0.25, "P@3": 0.16667}
+
+ def test_nAUC(self):
+ relevant_docs = {
+ "0": {"0": 1, "1": 1},
+ "1": {"0": 1},
+ "2": {"0": 1, "1": 1, "2": 1},
+ "3": {"0": 1},
+ "4": {"0": 1, "1": 1},
+ }
+ results = {
+ "0": {"0": 0.8, "1": 0.3, "2": 0.4},
+ "1": {"0": 0.5, "1": 0.8, "2": 0.4},
+ "2": {"0": 0.9, "1": 0.3, "2": 0.3},
+ "3": {"0": 0.1, "1": 0.2, "2": 0.2},
+ "4": {"0": 0.5, "1": 0.4, "2": 0.5},
+ }
+
+ _, _, _, _, naucs = self.evaluator.evaluate(
+ relevant_docs,
+ results,
+ [1, 2, 3],
+ )
+
+ assert naucs["nAUC_NDCG@3_max"] == pytest.approx(0.62792, TOL)
+ assert naucs["nAUC_NDCG@3_std"] == pytest.approx(0.06211, TOL)
+ assert naucs["nAUC_NDCG@3_diff1"] == pytest.approx(0.06600, TOL)
| diff --git a/.gitignore b/.gitignore
index 119770cdb8..dd9c7ea386 100644
--- a/.gitignore
+++ b/.gitignore
@@ -137,3 +137,6 @@ error_logs.txt
# tests
tests/results
tmp.py
+
+# sandbox
+sb.ipynb
\ No newline at end of file
diff --git a/docs/mmteb/points.md b/docs/mmteb/points.md
index 7f4af0226a..d8a3a3e09a 100644
--- a/docs/mmteb/points.md
+++ b/docs/mmteb/points.md
@@ -88,4 +88,6 @@ Please also add your first name and last name are as you want them to appear in
| ShawonAshraf | Shawon | Ashraf | shawon@ellamind.com | ~Shawon_Ashraf1 | ellamind, Germany |
| bjoernpl | Björn | Plüster | bjoern@ellamind.com | ~Björn_Plüster1 | ellamind, Germany |
| jphme | Jan Philipp| Harries | jan@ellamind.com |~Jan_Philipp_Harries1 | ellamind, Germany |
-| malteos | Malte | Ostendorff | malte@occiglot.eu | ~Malte_Ostendorff1| Occiglot |
\ No newline at end of file
+| malteos | Malte | Ostendorff | malte@occiglot.eu | ~Malte_Ostendorff1| Occiglot |
+| ManuelFay | Manuel | Faysse | manuel.faysse@centralesupelec.fr | ~Manuel_Faysse1 | CentraleSupélec & Illuin Technology |
+| hgissbkh | Hippolyte | Gisserot-Boukhlef | hippolyte.gisserot-boukhlef@centralesupelec.fr | ~Hippolyte_Gisserot-Boukhlef1 | CentraleSupélec & Artefact |
\ No newline at end of file
diff --git a/docs/mmteb/points/854.jsonl b/docs/mmteb/points/854.jsonl
new file mode 100644
index 0000000000..a86907c26c
--- /dev/null
+++ b/docs/mmteb/points/854.jsonl
@@ -0,0 +1,5 @@
+{"GitHub": "ManuelFay", "Bug fixes": 13, "New task": 5}
+{"GitHub": "hgissbkh", "Bug fixes": 13, "New task": 5}
+{"GitHub": "KennethEnevoldsen", "PR Review": 2}
+{"GitHub": "imenelydiaker", "Review PR": 2}
+{"GitHub": "orionw", "Review PR": 2}
\ No newline at end of file
| [
{
"components": [
{
"doc": "Computes similarity scores for a single instance = (query, positives, negatives)\n\nArgs:\n query_emb: Query embedding, with shape `(num_queries, hidden_size)`\n if `num_queries` > 0: we take the closest document to any of the queries\n docs_emb: Candidates... | [
"tests/test_RerankingEvaluator.py::TestRerankingEvaluator::test_nAUC",
"tests/test_RetrievalEvaluator.py::TestRetrievalEvaluator::test_metrics_at_k",
"tests/test_RetrievalEvaluator.py::TestRetrievalEvaluator::test_nAUC"
] | [
"tests/test_RerankingEvaluator.py::TestRerankingEvaluator::test_mrr_at_k",
"tests/test_RerankingEvaluator.py::TestRerankingEvaluator::test_map"
] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add abstention metrics to retrieval and reranking tasks
Hi @KennethEnevoldsen,
As discussed in PR [https://github.com/embeddings-benchmark/mteb/pull/841](https://github.com/embeddings-benchmark/mteb/pull/841), the most up-to-date version of our code is now 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 mteb/evaluation/evaluators/RerankingEvaluator.py]
(definition of RerankingEvaluator._compute_sim_scores_instance:)
def _compute_sim_scores_instance( self, query_emb: torch.Tensor, docs_emb: torch.Tensor ) -> torch.Tensor:
"""Computes similarity scores for a single instance = (query, positives, negatives)
Args:
query_emb: Query embedding, with shape `(num_queries, hidden_size)`
if `num_queries` > 0: we take the closest document to any of the queries
docs_emb: Candidates documents embeddings, with shape `(num_pos+num_neg, hidden_size)`
Returns:
sim_scores: Query-documents similarity scores, with shape `(num_pos+num_neg,)`"""
(definition of RerankingEvaluator.conf_scores:)
def conf_scores(sim_scores: torch.Tensor) -> Dict[str, float]:
"""Computes confidence scores for a single instance = (query, positives, negatives)
Args:
sim_scores: Query-documents similarity scores, with shape `(num_pos+num_neg,)`
Returns:
conf_scores:
- `max`: Maximum similarity score
- `std`: Standard deviation of similarity scores
- `diff1`: Difference between highest and second highest similarity scores"""
(definition of RerankingEvaluator.nAUC_scores:)
def nAUC_scores( all_conf_scores: List[Dict[str, float]], metrics: List[float], metric_name: str, ) -> Dict[str, float]:
"""Computes normalized Area Under the Curve on a set of evaluated instances as presented in the paper https://arxiv.org/abs/2402.12997
Args:
all_conf_scores: Confidence scores for all instances, with length `len(samples)`
metrics: Metric scores for all instances, with length `len(samples)`
metric_name: Name of the metric (mrr or ap)
Returns:
naucs: nAUCs for each confidence function"""
[end of new definitions in mteb/evaluation/evaluators/RerankingEvaluator.py]
[start of new definitions in mteb/evaluation/evaluators/RetrievalEvaluator.py]
(definition of RetrievalEvaluator.evaluate_abstention:)
def evaluate_abstention( results: dict[str, dict[str, float]], metric_scores: dict[str, list[float]], ) -> Dict[str, float]:
"""Computes normalized Area Under the Curve on a set of evaluated instances as presented in the paper https://arxiv.org/abs/2402.12997"""
[end of new definitions in mteb/evaluation/evaluators/RetrievalEvaluator.py]
[start of new definitions in mteb/evaluation/evaluators/utils.py]
(definition of confidence_scores:)
def confidence_scores(sim_scores: List[float]) -> Dict[str, float]:
"""Computes confidence scores for a single instance = (query, positives, negatives)
Args:
sim_scores: Query-documents similarity scores with length `num_pos+num_neg`
Returns:
conf_scores:
- `max`: Maximum similarity score
- `std`: Standard deviation of similarity scores
- `diff1`: Difference between highest and second highest similarity scores"""
(definition of nAUC:)
def nAUC( conf_scores: np.ndarray, metrics: np.ndarray, abstention_rates: np.ndarray = np.linspace(0,1,11)[:-1], ) -> float:
"""Computes normalized Area Under the Curve on a set of evaluated instances as presented in the paper https://arxiv.org/abs/2402.12997
1/ Computes the raw abstention curve, i.e., the average evaluation metric at different abstention rates determined by the confidence scores
2/ Computes the oracle abstention curve, i.e., the best theoretical abstention curve (e.g.: at a 10% abstention rate, the oracle abstains on the bottom-10% instances with regard to the evaluation metric)
3/ Computes the flat abstention curve, i.e., the one remains flat for all abstention rates (ineffective abstention)
4/ Computes the area under the three curves
5/ Finally scales the raw AUC between the oracle and the flat AUCs to get normalized AUC
Args:
conf_scores: Instance confidence scores used for abstention thresholding, with shape `(num_test_instances,)`
metrics: Metric evaluations at instance-level (e.g.: average precision, NDCG...), with shape `(num_test_instances,)`
abstention_rates: Target rates for the computation of the abstention curve
Returns:
abst_nauc: Normalized area under the abstention curve (upper-bounded by 1)"""
(definition of nAUC.abstention_curve:)
def abstention_curve( conf_scores: np.ndarray, metrics: np.ndarray, abstention_rates: np.ndarray = np.linspace(0,1,11)[:-1], ) -> np.ndarray:
"""Computes the raw abstention curve for a given set of evaluated instances and corresponding confidence scores
Args:
conf_scores: Instance confidence scores used for abstention thresholding, with shape `(num_test_instances,)`
metrics: Metric evaluations at instance-level (e.g.: average precision, NDCG...), with shape `(num_test_instances,)`
abstention_rates: Target rates for the computation of the abstention curve
Returns:
abst_curve: Abstention curve of length `len(abstention_rates)`"""
(definition of nAUC.oracle_curve:)
def oracle_curve( metrics: np.ndaray, abstention_rates: np.ndarray = np.linspace(0,1,11)[:-1] ) -> np.ndarray:
"""Computes the oracle curve for a given set of evaluated instances
Args:
metrics: Metric evaluations at instance-level, with shape `(num_test_instances,)`
abstention_rates: Target rates for the computation of the abstention curve
Returns:
or_curve: Oracle curve of length `len(abstention_rates)`"""
[end of new definitions in mteb/evaluation/evaluators/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>> | b580b95fc91a7e7e675d27c3ae9a9df64ddad169 | |
deepset-ai__haystack-7765 | 7,765 | deepset-ai/haystack | null | 5c468feecf580099fe6e6703d8d7b2c047d0887d | 2024-05-30T10:06:07Z | diff --git a/docs/pydoc/config/joiners_api.yml b/docs/pydoc/config/joiners_api.yml
index 9cbf2b161c..ad6e89a52a 100644
--- a/docs/pydoc/config/joiners_api.yml
+++ b/docs/pydoc/config/joiners_api.yml
@@ -1,7 +1,7 @@
loaders:
- type: haystack_pydoc_tools.loaders.CustomPythonLoader
search_path: [../../../haystack/components/joiners]
- modules: ["document_joiner"]
+ modules: ["document_joiner", "branch"]
ignore_when_discovered: ["__init__"]
processors:
- type: filter
diff --git a/haystack/components/joiners/__init__.py b/haystack/components/joiners/__init__.py
index 23f815050a..a72f73c134 100644
--- a/haystack/components/joiners/__init__.py
+++ b/haystack/components/joiners/__init__.py
@@ -2,6 +2,7 @@
#
# SPDX-License-Identifier: Apache-2.0
-from haystack.components.joiners.document_joiner import DocumentJoiner
+from .branch import BranchJoiner
+from .document_joiner import DocumentJoiner
-__all__ = ["DocumentJoiner"]
+__all__ = ["DocumentJoiner", "BranchJoiner"]
diff --git a/haystack/components/joiners/branch.py b/haystack/components/joiners/branch.py
new file mode 100644
index 0000000000..45673f1a49
--- /dev/null
+++ b/haystack/components/joiners/branch.py
@@ -0,0 +1,141 @@
+# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
+#
+# SPDX-License-Identifier: Apache-2.0
+
+from typing import Any, Dict, Type
+
+from haystack import component, default_from_dict, default_to_dict, logging
+from haystack.core.component.types import Variadic
+from haystack.utils import deserialize_type, serialize_type
+
+logger = logging.getLogger(__name__)
+
+
+@component(is_greedy=True)
+class BranchJoiner:
+ """
+ A component to join different branches of a pipeline into one single output.
+
+ `BranchJoiner` receives multiple data connections of the same type from other components and passes the first
+ value coming to its single output, possibly distributing it to various other components.
+
+ `BranchJoiner` is fundamental to close loops in a pipeline, where the two branches it joins are the ones
+ coming from the previous component and one coming back from a loop. For example, `BranchJoiner` could be used
+ to send data to a component evaluating errors. `BranchJoiner` would receive two connections, one to get the
+ original data and another one to get modified data in case there was an error. In both cases, `BranchJoiner`
+ would send (or re-send in case of a loop) data to the component evaluating errors. See "Usage example" below.
+
+ Another use case with a need for `BranchJoiner` is to reconcile multiple branches coming out of a decision
+ or Classifier component. For example, in a RAG pipeline, there might be a "query language classifier" component
+ sending the query to different retrievers, selecting one specifically according to the detected language. After the
+ retrieval step the pipeline would ideally continue with a `PromptBuilder`, and since we don't know in advance the
+ language of the query, all the retrievers should be ideally connected to the single `PromptBuilder`. Since the
+ `PromptBuilder` won't accept more than one connection in input, we would connect all the retrievers to a
+ `BranchJoiner` component and reconcile them in a single output that can be connected to the `PromptBuilder`
+ downstream.
+
+ Usage example:
+
+ ```python
+ import json
+ from typing import List
+
+ from haystack import Pipeline
+ from haystack.components.converters import OutputAdapter
+ from haystack.components.generators.chat import OpenAIChatGenerator
+ from haystack.components.joiners import BranchJoiner
+ from haystack.components.validators import JsonSchemaValidator
+ from haystack.dataclasses import ChatMessage
+
+ person_schema = {
+ "type": "object",
+ "properties": {
+ "first_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"},
+ "last_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"},
+ "nationality": {"type": "string", "enum": ["Italian", "Portuguese", "American"]},
+ },
+ "required": ["first_name", "last_name", "nationality"]
+ }
+
+ # Initialize a pipeline
+ pipe = Pipeline()
+
+ # Add components to the pipeline
+ pipe.add_component('joiner', BranchJoiner(List[ChatMessage]))
+ pipe.add_component('fc_llm', OpenAIChatGenerator(model="gpt-3.5-turbo-0125"))
+ pipe.add_component('validator', JsonSchemaValidator(json_schema=person_schema))
+ pipe.add_component('adapter', OutputAdapter("{{chat_message}}", List[ChatMessage])),
+ # And connect them
+ pipe.connect("adapter", "joiner")
+ pipe.connect("joiner", "fc_llm")
+ pipe.connect("fc_llm.replies", "validator.messages")
+ pipe.connect("validator.validation_error", "joiner")
+
+ result = pipe.run(data={"fc_llm": {"generation_kwargs": {"response_format": {"type": "json_object"}}},
+ "adapter": {"chat_message": [ChatMessage.from_user("Create json object from Peter Parker")]}})
+
+ print(json.loads(result["validator"]["validated"][0].content))
+
+
+ >> {'first_name': 'Peter', 'last_name': 'Parker', 'nationality': 'American', 'name': 'Spider-Man', 'occupation':
+ >> 'Superhero', 'age': 23, 'location': 'New York City'}
+ ```
+
+ Note that `BranchJoiner` can manage only one data type at a time. In this case, `BranchJoiner` is created for passing
+ `List[ChatMessage]`. This determines the type of data that `BranchJoiner` will receive from the upstream connected
+ components and also the type of data that `BranchJoiner` will send through its output.
+
+ In the code example, `BranchJoiner` receives a looped back `List[ChatMessage]` from the `JsonSchemaValidator` and
+ sends it down to the `OpenAIChatGenerator` for re-generation. We can have multiple loopback connections in the
+ pipeline. In this instance, the downstream component is only one (the `OpenAIChatGenerator`), but the pipeline might
+ have more than one downstream component.
+ """
+
+ def __init__(self, type_: Type):
+ """
+ Create a `BranchJoiner` component.
+
+ :param type_: The type of data that the `BranchJoiner` will receive from the upstream connected components and
+ distribute to the downstream connected components.
+ """
+ self.type_ = type_
+ # type_'s type can't be determined statically
+ component.set_input_types(self, value=Variadic[type_]) # type: ignore
+ component.set_output_types(self, value=type_)
+
+ def to_dict(self):
+ """
+ Serializes the component to a dictionary.
+
+ :returns:
+ Dictionary with serialized data.
+ """
+ return default_to_dict(self, type_=serialize_type(self.type_))
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "BranchJoiner":
+ """
+ Deserializes the component from a dictionary.
+
+ :param data:
+ Dictionary to deserialize from.
+ :returns:
+ Deserialized component.
+ """
+ data["init_parameters"]["type_"] = deserialize_type(data["init_parameters"]["type_"])
+ return default_from_dict(cls, data)
+
+ def run(self, **kwargs):
+ """
+ The run method of the `BranchJoiner` component.
+
+ Multiplexes the input data from the upstream connected components and distributes it to the downstream connected
+ components.
+
+ :param **kwargs: The input data. Must be of the type declared in `__init__`.
+ :return: A dictionary with the following keys:
+ - `value`: The input data.
+ """
+ if (inputs_count := len(kwargs["value"])) != 1:
+ raise ValueError(f"BranchJoiner expects only one input, but {inputs_count} were received.")
+ return {"value": kwargs["value"][0]}
diff --git a/haystack/components/others/multiplexer.py b/haystack/components/others/multiplexer.py
index 0f23debe89..015fcd7328 100644
--- a/haystack/components/others/multiplexer.py
+++ b/haystack/components/others/multiplexer.py
@@ -3,6 +3,7 @@
# SPDX-License-Identifier: Apache-2.0
import sys
+import warnings
from typing import Any, Dict
from haystack import component, default_from_dict, default_to_dict, logging
@@ -103,6 +104,10 @@ def __init__(self, type_: TypeAlias):
:param type_: The type of data that the `Multiplexer` will receive from the upstream connected components and
distribute to the downstream connected components.
"""
+ warnings.warn(
+ "`Multiplexer` is deprecated and will be removed in Haystack 2.4.0. Use `joiners.BranchJoiner` instead.",
+ DeprecationWarning,
+ )
self.type_ = type_
component.set_input_types(self, value=Variadic[type_])
component.set_output_types(self, value=type_)
diff --git a/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml b/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml
new file mode 100644
index 0000000000..75893aa537
--- /dev/null
+++ b/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml
@@ -0,0 +1,14 @@
+---
+highlights: >
+ The `Multiplexer` component proved to be hard to explain and to understand. After reviewing its use cases, the documentation
+ was rewritten and the component was renamed to `BranchJoiner` to better explain its functionalities.
+upgrade:
+ - |
+ `BranchJoiner` has the very same interface as `Multiplexer`. To upgrade your code, just rename any occurrence
+ of `Multiplexer` to `BranchJoiner` and ajdust the imports accordingly.
+features:
+ - |
+ Add `BranchJoiner` to eventually replace `Multiplexer`
+deprecations:
+ - |
+ `Mulitplexer` is now deprecated.
| diff --git a/test/components/joiners/test_branch_joiner.py b/test/components/joiners/test_branch_joiner.py
new file mode 100644
index 0000000000..05d30ad6d3
--- /dev/null
+++ b/test/components/joiners/test_branch_joiner.py
@@ -0,0 +1,35 @@
+# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
+#
+# SPDX-License-Identifier: Apache-2.0
+import pytest
+
+from haystack.components.joiners import BranchJoiner
+
+
+class TestBranchJoiner:
+ def test_one_value(self):
+ joiner = BranchJoiner(int)
+ output = joiner.run(value=[2])
+ assert output == {"value": 2}
+
+ def test_one_value_of_wrong_type(self):
+ # BranchJoiner does not type check the input
+ joiner = BranchJoiner(int)
+ output = joiner.run(value=["hello"])
+ assert output == {"value": "hello"}
+
+ def test_one_value_of_none_type(self):
+ # BranchJoiner does not type check the input
+ joiner = BranchJoiner(int)
+ output = joiner.run(value=[None])
+ assert output == {"value": None}
+
+ def test_more_values_of_expected_type(self):
+ joiner = BranchJoiner(int)
+ with pytest.raises(ValueError, match="BranchJoiner expects only one input, but 3 were received."):
+ joiner.run(value=[2, 3, 4])
+
+ def test_no_values(self):
+ joiner = BranchJoiner(int)
+ with pytest.raises(ValueError, match="BranchJoiner expects only one input, but 0 were received."):
+ joiner.run(value=[])
| diff --git a/docs/pydoc/config/joiners_api.yml b/docs/pydoc/config/joiners_api.yml
index 9cbf2b161c..ad6e89a52a 100644
--- a/docs/pydoc/config/joiners_api.yml
+++ b/docs/pydoc/config/joiners_api.yml
@@ -1,7 +1,7 @@
loaders:
- type: haystack_pydoc_tools.loaders.CustomPythonLoader
search_path: [../../../haystack/components/joiners]
- modules: ["document_joiner"]
+ modules: ["document_joiner", "branch"]
ignore_when_discovered: ["__init__"]
processors:
- type: filter
diff --git a/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml b/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml
new file mode 100644
index 0000000000..75893aa537
--- /dev/null
+++ b/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml
@@ -0,0 +1,14 @@
+---
+highlights: >
+ The `Multiplexer` component proved to be hard to explain and to understand. After reviewing its use cases, the documentation
+ was rewritten and the component was renamed to `BranchJoiner` to better explain its functionalities.
+upgrade:
+ - |
+ `BranchJoiner` has the very same interface as `Multiplexer`. To upgrade your code, just rename any occurrence
+ of `Multiplexer` to `BranchJoiner` and ajdust the imports accordingly.
+features:
+ - |
+ Add `BranchJoiner` to eventually replace `Multiplexer`
+deprecations:
+ - |
+ `Mulitplexer` is now deprecated.
| [
{
"components": [
{
"doc": "A component to join different branches of a pipeline into one single output.\n\n`BranchJoiner` receives multiple data connections of the same type from other components and passes the first\nvalue coming to its single output, possibly distributing it to various other co... | [
"test/components/joiners/test_branch_joiner.py::TestBranchJoiner::test_one_value",
"test/components/joiners/test_branch_joiner.py::TestBranchJoiner::test_one_value_of_wrong_type",
"test/components/joiners/test_branch_joiner.py::TestBranchJoiner::test_one_value_of_none_type",
"test/components/joiners/test_bran... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add BranchJoiner and deprecate Multiplexer
### Related Issues
- fixes n/a
### Proposed Changes:
Introduce `BranchJoiner` and deprecate the `Mulitplexer`
### How did you test it?
<!-- unit tests, integration tests, manual verification, instructions for manual tests -->
### Notes for the reviewer
<!-- E.g. point out section where the reviewer -->
### 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/joiners/branch.py]
(definition of BranchJoiner:)
class BranchJoiner:
"""A component to join different branches of a pipeline into one single output.
`BranchJoiner` receives multiple data connections of the same type from other components and passes the first
value coming to its single output, possibly distributing it to various other components.
`BranchJoiner` is fundamental to close loops in a pipeline, where the two branches it joins are the ones
coming from the previous component and one coming back from a loop. For example, `BranchJoiner` could be used
to send data to a component evaluating errors. `BranchJoiner` would receive two connections, one to get the
original data and another one to get modified data in case there was an error. In both cases, `BranchJoiner`
would send (or re-send in case of a loop) data to the component evaluating errors. See "Usage example" below.
Another use case with a need for `BranchJoiner` is to reconcile multiple branches coming out of a decision
or Classifier component. For example, in a RAG pipeline, there might be a "query language classifier" component
sending the query to different retrievers, selecting one specifically according to the detected language. After the
retrieval step the pipeline would ideally continue with a `PromptBuilder`, and since we don't know in advance the
language of the query, all the retrievers should be ideally connected to the single `PromptBuilder`. Since the
`PromptBuilder` won't accept more than one connection in input, we would connect all the retrievers to a
`BranchJoiner` component and reconcile them in a single output that can be connected to the `PromptBuilder`
downstream.
Usage example:
```python
import json
from typing import List
from haystack import Pipeline
from haystack.components.converters import OutputAdapter
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.joiners import BranchJoiner
from haystack.components.validators import JsonSchemaValidator
from haystack.dataclasses import ChatMessage
person_schema = {
"type": "object",
"properties": {
"first_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"},
"last_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"},
"nationality": {"type": "string", "enum": ["Italian", "Portuguese", "American"]},
},
"required": ["first_name", "last_name", "nationality"]
}
# Initialize a pipeline
pipe = Pipeline()
# Add components to the pipeline
pipe.add_component('joiner', BranchJoiner(List[ChatMessage]))
pipe.add_component('fc_llm', OpenAIChatGenerator(model="gpt-3.5-turbo-0125"))
pipe.add_component('validator', JsonSchemaValidator(json_schema=person_schema))
pipe.add_component('adapter', OutputAdapter("{{chat_message}}", List[ChatMessage])),
# And connect them
pipe.connect("adapter", "joiner")
pipe.connect("joiner", "fc_llm")
pipe.connect("fc_llm.replies", "validator.messages")
pipe.connect("validator.validation_error", "joiner")
result = pipe.run(data={"fc_llm": {"generation_kwargs": {"response_format": {"type": "json_object"}}},
"adapter": {"chat_message": [ChatMessage.from_user("Create json object from Peter Parker")]}})
print(json.loads(result["validator"]["validated"][0].content))
>> {'first_name': 'Peter', 'last_name': 'Parker', 'nationality': 'American', 'name': 'Spider-Man', 'occupation':
>> 'Superhero', 'age': 23, 'location': 'New York City'}
```
Note that `BranchJoiner` can manage only one data type at a time. In this case, `BranchJoiner` is created for passing
`List[ChatMessage]`. This determines the type of data that `BranchJoiner` will receive from the upstream connected
components and also the type of data that `BranchJoiner` will send through its output.
In the code example, `BranchJoiner` receives a looped back `List[ChatMessage]` from the `JsonSchemaValidator` and
sends it down to the `OpenAIChatGenerator` for re-generation. We can have multiple loopback connections in the
pipeline. In this instance, the downstream component is only one (the `OpenAIChatGenerator`), but the pipeline might
have more than one downstream component."""
(definition of BranchJoiner.__init__:)
def __init__(self, type_: Type):
"""Create a `BranchJoiner` component.
:param type_: The type of data that the `BranchJoiner` will receive from the upstream connected components and
distribute to the downstream connected components."""
(definition of BranchJoiner.to_dict:)
def to_dict(self):
"""Serializes the component to a dictionary.
:returns:
Dictionary with serialized data."""
(definition of BranchJoiner.from_dict:)
def from_dict(cls, data: Dict[str, Any]) -> "BranchJoiner":
"""Deserializes the component from a dictionary.
:param data:
Dictionary to deserialize from.
:returns:
Deserialized component."""
(definition of BranchJoiner.run:)
def run(self, **kwargs):
"""The run method of the `BranchJoiner` component.
Multiplexes the input data from the upstream connected components and distributes it to the downstream connected
components.
:param **kwargs: The input data. Must be of the type declared in `__init__`.
:return: A dictionary with the following keys:
- `value`: The input data."""
[end of new definitions in haystack/components/joiners/branch.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-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` encapsula... | [
"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_r... | [
"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_e... | 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 | |
googleapis__python-aiplatform-3840 | 3,840 | googleapis/python-aiplatform | null | 71fbc81df8fa0d7c863233abc3ed6d40666c1623 | 2024-05-28T21:42:18Z | diff --git a/google/cloud/aiplatform/persistent_resource.py b/google/cloud/aiplatform/persistent_resource.py
index 0bd6dbe404..f0944a5bb4 100644
--- a/google/cloud/aiplatform/persistent_resource.py
+++ b/google/cloud/aiplatform/persistent_resource.py
@@ -420,3 +420,34 @@ def list(
location=location,
credentials=credentials,
)
+
+ @base.optional_sync()
+ def reboot(
+ self,
+ sync: Optional[bool] = True, # pylint: disable=unused-argument
+ ) -> None:
+ """Reboots this Persistent Resource.
+
+ Args:
+ name (str):
+ Required. The name of the PersistentResource resource.
+ Name should be in the following format:
+ ``projects/{project_id_or_number}/locations/{location_id}/persistentResources/{persistent_resource_id}``
+
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ sync (bool):
+ Whether to execute this method synchonously. If False, this
+ method will be executed in concurrent Future and any downstream
+ object will be immediately returned and synced when the Future
+ has completed.
+ """
+
+ _LOGGER.log_action_start_against_resource("Rebooting", "", self)
+ lro = self.api_client.reboot_persistent_resource(name=self.resource_name)
+ _LOGGER.log_action_started_against_resource_with_lro(
+ "Reboot", "", self.__class__, lro
+ )
+ lro.result(timeout=None)
+ _LOGGER.log_action_completed_against_resource("rebooted.", "", self)
| diff --git a/tests/unit/aiplatform/test_persistent_resource.py b/tests/unit/aiplatform/test_persistent_resource.py
index 14421e9066..55c460b113 100644
--- a/tests/unit/aiplatform/test_persistent_resource.py
+++ b/tests/unit/aiplatform/test_persistent_resource.py
@@ -153,6 +153,20 @@ def delete_persistent_resource_mock():
yield delete_persistent_resource_mock
+@pytest.fixture
+def reboot_persistent_resource_mock():
+ with mock.patch.object(
+ (persistent_resource_service_client_v1.PersistentResourceServiceClient),
+ "reboot_persistent_resource",
+ ) as reboot_persistent_resource_mock:
+ reboot_lro = mock.Mock(ga_operation.Operation)
+ reboot_lro.result.return_value = (
+ persistent_resource_service_v1.RebootPersistentResourceRequest()
+ )
+ reboot_persistent_resource_mock.return_value = reboot_lro
+ yield reboot_persistent_resource_mock
+
+
@pytest.mark.usefixtures("google_auth_mock")
class TestPersistentResource:
def setup_method(self):
@@ -359,3 +373,23 @@ def test_delete_persistent_resource(
delete_persistent_resource_mock.assert_called_once_with(
name=_TEST_PERSISTENT_RESOURCE_ID,
)
+
+ @pytest.mark.parametrize("sync", [True, False])
+ def test_reboot_persistent_resource(
+ self,
+ get_persistent_resource_mock,
+ reboot_persistent_resource_mock,
+ sync,
+ ):
+ test_resource = persistent_resource.PersistentResource(
+ _TEST_PERSISTENT_RESOURCE_ID
+ )
+ test_resource.reboot(sync=sync)
+
+ if not sync:
+ test_resource.wait()
+
+ get_persistent_resource_mock.assert_called_once()
+ reboot_persistent_resource_mock.assert_called_once_with(
+ name=_TEST_PERSISTENT_RESOURCE_ID,
+ )
| [
{
"components": [
{
"doc": "Reboots this Persistent Resource.\n\nArgs:\n name (str):\n Required. The name of the PersistentResource resource.\n Name should be in the following format:\n ``projects/{project_id_or_number}/locations/{location_id}/persistentResources/{persisten... | [
"tests/unit/aiplatform/test_persistent_resource.py::TestPersistentResource::test_reboot_persistent_resource[True]",
"tests/unit/aiplatform/test_persistent_resource.py::TestPersistentResource::test_reboot_persistent_resource[False]"
] | [
"tests/unit/aiplatform/test_persistent_resource.py::TestPersistentResource::test_create_persistent_resource[True]",
"tests/unit/aiplatform/test_persistent_resource.py::TestPersistentResource::test_create_persistent_resource[False]",
"tests/unit/aiplatform/test_persistent_resource.py::TestPersistentResource::tes... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Added reboot command for PersistentResource
feat: Added reboot command for PersistentResource
----------
</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 google/cloud/aiplatform/persistent_resource.py]
(definition of PersistentResource.reboot:)
def reboot( self, sync: Optional[bool] = True,
"""Reboots this Persistent Resource.
Args:
name (str):
Required. The name of the PersistentResource resource.
Name should be in the following format:
``projects/{project_id_or_number}/locations/{location_id}/persistentResources/{persistent_resource_id}``
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
sync (bool):
Whether to execute this method synchonously. If False, this
method will be executed in concurrent Future and any downstream
object will be immediately returned and synced when the Future
has completed."""
[end of new definitions in google/cloud/aiplatform/persistent_resource.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 | ||
pvlib__pvlib-python-2072 | 2,072 | pvlib/pvlib-python | 0.10 | 1f361607037a1c9883de01d559ddfbf870f578bf | 2024-05-28T21:29:44Z | diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index fde3b170a9..56d7a6df15 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -13,5 +13,6 @@ Spectrum
spectrum.spectral_factor_caballero
spectrum.spectral_factor_firstsolar
spectrum.spectral_factor_sapm
+ spectrum.spectral_factor_pvspec
spectrum.sr_to_qe
spectrum.qe_to_sr
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 14694d0fc4..9d36af22e3 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -32,7 +32,9 @@ Enhancements
efficiency ([unitless]) and vice versa. The conversion functions are
:py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
respectively. (:issue:`2040`, :pull:`2041`)
-
+* Add function :py:func:`pvlib.spectrum.spectral_factor_pvspec`, which calculates the
+ spectral mismatch factor as a function of absolute airmass and clearsky index
+ using the PVSPEC model. (:issue:`1950`, :issue:`2065`, :pull:`2072`)
Bug fixes
~~~~~~~~~
@@ -56,3 +58,4 @@ Contributors
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
* Mark Campanelli (:ghuser:`markcampanelli`)
+* Rajiv Daxini (:ghuser:`RDaxini`)
diff --git a/pvlib/spectrum/__init__.py b/pvlib/spectrum/__init__.py
index 0b9f7b03e9..cda7202689 100644
--- a/pvlib/spectrum/__init__.py
+++ b/pvlib/spectrum/__init__.py
@@ -6,6 +6,7 @@
spectral_factor_caballero,
spectral_factor_firstsolar,
spectral_factor_sapm,
+ spectral_factor_pvspec,
sr_to_qe,
- qe_to_sr,
+ qe_to_sr
)
diff --git a/pvlib/spectrum/mismatch.py b/pvlib/spectrum/mismatch.py
index e3f434f99c..7c70a35360 100644
--- a/pvlib/spectrum/mismatch.py
+++ b/pvlib/spectrum/mismatch.py
@@ -54,14 +54,14 @@ def get_example_spectral_response(wavelength=None):
'''
# Contributed by Anton Driesse (@adriesse), PV Performance Labs. Aug. 2022
- SR_DATA = np.array([[ 290, 0.00],
- [ 350, 0.27],
- [ 400, 0.37],
- [ 500, 0.52],
- [ 650, 0.71],
- [ 800, 0.88],
- [ 900, 0.97],
- [ 950, 1.00],
+ SR_DATA = np.array([[290, 0.00],
+ [350, 0.27],
+ [400, 0.37],
+ [500, 0.52],
+ [650, 0.71],
+ [800, 0.88],
+ [900, 0.97],
+ [950, 1.00],
[1000, 0.93],
[1050, 0.58],
[1100, 0.21],
@@ -256,7 +256,7 @@ def spectral_factor_firstsolar(precipitable_water, airmass_absolute,
max_precipitable_water=8):
r"""
Spectral mismatch modifier based on precipitable water and absolute
- (pressure-adjusted) airmass.
+ (pressure-adjusted) air mass.
Estimates a spectral mismatch modifier :math:`M` representing the effect on
module short circuit current of variation in the spectral
@@ -294,7 +294,7 @@ def spectral_factor_firstsolar(precipitable_water, airmass_absolute,
atmospheric precipitable water. [cm]
airmass_absolute : numeric
- absolute (pressure-adjusted) airmass. [unitless]
+ absolute (pressure-adjusted) air mass. [unitless]
module_type : str, optional
a string specifying a cell type. Values of 'cdte', 'monosi', 'xsi',
@@ -583,6 +583,112 @@ def spectral_factor_caballero(precipitable_water, airmass_absolute, aod500,
return modifier
+def spectral_factor_pvspec(airmass_absolute, clearsky_index,
+ module_type=None, coefficients=None):
+ r"""
+ Estimate a technology-specific spectral mismatch modifier from absolute
+ airmass and clear sky index using the PVSPEC model.
+
+ The PVSPEC spectral mismatch model includes the effects of cloud cover on
+ the irradiance spectrum. Model coefficients are derived using spectral
+ irradiance and other meteorological data from eight locations. Coefficients
+ for six module types are available via the ``module_type`` parameter.
+ More details on the model can be found in [1]_.
+
+ Parameters
+ ----------
+ airmass_absolute : numeric
+ absolute (pressure-adjusted) airmass. [unitless]
+
+ clearsky_index: numeric
+ clear sky index. [unitless]
+
+ module_type : str, optional
+ One of the following PV technology strings from [1]_:
+
+ * ``'fs4-1'`` - First Solar series 4-1 and earlier CdTe module.
+ * ``'fs4-2'`` - First Solar 4-2 and later CdTe module.
+ * ``'monosi'``, - anonymous monocrystalline Si module.
+ * ``'multisi'``, - anonymous multicrystalline Si module.
+ * ``'cigs'`` - anonymous copper indium gallium selenide module.
+ * ``'asi'`` - anonymous amorphous silicon module.
+
+ coefficients : array-like, optional
+ user-defined coefficients, if not using one of the default coefficient
+ sets via the ``module_type`` parameter.
+
+ Returns
+ -------
+ mismatch: numeric
+ spectral mismatch factor (unitless) which is multiplied
+ with broadband irradiance reaching a module's cells to estimate
+ effective irradiance, i.e., the irradiance that is converted to
+ electrical current.
+
+ Notes
+ -----
+ The PVSPEC model parameterises the spectral mismatch factor as a function
+ of absolute air mass and the clear sky index as follows:
+
+ .. math::
+
+ M = a_1 k_c^{a_2} AM_a^{a_3},
+
+ where :math:`M` is the spectral mismatch factor, :math:`k_c` is the clear
+ sky index, :math:`AM_a` is the absolute air mass, and :math:`a_1, a_2, a_3`
+ are module-specific coefficients. In the PVSPEC model publication, absolute
+ air mass (denoted as :math:`AM`) is estimated starting from the Kasten and
+ Young relative air mass [2]_. The clear sky index, which is the ratio of
+ GHI to clear sky GHI, uses the ESRA model [3]_ to estimate the clear sky
+ GHI with monthly Linke turbidity values from [4]_ as inputs.
+
+ References
+ ----------
+ .. [1] Pelland, S., Beswick, C., Thevenard, D., Côté, A., Pai, A. and
+ Poissant, Y., 2020. Development and testing of the PVSPEC model of
+ photovoltaic spectral mismatch factor. In 2020 47th IEEE Photovoltaic
+ Specialists Conference (PVSC) (pp. 1258-1264). IEEE.
+ :doi:`10.1109/PVSC45281.2020.9300932`
+ .. [2] Kasten, F. and Young, A.T., 1989. Revised optical air mass tables
+ and approximation formula. Applied Optics, 28(22), pp.4735-4738.
+ :doi:`10.1364/AO.28.004735`
+ .. [3] Rigollier, C., Bauer, O. and Wald, L., 2000. On the clear sky model
+ of the ESRA—European Solar Radiation Atlas—with respect to the Heliosat
+ method. Solar energy, 68(1), pp.33-48.
+ :doi:`10.1016/S0038-092X(99)00055-9`
+ .. [4] SoDa website monthly Linke turbidity values:
+ http://www.soda-pro.com/
+ """
+
+ _coefficients = {}
+ _coefficients['multisi'] = (0.9847, -0.05237, 0.03034)
+ _coefficients['monosi'] = (0.9845, -0.05169, 0.03034)
+ _coefficients['fs-2'] = (1.002, -0.07108, 0.02465)
+ _coefficients['fs-4'] = (0.9981, -0.05776, 0.02336)
+ _coefficients['cigs'] = (0.9791, -0.03904, 0.03096)
+ _coefficients['asi'] = (1.051, -0.1033, 0.009838)
+
+ if module_type is not None and coefficients is None:
+ coefficients = _coefficients[module_type.lower()]
+ elif module_type is None and coefficients is not None:
+ pass
+ elif module_type is None and coefficients is None:
+ raise ValueError('No valid input provided, both module_type and ' +
+ 'coefficients are None. module_type can be one of ' +
+ ", ".join(_coefficients.keys()))
+ else:
+ raise ValueError('Cannot resolve input, must supply only one of ' +
+ 'module_type and coefficients. module_type can be ' +
+ 'one of' ", ".join(_coefficients.keys()))
+
+ coeff = coefficients
+ ama = airmass_absolute
+ kc = clearsky_index
+ mismatch = coeff[0]*np.power(kc, coeff[1])*np.power(ama, coeff[2])
+
+ return mismatch
+
+
def sr_to_qe(sr, wavelength=None, normalize=False):
"""
Convert spectral responsivities to quantum efficiencies.
| diff --git a/pvlib/tests/test_spectrum.py b/pvlib/tests/test_spectrum.py
index 7b86cb713e..6b1dcd4506 100644
--- a/pvlib/tests/test_spectrum.py
+++ b/pvlib/tests/test_spectrum.py
@@ -8,6 +8,7 @@
SPECTRL2_TEST_DATA = DATA_DIR / 'spectrl2_example_spectra.csv'
+
@pytest.fixture
def spectrl2_data():
# reference spectra generated with solar_utils==0.3
@@ -175,25 +176,25 @@ def test_calc_spectral_mismatch_field(spectrl2_data):
@pytest.mark.parametrize("module_type,expect", [
('cdte', np.array(
- [[ 0.99051020, 0.97640320, 0.93975028],
- [ 1.02928735, 1.01881074, 0.98578821],
- [ 1.04750335, 1.03814456, 1.00623986]])),
+ [[0.99051020, 0.97640320, 0.93975028],
+ [1.02928735, 1.01881074, 0.98578821],
+ [1.04750335, 1.03814456, 1.00623986]])),
('monosi', np.array(
- [[ 0.97769770, 1.02043409, 1.03574032],
- [ 0.98630905, 1.03055092, 1.04736262],
- [ 0.98828494, 1.03299036, 1.05026561]])),
+ [[0.97769770, 1.02043409, 1.03574032],
+ [0.98630905, 1.03055092, 1.04736262],
+ [0.98828494, 1.03299036, 1.05026561]])),
('polysi', np.array(
- [[ 0.97704080, 1.01705849, 1.02613202],
- [ 0.98992828, 1.03173953, 1.04260662],
- [ 0.99352435, 1.03588785, 1.04730718]])),
+ [[0.97704080, 1.01705849, 1.02613202],
+ [0.98992828, 1.03173953, 1.04260662],
+ [0.99352435, 1.03588785, 1.04730718]])),
('cigs', np.array(
- [[ 0.97459190, 1.02821696, 1.05067895],
- [ 0.97529378, 1.02967497, 1.05289307],
- [ 0.97269159, 1.02730558, 1.05075651]])),
+ [[0.97459190, 1.02821696, 1.05067895],
+ [0.97529378, 1.02967497, 1.05289307],
+ [0.97269159, 1.02730558, 1.05075651]])),
('asi', np.array(
- [[ 1.05552750, 0.87707583, 0.72243772],
- [ 1.11225204, 0.93665901, 0.78487953],
- [ 1.14555295, 0.97084011, 0.81994083]]))
+ [[1.05552750, 0.87707583, 0.72243772],
+ [1.11225204, 0.93665901, 0.78487953],
+ [1.14555295, 0.97084011, 0.81994083]]))
])
def test_spectral_factor_firstsolar(module_type, expect):
ams = np.array([1, 3, 5])
@@ -317,6 +318,62 @@ def test_spectral_factor_caballero_supplied_ambiguous():
coefficients=None)
+@pytest.mark.parametrize("module_type,expected", [
+ ('asi', np.array([1.15534029, 1.1123772, 1.08286684, 1.01915462])),
+ ('fs-2', np.array([1.0694323, 1.04948777, 1.03556288, 0.9881471])),
+ ('fs-4', np.array([1.05234725, 1.037771, 1.0275516, 0.98820533])),
+ ('multisi', np.array([1.03310403, 1.02391703, 1.01744833, 0.97947605])),
+ ('monosi', np.array([1.03225083, 1.02335353, 1.01708734, 0.97950110])),
+ ('cigs', np.array([1.01475834, 1.01143927, 1.00909094, 0.97852966])),
+])
+def test_spectral_factor_pvspec(module_type, expected):
+ ams = np.array([1.0, 1.5, 2.0, 1.5])
+ kcs = np.array([0.4, 0.6, 0.8, 1.4])
+ out = spectrum.spectral_factor_pvspec(ams, kcs,
+ module_type=module_type)
+ assert np.allclose(expected, out, atol=1e-8)
+
+
+@pytest.mark.parametrize("module_type,expected", [
+ ('asi', pd.Series([1.15534029, 1.1123772, 1.08286684, 1.01915462])),
+ ('fs-2', pd.Series([1.0694323, 1.04948777, 1.03556288, 0.9881471])),
+ ('fs-4', pd.Series([1.05234725, 1.037771, 1.0275516, 0.98820533])),
+ ('multisi', pd.Series([1.03310403, 1.02391703, 1.01744833, 0.97947605])),
+ ('monosi', pd.Series([1.03225083, 1.02335353, 1.01708734, 0.97950110])),
+ ('cigs', pd.Series([1.01475834, 1.01143927, 1.00909094, 0.97852966])),
+])
+def test_spectral_factor_pvspec_series(module_type, expected):
+ ams = pd.Series([1.0, 1.5, 2.0, 1.5])
+ kcs = pd.Series([0.4, 0.6, 0.8, 1.4])
+ out = spectrum.spectral_factor_pvspec(ams, kcs,
+ module_type=module_type)
+ assert isinstance(out, pd.Series)
+ assert np.allclose(expected, out, atol=1e-8)
+
+
+def test_spectral_factor_pvspec_supplied():
+ # use the multisi coeffs
+ coeffs = (0.9847, -0.05237, 0.03034)
+ out = spectrum.spectral_factor_pvspec(1.5, 0.8, coefficients=coeffs)
+ expected = 1.00860641
+ assert_allclose(out, expected, atol=1e-8)
+
+
+def test_spectral_factor_pvspec_supplied_redundant():
+ # Error when specifying both module_type and coefficients
+ coeffs = (0.9847, -0.05237, 0.03034)
+ with pytest.raises(ValueError, match='supply only one of'):
+ spectrum.spectral_factor_pvspec(1.5, 0.8, module_type='multisi',
+ coefficients=coeffs)
+
+
+def test_spectral_factor_pvspec_supplied_ambiguous():
+ # Error when specifying neither module_type nor coefficients
+ with pytest.raises(ValueError, match='No valid input provided'):
+ spectrum.spectral_factor_pvspec(1.5, 0.8, module_type=None,
+ coefficients=None)
+
+
@pytest.fixture
def sr_and_eqe_fixture():
# Just some arbitrary data for testing the conversion functions
| diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index fde3b170a9..56d7a6df15 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -13,5 +13,6 @@ Spectrum
spectrum.spectral_factor_caballero
spectrum.spectral_factor_firstsolar
spectrum.spectral_factor_sapm
+ spectrum.spectral_factor_pvspec
spectrum.sr_to_qe
spectrum.qe_to_sr
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 14694d0fc4..9d36af22e3 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -32,7 +32,9 @@ Enhancements
efficiency ([unitless]) and vice versa. The conversion functions are
:py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
respectively. (:issue:`2040`, :pull:`2041`)
-
+* Add function :py:func:`pvlib.spectrum.spectral_factor_pvspec`, which calculates the
+ spectral mismatch factor as a function of absolute airmass and clearsky index
+ using the PVSPEC model. (:issue:`1950`, :issue:`2065`, :pull:`2072`)
Bug fixes
~~~~~~~~~
@@ -56,3 +58,4 @@ Contributors
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
* Mark Campanelli (:ghuser:`markcampanelli`)
+* Rajiv Daxini (:ghuser:`RDaxini`)
| [
{
"components": [
{
"doc": "Estimate a technology-specific spectral mismatch modifier from absolute\nairmass and clear sky index using the PVSPEC model.\n\nThe PVSPEC spectral mismatch model includes the effects of cloud cover on\nthe irradiance spectrum. Model coefficients are derived using spect... | [
"pvlib/tests/test_spectrum.py::test_spectral_factor_pvspec[asi-expected0]",
"pvlib/tests/test_spectrum.py::test_spectral_factor_pvspec[fs-2-expected1]",
"pvlib/tests/test_spectrum.py::test_spectral_factor_pvspec[fs-4-expected2]",
"pvlib/tests/test_spectrum.py::test_spectral_factor_pvspec[multisi-expected3]",
... | [
"pvlib/tests/test_spectrum.py::test_spectrl2",
"pvlib/tests/test_spectrum.py::test_spectrl2_array",
"pvlib/tests/test_spectrum.py::test_spectrl2_series",
"pvlib/tests/test_spectrum.py::test_dayofyear_missing",
"pvlib/tests/test_spectrum.py::test_aoi_gt_90",
"pvlib/tests/test_spectrum.py::test_get_example_... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add PVSPEC spectral correction factor model
- [X] Closes (partially addresses #1950 and #2065)
- [X] I am familiar with the [contributing guidelines](https://pvlib-python.readthedocs.io/en/latest/contributing.html)
- [X] Tests added
- [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.
[This model](https://ieeexplore.ieee.org/document/9300932) is one of the spectral correction functions suggested in the cited issues (#1950 and #2065).
Docs: https://pvlib-python--2072.org.readthedocs.build/en/2072/reference/generated/pvlib.spectrum.spectral_factor_pvspec.html
----------
</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/spectrum/mismatch.py]
(definition of spectral_factor_pvspec:)
def spectral_factor_pvspec(airmass_absolute, clearsky_index, module_type=None, coefficients=None):
"""Estimate a technology-specific spectral mismatch modifier from absolute
airmass and clear sky index using the PVSPEC model.
The PVSPEC spectral mismatch model includes the effects of cloud cover on
the irradiance spectrum. Model coefficients are derived using spectral
irradiance and other meteorological data from eight locations. Coefficients
for six module types are available via the ``module_type`` parameter.
More details on the model can be found in [1]_.
Parameters
----------
airmass_absolute : numeric
absolute (pressure-adjusted) airmass. [unitless]
clearsky_index: numeric
clear sky index. [unitless]
module_type : str, optional
One of the following PV technology strings from [1]_:
* ``'fs4-1'`` - First Solar series 4-1 and earlier CdTe module.
* ``'fs4-2'`` - First Solar 4-2 and later CdTe module.
* ``'monosi'``, - anonymous monocrystalline Si module.
* ``'multisi'``, - anonymous multicrystalline Si module.
* ``'cigs'`` - anonymous copper indium gallium selenide module.
* ``'asi'`` - anonymous amorphous silicon module.
coefficients : array-like, optional
user-defined coefficients, if not using one of the default coefficient
sets via the ``module_type`` parameter.
Returns
-------
mismatch: numeric
spectral mismatch factor (unitless) which is multiplied
with broadband irradiance reaching a module's cells to estimate
effective irradiance, i.e., the irradiance that is converted to
electrical current.
Notes
-----
The PVSPEC model parameterises the spectral mismatch factor as a function
of absolute air mass and the clear sky index as follows:
.. math::
M = a_1 k_c^{a_2} AM_a^{a_3},
where :math:`M` is the spectral mismatch factor, :math:`k_c` is the clear
sky index, :math:`AM_a` is the absolute air mass, and :math:`a_1, a_2, a_3`
are module-specific coefficients. In the PVSPEC model publication, absolute
air mass (denoted as :math:`AM`) is estimated starting from the Kasten and
Young relative air mass [2]_. The clear sky index, which is the ratio of
GHI to clear sky GHI, uses the ESRA model [3]_ to estimate the clear sky
GHI with monthly Linke turbidity values from [4]_ as inputs.
References
----------
.. [1] Pelland, S., Beswick, C., Thevenard, D., Côté, A., Pai, A. and
Poissant, Y., 2020. Development and testing of the PVSPEC model of
photovoltaic spectral mismatch factor. In 2020 47th IEEE Photovoltaic
Specialists Conference (PVSC) (pp. 1258-1264). IEEE.
:doi:`10.1109/PVSC45281.2020.9300932`
.. [2] Kasten, F. and Young, A.T., 1989. Revised optical air mass tables
and approximation formula. Applied Optics, 28(22), pp.4735-4738.
:doi:`10.1364/AO.28.004735`
.. [3] Rigollier, C., Bauer, O. and Wald, L., 2000. On the clear sky model
of the ESRA—European Solar Radiation Atlas—with respect to the Heliosat
method. Solar energy, 68(1), pp.33-48.
:doi:`10.1016/S0038-092X(99)00055-9`
.. [4] SoDa website monthly Linke turbidity values:
http://www.soda-pro.com/"""
[end of new definitions in pvlib/spectrum/mismatch.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>> | 6af80da35a7c96059c534ee38be9123bcfc7f50f | |
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")})
| [] | [
"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... | 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>
</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... | [
"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/util... | [] | 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 | ||
roboflow__supervision-1236 | 1,236 | roboflow/supervision | null | 9bc2907c4907714da5b469fdfee7800f4cf9f09e | 2024-05-28T06:56:15Z | diff --git a/docs/detection/double_detection_filter.md b/docs/detection/double_detection_filter.md
new file mode 100644
index 000000000..1631852f4
--- /dev/null
+++ b/docs/detection/double_detection_filter.md
@@ -0,0 +1,30 @@
+---
+comments: true
+status: new
+---
+
+# Double Detection Filter
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.OverlapFilter">OverlapFilter</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.OverlapFilter
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.box_non_max_suppression">box_non_max_suppression</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.box_non_max_suppression
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.mask_non_max_suppression">mask_non_max_suppression</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.mask_non_max_suppression
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.box_non_max_merge">box_non_max_merge</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.box_non_max_merge
diff --git a/docs/detection/utils.md b/docs/detection/utils.md
index f9c9473bc..369746a3e 100644
--- a/docs/detection/utils.md
+++ b/docs/detection/utils.md
@@ -17,18 +17,6 @@ status: new
:::supervision.detection.utils.mask_iou_batch
-<div class="md-typeset">
- <h2><a href="#supervision.detection.utils.box_non_max_suppression">box_non_max_suppression</a></h2>
-</div>
-
-:::supervision.detection.utils.box_non_max_suppression
-
-<div class="md-typeset">
- <h2><a href="#supervision.detection.utils.mask_non_max_suppression">mask_non_max_suppression</a></h2>
-</div>
-
-:::supervision.detection.utils.mask_non_max_suppression
-
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.polygon_to_mask">polygon_to_mask</a></h2>
</div>
diff --git a/mkdocs.yml b/mkdocs.yml
index f257238df..19d6a4fd4 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -48,6 +48,7 @@ nav:
- Core: detection/core.md
- Annotators: detection/annotators.md
- Metrics: detection/metrics.md
+ - Double Detection Filter: detection/double_detection_filter.md
- Utils: detection/utils.md
- Keypoint Detection:
- Core: keypoint/core.md
diff --git a/supervision/__init__.py b/supervision/__init__.py
index 1a46226fd..4f28d49f4 100644
--- a/supervision/__init__.py
+++ b/supervision/__init__.py
@@ -40,6 +40,12 @@
from supervision.detection.core import Detections
from supervision.detection.line_zone import LineZone, LineZoneAnnotator
from supervision.detection.lmm import LMM
+from supervision.detection.overlap_filter import (
+ OverlapFilter,
+ box_non_max_merge,
+ box_non_max_suppression,
+ mask_non_max_suppression,
+)
from supervision.detection.tools.csv_sink import CSVSink
from supervision.detection.tools.inference_slicer import InferenceSlicer
from supervision.detection.tools.json_sink import JSONSink
@@ -47,15 +53,12 @@
from supervision.detection.tools.smoother import DetectionsSmoother
from supervision.detection.utils import (
box_iou_batch,
- box_non_max_merge,
- box_non_max_suppression,
calculate_masks_centroids,
clip_boxes,
contains_holes,
contains_multiple_segments,
filter_polygons_by_area,
mask_iou_batch,
- mask_non_max_suppression,
mask_to_polygons,
mask_to_xyxy,
move_boxes,
diff --git a/supervision/detection/core.py b/supervision/detection/core.py
index be6104820..c47bc8197 100644
--- a/supervision/detection/core.py
+++ b/supervision/detection/core.py
@@ -8,15 +8,17 @@
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.utils import (
- box_iou_batch,
+from supervision.detection.overlap_filter import (
box_non_max_merge,
box_non_max_suppression,
+ mask_non_max_suppression,
+)
+from supervision.detection.utils import (
+ box_iou_batch,
calculate_masks_centroids,
extract_ultralytics_masks,
get_data_item,
is_data_equal,
- mask_non_max_suppression,
mask_to_xyxy,
merge_data,
process_roboflow_result,
diff --git a/supervision/detection/overlap_filter.py b/supervision/detection/overlap_filter.py
new file mode 100644
index 000000000..ab4408d18
--- /dev/null
+++ b/supervision/detection/overlap_filter.py
@@ -0,0 +1,263 @@
+from enum import Enum
+from typing import List, Union
+
+import numpy as np
+import numpy.typing as npt
+
+from supervision.detection.utils import box_iou_batch, mask_iou_batch
+
+
+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:
+ """
+ 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`.
+ """
+ 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
+
+ # add column #5 - category filled with zeros for agnostic nms
+ if columns == 5:
+ predictions = np.c_[predictions, np.zeros(rows)]
+
+ # sort predictions column #4 - score
+ sort_index = np.flip(predictions[:, 4].argsort())
+ predictions = predictions[sort_index]
+
+ boxes = predictions[:, :4]
+ categories = predictions[:, 5]
+ ious = box_iou_batch(boxes, boxes)
+ ious = ious - np.eye(rows)
+
+ keep = np.ones(rows, dtype=bool)
+
+ for index, (iou, category) in enumerate(zip(ious, categories)):
+ if not keep[index]:
+ continue
+
+ # drop detections with iou > iou_threshold and
+ # same category as current detections
+ condition = (iou > iou_threshold) & (categories == category)
+ keep = keep & ~condition
+
+ return keep[sort_index.argsort()]
+
+
+def group_overlapping_boxes(
+ predictions: npt.NDArray[np.float64], iou_threshold: float = 0.5
+) -> List[List[int]]:
+ """
+ Apply greedy version of non-maximum merging to avoid detecting too many
+ overlapping bounding boxes for a given object.
+
+ Args:
+ predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` containing
+ the bounding boxes coordinates in format `[x1, y1, x2, y2]`
+ and the confidence scores.
+ iou_threshold (float, optional): The intersection-over-union threshold
+ to use for non-maximum suppression. Defaults to 0.5.
+
+ Returns:
+ List[List[int]]: Groups of prediction indices be merged.
+ Each group may have 1 or more elements.
+ """
+ merge_groups: List[List[int]] = []
+
+ scores = predictions[:, 4]
+ order = scores.argsort()
+
+ while len(order) > 0:
+ idx = int(order[-1])
+
+ order = order[:-1]
+ if len(order) == 0:
+ merge_groups.append([idx])
+ break
+
+ merge_candidate = np.expand_dims(predictions[idx], axis=0)
+ ious = box_iou_batch(predictions[order][:, :4], merge_candidate[:, :4])
+ ious = ious.flatten()
+
+ above_threshold = ious >= iou_threshold
+ merge_group = [idx] + np.flip(order[above_threshold]).tolist()
+ merge_groups.append(merge_group)
+ order = order[~above_threshold]
+ return merge_groups
+
+
+def box_non_max_merge(
+ predictions: npt.NDArray[np.float64],
+ iou_threshold: float = 0.5,
+) -> List[List[int]]:
+ """
+ Apply greedy version of non-maximum merging per category to avoid detecting
+ too many overlapping bounding boxes for a given object.
+
+ Args:
+ predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` or `(n, 6)`
+ containing the bounding boxes coordinates in format `[x1, y1, x2, y2]`,
+ the confidence scores and class_ids. Omit class_id column to allow
+ detections of different classes to be merged.
+ iou_threshold (float, optional): The intersection-over-union threshold
+ to use for non-maximum suppression. Defaults to 0.5.
+
+ Returns:
+ List[List[int]]: Groups of prediction indices be merged.
+ Each group may have 1 or more elements.
+ """
+ if predictions.shape[1] == 5:
+ return group_overlapping_boxes(predictions, iou_threshold)
+
+ category_ids = predictions[:, 5]
+ merge_groups = []
+ for category_id in np.unique(category_ids):
+ curr_indices = np.where(category_ids == category_id)[0]
+ merge_class_groups = group_overlapping_boxes(
+ predictions[curr_indices], iou_threshold
+ )
+
+ for merge_class_group in merge_class_groups:
+ merge_groups.append(curr_indices[merge_class_group].tolist())
+
+ for merge_group in merge_groups:
+ if len(merge_group) == 0:
+ raise ValueError(
+ f"Empty group detected when non-max-merging "
+ f"detections: {merge_groups}"
+ )
+ return merge_groups
+
+
+class OverlapFilter(Enum):
+ """
+ Enum specifying the strategy for filtering overlapping detections.
+
+ Attributes:
+ NONE: Do not filter detections based on overlap.
+ NON_MAX_SUPPRESSION: Filter detections using non-max suppression. This means,
+ detections that overlap by more than a set threshold will be discarded,
+ except for the one with the highest confidence.
+ NON_MAX_MERGE: Merge detections with non-max merging. This means,
+ detections that overlap by more than a set threshold will be merged
+ into a single detection.
+ """
+
+ NONE = "none"
+ NON_MAX_SUPPRESSION = "non_max_suppression"
+ NON_MAX_MERGE = "non_max_merge"
+
+
+def validate_overlap_filter(
+ strategy: Union[OverlapFilter, str],
+) -> OverlapFilter:
+ if isinstance(strategy, str):
+ try:
+ strategy = OverlapFilter(strategy.lower())
+ except ValueError:
+ raise ValueError(
+ f"Invalid strategy value: {strategy}. Must be one of "
+ f"{[e.value for e in OverlapFilter]}"
+ )
+ return strategy
diff --git a/supervision/detection/tools/inference_slicer.py b/supervision/detection/tools/inference_slicer.py
index 82551434e..134361bd3 100644
--- a/supervision/detection/tools/inference_slicer.py
+++ b/supervision/detection/tools/inference_slicer.py
@@ -1,11 +1,14 @@
+import warnings
from concurrent.futures import ThreadPoolExecutor, as_completed
-from typing import Callable, Optional, Tuple
+from typing import Callable, Optional, Tuple, Union
import numpy as np
from supervision.detection.core import Detections
+from supervision.detection.overlap_filter import OverlapFilter, validate_overlap_filter
from supervision.detection.utils import move_boxes, move_masks
from supervision.utils.image import crop_image
+from supervision.utils.internal import SupervisionWarnings
def move_detections(
@@ -50,8 +53,10 @@ class InferenceSlicer:
`(width, height)`.
overlap_ratio_wh (Tuple[float, float]): Overlap ratio between consecutive
slices in the format `(width_ratio, height_ratio)`.
- iou_threshold (Optional[float]): Intersection over Union (IoU) threshold
- used for non-max suppression.
+ overlap_filter_strategy (Union[OverlapFilter, str]): Strategy for
+ filtering or merging overlapping detections in slices.
+ iou_threshold (float): Intersection over Union (IoU) threshold
+ used when filtering by overlap.
callback (Callable): A function that performs inference on a given image
slice and returns detections.
thread_workers (int): Number of threads for parallel execution.
@@ -68,12 +73,18 @@ def __init__(
callback: Callable[[np.ndarray], Detections],
slice_wh: Tuple[int, int] = (320, 320),
overlap_ratio_wh: Tuple[float, float] = (0.2, 0.2),
- iou_threshold: Optional[float] = 0.5,
+ overlap_filter_strategy: Union[
+ OverlapFilter, str
+ ] = OverlapFilter.NON_MAX_SUPPRESSION,
+ iou_threshold: float = 0.5,
thread_workers: int = 1,
):
+ overlap_filter_strategy = validate_overlap_filter(overlap_filter_strategy)
+
self.slice_wh = slice_wh
self.overlap_ratio_wh = overlap_ratio_wh
self.iou_threshold = iou_threshold
+ self.overlap_filter_strategy = overlap_filter_strategy
self.callback = callback
self.thread_workers = thread_workers
@@ -104,7 +115,10 @@ def callback(image_slice: np.ndarray) -> sv.Detections:
result = model(image_slice)[0]
return sv.Detections.from_ultralytics(result)
- slicer = sv.InferenceSlicer(callback = callback)
+ slicer = sv.InferenceSlicer(
+ callback=callback,
+ overlap_filter_strategy=sv.OverlapFilter.NON_MAX_SUPPRESSION,
+ )
detections = slicer(image)
```
@@ -124,9 +138,19 @@ def callback(image_slice: np.ndarray) -> sv.Detections:
for future in as_completed(futures):
detections_list.append(future.result())
- return Detections.merge(detections_list=detections_list).with_nms(
- threshold=self.iou_threshold
- )
+ merged = Detections.merge(detections_list=detections_list)
+ if self.overlap_filter_strategy == OverlapFilter.NONE:
+ return merged
+ elif self.overlap_filter_strategy == OverlapFilter.NON_MAX_SUPPRESSION:
+ return merged.with_nms(threshold=self.iou_threshold)
+ elif self.overlap_filter_strategy == OverlapFilter.NON_MAX_MERGE:
+ return merged.with_nmm(threshold=self.iou_threshold)
+ else:
+ warnings.warn(
+ f"Invalid overlap filter strategy: {self.overlap_filter_strategy}",
+ category=SupervisionWarnings,
+ )
+ return merged
def _run_callback(self, image, offset) -> Detections:
"""
diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py
index 1ca487916..b36b6853f 100644
--- a/supervision/detection/utils.py
+++ b/supervision/detection/utils.py
@@ -139,229 +139,6 @@ def mask_iou_batch(
return np.vstack(ious)
-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:
- """
- 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`.
- """
- 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
-
- # add column #5 - category filled with zeros for agnostic nms
- if columns == 5:
- predictions = np.c_[predictions, np.zeros(rows)]
-
- # sort predictions column #4 - score
- sort_index = np.flip(predictions[:, 4].argsort())
- predictions = predictions[sort_index]
-
- boxes = predictions[:, :4]
- categories = predictions[:, 5]
- ious = box_iou_batch(boxes, boxes)
- ious = ious - np.eye(rows)
-
- keep = np.ones(rows, dtype=bool)
-
- for index, (iou, category) in enumerate(zip(ious, categories)):
- if not keep[index]:
- continue
-
- # drop detections with iou > iou_threshold and
- # same category as current detections
- condition = (iou > iou_threshold) & (categories == category)
- keep = keep & ~condition
-
- return keep[sort_index.argsort()]
-
-
-def group_overlapping_boxes(
- predictions: npt.NDArray[np.float64], iou_threshold: float = 0.5
-) -> List[List[int]]:
- """
- Apply greedy version of non-maximum merging to avoid detecting too many
- overlapping bounding boxes for a given object.
-
- Args:
- predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` containing
- the bounding boxes coordinates in format `[x1, y1, x2, y2]`
- and the confidence scores.
- iou_threshold (float, optional): The intersection-over-union threshold
- to use for non-maximum suppression. Defaults to 0.5.
-
- Returns:
- List[List[int]]: Groups of prediction indices be merged.
- Each group may have 1 or more elements.
- """
- merge_groups: List[List[int]] = []
-
- scores = predictions[:, 4]
- order = scores.argsort()
-
- while len(order) > 0:
- idx = int(order[-1])
-
- order = order[:-1]
- if len(order) == 0:
- merge_groups.append([idx])
- break
-
- merge_candidate = np.expand_dims(predictions[idx], axis=0)
- ious = box_iou_batch(predictions[order][:, :4], merge_candidate[:, :4])
- ious = ious.flatten()
-
- above_threshold = ious >= iou_threshold
- merge_group = [idx] + np.flip(order[above_threshold]).tolist()
- merge_groups.append(merge_group)
- order = order[~above_threshold]
- return merge_groups
-
-
-def box_non_max_merge(
- predictions: npt.NDArray[np.float64],
- iou_threshold: float = 0.5,
-) -> List[List[int]]:
- """
- Apply greedy version of non-maximum merging per category to avoid detecting
- too many overlapping bounding boxes for a given object.
-
- Args:
- predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` or `(n, 6)`
- containing the bounding boxes coordinates in format `[x1, y1, x2, y2]`,
- the confidence scores and class_ids. Omit class_id column to allow
- detections of different classes to be merged.
- iou_threshold (float, optional): The intersection-over-union threshold
- to use for non-maximum suppression. Defaults to 0.5.
-
- Returns:
- List[List[int]]: Groups of prediction indices be merged.
- Each group may have 1 or more elements.
- """
- if predictions.shape[1] == 5:
- return group_overlapping_boxes(predictions, iou_threshold)
-
- category_ids = predictions[:, 5]
- merge_groups = []
- for category_id in np.unique(category_ids):
- curr_indices = np.where(category_ids == category_id)[0]
- merge_class_groups = group_overlapping_boxes(
- predictions[curr_indices], iou_threshold
- )
-
- for merge_class_group in merge_class_groups:
- merge_groups.append(curr_indices[merge_class_group].tolist())
-
- for merge_group in merge_groups:
- if len(merge_group) == 0:
- raise ValueError(
- f"Empty group detected when non-max-merging "
- f"detections: {merge_groups}"
- )
- return merge_groups
-
-
def clip_boxes(xyxy: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray:
"""
Clips bounding boxes coordinates to fit within the frame resolution.
| diff --git a/test/detection/test_overlap_filter.py b/test/detection/test_overlap_filter.py
new file mode 100644
index 000000000..f628c30f9
--- /dev/null
+++ b/test/detection/test_overlap_filter.py
@@ -0,0 +1,449 @@
+from contextlib import ExitStack as DoesNotRaise
+from typing import List, Optional
+
+import numpy as np
+import pytest
+
+from supervision.detection.overlap_filter import (
+ box_non_max_suppression,
+ group_overlapping_boxes,
+ mask_non_max_suppression,
+)
+
+
+@pytest.mark.parametrize(
+ "predictions, iou_threshold, expected_result, exception",
+ [
+ (
+ np.empty(shape=(0, 5), dtype=float),
+ 0.5,
+ [],
+ DoesNotRaise(),
+ ),
+ (
+ np.array([[0, 0, 10, 10, 1.0]]),
+ 0.5,
+ [[0]],
+ DoesNotRaise(),
+ ),
+ (
+ np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0]]),
+ 0.5,
+ [[1, 0]],
+ DoesNotRaise(),
+ ), # High overlap, tie-break to second det
+ (
+ np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 0.99]]),
+ 0.5,
+ [[0, 1]],
+ DoesNotRaise(),
+ ), # High overlap, merge to high confidence
+ (
+ np.array([[0, 0, 10, 10, 0.99], [0, 0, 9, 9, 1.0]]),
+ 0.5,
+ [[1, 0]],
+ DoesNotRaise(),
+ ), # (test symmetry) High overlap, merge to high confidence
+ (
+ np.array([[0, 0, 10, 10, 0.90], [0, 0, 9, 9, 1.0]]),
+ 0.5,
+ [[1, 0]],
+ DoesNotRaise(),
+ ), # (test symmetry) High overlap, merge to high confidence
+ (
+ np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0]]),
+ 1.0,
+ [[1], [0]],
+ DoesNotRaise(),
+ ), # High IOU required
+ (
+ np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0]]),
+ 0.0,
+ [[1, 0]],
+ DoesNotRaise(),
+ ), # No IOU required
+ (
+ np.array([[0, 0, 10, 10, 1.0], [0, 0, 5, 5, 0.9]]),
+ 0.25,
+ [[0, 1]],
+ DoesNotRaise(),
+ ), # Below IOU requirement
+ (
+ np.array([[0, 0, 10, 10, 1.0], [0, 0, 5, 5, 0.9]]),
+ 0.26,
+ [[0], [1]],
+ DoesNotRaise(),
+ ), # Above IOU requirement
+ (
+ np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0], [0, 0, 8, 8, 1.0]]),
+ 0.5,
+ [[2, 1, 0]],
+ DoesNotRaise(),
+ ), # 3 boxes
+ (
+ np.array(
+ [
+ [0, 0, 10, 10, 1.0],
+ [0, 0, 9, 9, 1.0],
+ [5, 5, 10, 10, 1.0],
+ [6, 6, 10, 10, 1.0],
+ [9, 9, 10, 10, 1.0],
+ ]
+ ),
+ 0.5,
+ [[4], [3, 2], [1, 0]],
+ DoesNotRaise(),
+ ), # 5 boxes, 2 merges, 1 separate
+ (
+ np.array(
+ [
+ [0, 0, 2, 1, 1.0],
+ [1, 0, 3, 1, 1.0],
+ [2, 0, 4, 1, 1.0],
+ [3, 0, 5, 1, 1.0],
+ [4, 0, 6, 1, 1.0],
+ ]
+ ),
+ 0.33,
+ [[4, 3], [2, 1], [0]],
+ DoesNotRaise(),
+ ), # sequential merge, half overlap
+ (
+ np.array(
+ [
+ [0, 0, 2, 1, 0.9],
+ [1, 0, 3, 1, 0.9],
+ [2, 0, 4, 1, 1.0],
+ [3, 0, 5, 1, 0.9],
+ [4, 0, 6, 1, 0.9],
+ ]
+ ),
+ 0.33,
+ [[2, 3, 1], [4], [0]],
+ DoesNotRaise(),
+ ), # confidence
+ ],
+)
+def test_group_overlapping_boxes(
+ predictions: np.ndarray,
+ iou_threshold: float,
+ expected_result: List[List[int]],
+ exception: Exception,
+) -> None:
+ with exception:
+ result = group_overlapping_boxes(
+ predictions=predictions, iou_threshold=iou_threshold
+ )
+
+ assert result == expected_result
+
+
+@pytest.mark.parametrize(
+ "predictions, iou_threshold, expected_result, exception",
+ [
+ (
+ np.empty(shape=(0, 5)),
+ 0.5,
+ np.array([]),
+ DoesNotRaise(),
+ ), # single box with no category
+ (
+ np.array([[10.0, 10.0, 40.0, 40.0, 0.8]]),
+ 0.5,
+ np.array([True]),
+ DoesNotRaise(),
+ ), # single box with no category
+ (
+ np.array([[10.0, 10.0, 40.0, 40.0, 0.8, 0]]),
+ 0.5,
+ np.array([True]),
+ DoesNotRaise(),
+ ), # single box with category
+ (
+ np.array(
+ [
+ [10.0, 10.0, 40.0, 40.0, 0.8],
+ [15.0, 15.0, 40.0, 40.0, 0.9],
+ ]
+ ),
+ 0.5,
+ np.array([False, True]),
+ DoesNotRaise(),
+ ), # two boxes with no category
+ (
+ np.array(
+ [
+ [10.0, 10.0, 40.0, 40.0, 0.8, 0],
+ [15.0, 15.0, 40.0, 40.0, 0.9, 1],
+ ]
+ ),
+ 0.5,
+ np.array([True, True]),
+ DoesNotRaise(),
+ ), # two boxes with different category
+ (
+ np.array(
+ [
+ [10.0, 10.0, 40.0, 40.0, 0.8, 0],
+ [15.0, 15.0, 40.0, 40.0, 0.9, 0],
+ ]
+ ),
+ 0.5,
+ np.array([False, True]),
+ DoesNotRaise(),
+ ), # two boxes with same category
+ (
+ np.array(
+ [
+ [0.0, 0.0, 30.0, 40.0, 0.8],
+ [5.0, 5.0, 35.0, 45.0, 0.9],
+ [10.0, 10.0, 40.0, 50.0, 0.85],
+ ]
+ ),
+ 0.5,
+ np.array([False, True, False]),
+ DoesNotRaise(),
+ ), # three boxes with no category
+ (
+ np.array(
+ [
+ [0.0, 0.0, 30.0, 40.0, 0.8, 0],
+ [5.0, 5.0, 35.0, 45.0, 0.9, 1],
+ [10.0, 10.0, 40.0, 50.0, 0.85, 2],
+ ]
+ ),
+ 0.5,
+ np.array([True, True, True]),
+ DoesNotRaise(),
+ ), # three boxes with same category
+ (
+ np.array(
+ [
+ [0.0, 0.0, 30.0, 40.0, 0.8, 0],
+ [5.0, 5.0, 35.0, 45.0, 0.9, 0],
+ [10.0, 10.0, 40.0, 50.0, 0.85, 1],
+ ]
+ ),
+ 0.5,
+ np.array([False, True, True]),
+ DoesNotRaise(),
+ ), # three boxes with different category
+ ],
+)
+def test_box_non_max_suppression(
+ predictions: np.ndarray,
+ iou_threshold: float,
+ expected_result: Optional[np.ndarray],
+ exception: Exception,
+) -> None:
+ with exception:
+ 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)
diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py
index 837b3b840..f0f0a6b13 100644
--- a/test/detection/test_utils.py
+++ b/test/detection/test_utils.py
@@ -7,15 +7,12 @@
from supervision.config import CLASS_NAME_DATA_FIELD
from supervision.detection.utils import (
- box_non_max_suppression,
calculate_masks_centroids,
clip_boxes,
contains_holes,
contains_multiple_segments,
filter_polygons_by_area,
get_data_item,
- group_overlapping_boxes,
- mask_non_max_suppression,
merge_data,
move_boxes,
process_roboflow_result,
@@ -26,444 +23,6 @@
TEST_MASK[:, 300:351, 200:251] = True
-@pytest.mark.parametrize(
- "predictions, iou_threshold, expected_result, exception",
- [
- (
- np.empty(shape=(0, 5)),
- 0.5,
- np.array([]),
- DoesNotRaise(),
- ), # single box with no category
- (
- np.array([[10.0, 10.0, 40.0, 40.0, 0.8]]),
- 0.5,
- np.array([True]),
- DoesNotRaise(),
- ), # single box with no category
- (
- np.array([[10.0, 10.0, 40.0, 40.0, 0.8, 0]]),
- 0.5,
- np.array([True]),
- DoesNotRaise(),
- ), # single box with category
- (
- np.array(
- [
- [10.0, 10.0, 40.0, 40.0, 0.8],
- [15.0, 15.0, 40.0, 40.0, 0.9],
- ]
- ),
- 0.5,
- np.array([False, True]),
- DoesNotRaise(),
- ), # two boxes with no category
- (
- np.array(
- [
- [10.0, 10.0, 40.0, 40.0, 0.8, 0],
- [15.0, 15.0, 40.0, 40.0, 0.9, 1],
- ]
- ),
- 0.5,
- np.array([True, True]),
- DoesNotRaise(),
- ), # two boxes with different category
- (
- np.array(
- [
- [10.0, 10.0, 40.0, 40.0, 0.8, 0],
- [15.0, 15.0, 40.0, 40.0, 0.9, 0],
- ]
- ),
- 0.5,
- np.array([False, True]),
- DoesNotRaise(),
- ), # two boxes with same category
- (
- np.array(
- [
- [0.0, 0.0, 30.0, 40.0, 0.8],
- [5.0, 5.0, 35.0, 45.0, 0.9],
- [10.0, 10.0, 40.0, 50.0, 0.85],
- ]
- ),
- 0.5,
- np.array([False, True, False]),
- DoesNotRaise(),
- ), # three boxes with no category
- (
- np.array(
- [
- [0.0, 0.0, 30.0, 40.0, 0.8, 0],
- [5.0, 5.0, 35.0, 45.0, 0.9, 1],
- [10.0, 10.0, 40.0, 50.0, 0.85, 2],
- ]
- ),
- 0.5,
- np.array([True, True, True]),
- DoesNotRaise(),
- ), # three boxes with same category
- (
- np.array(
- [
- [0.0, 0.0, 30.0, 40.0, 0.8, 0],
- [5.0, 5.0, 35.0, 45.0, 0.9, 0],
- [10.0, 10.0, 40.0, 50.0, 0.85, 1],
- ]
- ),
- 0.5,
- np.array([False, True, True]),
- DoesNotRaise(),
- ), # three boxes with different category
- ],
-)
-def test_box_non_max_suppression(
- predictions: np.ndarray,
- iou_threshold: float,
- expected_result: Optional[np.ndarray],
- exception: Exception,
-) -> None:
- with exception:
- result = box_non_max_suppression(
- predictions=predictions, iou_threshold=iou_threshold
- )
- assert np.array_equal(result, expected_result)
-
-
-@pytest.mark.parametrize(
- "predictions, iou_threshold, expected_result, exception",
- [
- (
- np.empty(shape=(0, 5), dtype=float),
- 0.5,
- [],
- DoesNotRaise(),
- ),
- (
- np.array([[0, 0, 10, 10, 1.0]]),
- 0.5,
- [[0]],
- DoesNotRaise(),
- ),
- (
- np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0]]),
- 0.5,
- [[1, 0]],
- DoesNotRaise(),
- ), # High overlap, tie-break to second det
- (
- np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 0.99]]),
- 0.5,
- [[0, 1]],
- DoesNotRaise(),
- ), # High overlap, merge to high confidence
- (
- np.array([[0, 0, 10, 10, 0.99], [0, 0, 9, 9, 1.0]]),
- 0.5,
- [[1, 0]],
- DoesNotRaise(),
- ), # (test symmetry) High overlap, merge to high confidence
- (
- np.array([[0, 0, 10, 10, 0.90], [0, 0, 9, 9, 1.0]]),
- 0.5,
- [[1, 0]],
- DoesNotRaise(),
- ), # (test symmetry) High overlap, merge to high confidence
- (
- np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0]]),
- 1.0,
- [[1], [0]],
- DoesNotRaise(),
- ), # High IOU required
- (
- np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0]]),
- 0.0,
- [[1, 0]],
- DoesNotRaise(),
- ), # No IOU required
- (
- np.array([[0, 0, 10, 10, 1.0], [0, 0, 5, 5, 0.9]]),
- 0.25,
- [[0, 1]],
- DoesNotRaise(),
- ), # Below IOU requirement
- (
- np.array([[0, 0, 10, 10, 1.0], [0, 0, 5, 5, 0.9]]),
- 0.26,
- [[0], [1]],
- DoesNotRaise(),
- ), # Above IOU requirement
- (
- np.array([[0, 0, 10, 10, 1.0], [0, 0, 9, 9, 1.0], [0, 0, 8, 8, 1.0]]),
- 0.5,
- [[2, 1, 0]],
- DoesNotRaise(),
- ), # 3 boxes
- (
- np.array(
- [
- [0, 0, 10, 10, 1.0],
- [0, 0, 9, 9, 1.0],
- [5, 5, 10, 10, 1.0],
- [6, 6, 10, 10, 1.0],
- [9, 9, 10, 10, 1.0],
- ]
- ),
- 0.5,
- [[4], [3, 2], [1, 0]],
- DoesNotRaise(),
- ), # 5 boxes, 2 merges, 1 separate
- (
- np.array(
- [
- [0, 0, 2, 1, 1.0],
- [1, 0, 3, 1, 1.0],
- [2, 0, 4, 1, 1.0],
- [3, 0, 5, 1, 1.0],
- [4, 0, 6, 1, 1.0],
- ]
- ),
- 0.33,
- [[4, 3], [2, 1], [0]],
- DoesNotRaise(),
- ), # sequential merge, half overlap
- (
- np.array(
- [
- [0, 0, 2, 1, 0.9],
- [1, 0, 3, 1, 0.9],
- [2, 0, 4, 1, 1.0],
- [3, 0, 5, 1, 0.9],
- [4, 0, 6, 1, 0.9],
- ]
- ),
- 0.33,
- [[2, 3, 1], [4], [0]],
- DoesNotRaise(),
- ), # confidence
- ],
-)
-def test_group_overlapping_boxes(
- predictions: np.ndarray,
- iou_threshold: float,
- expected_result: List[List[int]],
- exception: Exception,
-) -> None:
- with exception:
- result = group_overlapping_boxes(
- predictions=predictions, iou_threshold=iou_threshold
- )
-
- assert 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/double_detection_filter.md b/docs/detection/double_detection_filter.md
new file mode 100644
index 000000000..1631852f4
--- /dev/null
+++ b/docs/detection/double_detection_filter.md
@@ -0,0 +1,30 @@
+---
+comments: true
+status: new
+---
+
+# Double Detection Filter
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.OverlapFilter">OverlapFilter</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.OverlapFilter
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.box_non_max_suppression">box_non_max_suppression</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.box_non_max_suppression
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.mask_non_max_suppression">mask_non_max_suppression</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.mask_non_max_suppression
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.overlap_filter.box_non_max_merge">box_non_max_merge</a></h2>
+</div>
+
+:::supervision.detection.overlap_filter.box_non_max_merge
diff --git a/docs/detection/utils.md b/docs/detection/utils.md
index f9c9473bc..369746a3e 100644
--- a/docs/detection/utils.md
+++ b/docs/detection/utils.md
@@ -17,18 +17,6 @@ status: new
:::supervision.detection.utils.mask_iou_batch
-<div class="md-typeset">
- <h2><a href="#supervision.detection.utils.box_non_max_suppression">box_non_max_suppression</a></h2>
-</div>
-
-:::supervision.detection.utils.box_non_max_suppression
-
-<div class="md-typeset">
- <h2><a href="#supervision.detection.utils.mask_non_max_suppression">mask_non_max_suppression</a></h2>
-</div>
-
-:::supervision.detection.utils.mask_non_max_suppression
-
<div class="md-typeset">
<h2><a href="#supervision.detection.utils.polygon_to_mask">polygon_to_mask</a></h2>
</div>
diff --git a/mkdocs.yml b/mkdocs.yml
index f257238df..19d6a4fd4 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -48,6 +48,7 @@ nav:
- Core: detection/core.md
- Annotators: detection/annotators.md
- Metrics: detection/metrics.md
+ - Double Detection Filter: detection/double_detection_filter.md
- Utils: detection/utils.md
- Keypoint Detection:
- Core: keypoint/core.md
| [
{
"components": [
{
"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 ... | [
"test/detection/test_overlap_filter.py::test_group_overlapping_boxes[predictions0-0.5-expected_result0-exception0]",
"test/detection/test_overlap_filter.py::test_group_overlapping_boxes[predictions1-0.5-expected_result1-exception1]",
"test/detection/test_overlap_filter.py::test_group_overlapping_boxes[predictio... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Select overlap filtering strategy
# Description
A new enum is defined, allowing InferenceSlicer to select whether to use non-max suppression, non-max merge or simply return `Detections.merge`.
## 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?
Colab: https://colab.research.google.com/drive/1iiJ5oCl8dwwcefRgNXRdaFH6G9dVpf4P?usp=sharing
## Any specific deployment considerations
See my comments in the PR.
## 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/overlap_filter.py]
(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`."""
(definition of group_overlapping_boxes:)
def group_overlapping_boxes( predictions: npt.NDArray[np.float64], iou_threshold: float = 0.5 ) -> List[List[int]]:
"""Apply greedy version of non-maximum merging to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` containing
the bounding boxes coordinates in format `[x1, y1, x2, y2]`
and the confidence scores.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression. Defaults to 0.5.
Returns:
List[List[int]]: Groups of prediction indices be merged.
Each group may have 1 or more elements."""
(definition of box_non_max_merge:)
def box_non_max_merge( predictions: npt.NDArray[np.float64], iou_threshold: float = 0.5, ) -> List[List[int]]:
"""Apply greedy version of non-maximum merging per category to avoid detecting
too many overlapping bounding boxes for a given object.
Args:
predictions (npt.NDArray[np.float64]): An array of shape `(n, 5)` or `(n, 6)`
containing the bounding boxes coordinates in format `[x1, y1, x2, y2]`,
the confidence scores and class_ids. Omit class_id column to allow
detections of different classes to be merged.
iou_threshold (float, optional): The intersection-over-union threshold
to use for non-maximum suppression. Defaults to 0.5.
Returns:
List[List[int]]: Groups of prediction indices be merged.
Each group may have 1 or more elements."""
(definition of OverlapFilter:)
class OverlapFilter(Enum):
"""Enum specifying the strategy for filtering overlapping detections.
Attributes:
NONE: Do not filter detections based on overlap.
NON_MAX_SUPPRESSION: Filter detections using non-max suppression. This means,
detections that overlap by more than a set threshold will be discarded,
except for the one with the highest confidence.
NON_MAX_MERGE: Merge detections with non-max merging. This means,
detections that overlap by more than a set threshold will be merged
into a single detection."""
(definition of validate_overlap_filter:)
def validate_overlap_filter( strategy: Union[OverlapFilter, str], ) -> OverlapFilter:
[end of new definitions in supervision/detection/overlap_filter.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-1770 | 1,770 | pgmpy/pgmpy | null | 9d74e8f957c40f80b8d169ed652d90fbc9289666 | 2024-05-28T04:37:12Z | diff --git a/pgmpy/factors/continuous/LinearGaussianCPD.py b/pgmpy/factors/continuous/LinearGaussianCPD.py
index 32e91ccb8..c7abaf6f2 100644
--- a/pgmpy/factors/continuous/LinearGaussianCPD.py
+++ b/pgmpy/factors/continuous/LinearGaussianCPD.py
@@ -74,7 +74,7 @@ def __init__(
"""
self.variable = variable
- self.mean = evidence_mean
+ self.mean = np.array(evidence_mean)
self.variance = evidence_variance
self.evidence = evidence
self.sigma_yx = None
@@ -220,6 +220,8 @@ def copy(self):
return copy_cpd
def __str__(self):
+ mean = self.mean.round(3)
+ variance = round(self.variance, 3)
if self.evidence and list(self.mean):
# P(Y| X1, X2, X3) = N(-2*X1_mu + 3*X2_mu + 7*X3_mu; 0.2)
rep_str = "P({node} | {parents}) = N({mu} + {b_0}; {sigma})".format(
@@ -228,17 +230,17 @@ def __str__(self):
mu=" + ".join(
[
f"{coeff}*{parent}"
- for coeff, parent in zip(self.mean[1:], self.evidence)
+ for coeff, parent in zip(mean[1:], self.evidence)
]
),
- b_0=str(self.mean[0]),
- sigma=str(self.variance),
+ b_0=str(mean[0]),
+ sigma=str(variance),
)
else:
# P(X) = N(1, 4)
- rep_str = "P({X}) = N({beta_0}; {variance})".format(
- X=str(self.variable),
- beta_0=str(self.mean[0]),
- variance=str(self.variance),
- )
+ rep_str = f"P({str(self.variable)}) = N({str(mean[0])}; {str(variance)})"
return rep_str
+
+ def __repr__(self):
+ str_repr = self.__str__()
+ return f"<LinearGaussianCPD: {str_repr} at {hex(id(self))}"
diff --git a/pgmpy/models/LinearGaussianBayesianNetwork.py b/pgmpy/models/LinearGaussianBayesianNetwork.py
index 2e1f30f88..75048ab2d 100644
--- a/pgmpy/models/LinearGaussianBayesianNetwork.py
+++ b/pgmpy/models/LinearGaussianBayesianNetwork.py
@@ -125,6 +125,42 @@ def remove_cpds(self, *cpds):
"""
return super(LinearGaussianBayesianNetwork, self).remove_cpds(*cpds)
+ def get_random_cpds(self, loc=0, scale=1, seed=None):
+ """
+ Generates random Linear Gaussian CPDs for the model. The coefficients
+ are sampled from a normal distribution with mean `loc` and standard
+ deviation `scale`.
+
+ Parameters
+ ----------
+ loc: float
+ The mean of the normal distribution from which the coefficients are
+ sampled.
+
+ scale: float
+ The standard deviation of the normal distribution from which the
+ coefficients are sampled.
+
+ seed: int
+ The seed for the random number generator.
+ """
+ rng = np.random.default_rng(seed=seed)
+
+ cpds = []
+ for var in self.nodes():
+ parents = self.get_parents(var)
+ cpds.append(
+ LinearGaussianCPD(
+ var,
+ evidence_mean=rng.normal(
+ loc=loc, scale=scale, size=(len(parents) + 1)
+ ),
+ evidence_variance=rng.normal(loc=loc, scale=scale),
+ evidence=parents,
+ )
+ )
+ return cpds
+
def to_joint_gaussian(self):
"""
Linear Gaussian Bayesian Networks can be represented using a joint
@@ -181,7 +217,8 @@ def to_joint_gaussian(self):
inv = np.linalg.inv((I - B))
implied_cov = inv.T @ omega @ inv
- return mean, implied_cov
+ # Round because numerical errors can lead to non-symmetric cov matrix.
+ return mean.round(decimals=8), implied_cov.round(decimals=8)
def simulate(self, n=1000, seed=None):
"""
@@ -211,6 +248,11 @@ def simulate(self, n=1000, seed=None):
>>> model.add_cpds(cpd1, cpd2, cpd3)
>>> model.simulate(n=500, seed=42)
"""
+ if len(self.cpds) != len(self.nodes()):
+ raise ValueError(
+ "Each node in the model should have a CPD associated with it"
+ )
+
mean, cov = self.to_joint_gaussian()
variables = list(nx.topological_sort(self))
rng = np.random.default_rng(seed=seed)
| diff --git a/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py b/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py
index dc26b18c0..d3d698ea5 100644
--- a/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py
+++ b/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py
@@ -83,5 +83,5 @@ def test_str(self):
self.assertEqual(cpd1.__str__(), "P(x) = N(0.23; 0.56)")
self.assertEqual(
cpd2.__str__(),
- "P(y | x1, x2, x3) = N(1*x1 + " "4.56*x2 + 8*x3 + 0.67; 2)",
+ "P(y | x1, x2, x3) = N(1.0*x1 + 4.56*x2 + 8.0*x3 + 0.67; 2)",
)
diff --git a/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py b/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py
index e5249fd0a..26152e94a 100644
--- a/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py
+++ b/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py
@@ -7,6 +7,7 @@
from pgmpy.factors.continuous import LinearGaussianCPD
from pgmpy.factors.discrete import TabularCPD
from pgmpy.models import LinearGaussianBayesianNetwork
+from pgmpy.utils import get_example_model
class TestLGBNMethods(unittest.TestCase):
@@ -105,5 +106,11 @@ def test_simulate(self):
np_test.assert_array_almost_equal(df_cont.mean(), df_equ.mean(), decimal=1)
np_test.assert_array_almost_equal(df_cont.cov(), df_equ.cov(), decimal=1)
+ def test_get_random_cpds(self):
+ model = get_example_model("alarm")
+ model_lin = LinearGaussianBayesianNetwork(model.edges())
+ cpds = model_lin.get_random_cpds()
+ self.assertEqual(len(cpds), len(model.nodes()))
+
def tearDown(self):
del self.model, self.cpd1, self.cpd2, self.cpd3
| [
{
"components": [
{
"doc": "",
"lines": [
244,
246
],
"name": "LinearGaussianCPD.__repr__",
"signature": "def __repr__(self):",
"type": "function"
}
],
"file": "pgmpy/factors/continuous/LinearGaussianCPD.py"
},
{
"co... | [
"pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py::TestLGCPD::test_str"
] | [
"pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py::TestLGCPD::test_class_init",
"pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py::TestLGCPD::test_maximum_likelihood_estimator",
"pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py::TestLGBNMethods::test_add_cpds... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Adds method to generate random Linear Gaussian CPDs for a given model
### 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/factors/continuous/LinearGaussianCPD.py]
(definition of LinearGaussianCPD.__repr__:)
def __repr__(self):
[end of new definitions in pgmpy/factors/continuous/LinearGaussianCPD.py]
[start of new definitions in pgmpy/models/LinearGaussianBayesianNetwork.py]
(definition of LinearGaussianBayesianNetwork.get_random_cpds:)
def get_random_cpds(self, loc=0, scale=1, seed=None):
"""Generates random Linear Gaussian CPDs for the model. The coefficients
are sampled from a normal distribution with mean `loc` and standard
deviation `scale`.
Parameters
----------
loc: float
The mean of the normal distribution from which the coefficients are
sampled.
scale: float
The standard deviation of the normal distribution from which the
coefficients are sampled.
seed: int
The seed for the random number generator."""
[end of new definitions in pgmpy/models/LinearGaussianBayesianNetwork.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 | ||
pgmpy__pgmpy-1768 | 1,768 | pgmpy/pgmpy | null | 8975b88969b8f0e9b0677fa9555c39ac94f94b20 | 2024-05-26T19:49:05Z | diff --git a/pgmpy/models/LinearGaussianBayesianNetwork.py b/pgmpy/models/LinearGaussianBayesianNetwork.py
index 4d4e88cdf..2e1f30f88 100644
--- a/pgmpy/models/LinearGaussianBayesianNetwork.py
+++ b/pgmpy/models/LinearGaussianBayesianNetwork.py
@@ -1,5 +1,6 @@
import networkx as nx
import numpy as np
+import pandas as pd
from pgmpy.factors.continuous import LinearGaussianCPD
from pgmpy.factors.distributions import GaussianDistribution
@@ -126,19 +127,14 @@ def remove_cpds(self, *cpds):
def to_joint_gaussian(self):
"""
- The linear Gaussian Bayesian Networks are an alternative
- representation for the class of multivariate Gaussian distributions.
- This method returns an equivalent joint Gaussian distribution.
+ Linear Gaussian Bayesian Networks can be represented using a joint
+ Gaussian distribution over all the variables. This method gives
+ the mean and covariance of this equivalent joint gaussian distribution.
Returns
-------
- GaussianDistribution: An equivalent joint Gaussian
- distribution for the network.
-
- Reference
- ---------
- Section 7.2, Example 7.3,
- Probabilistic Graphical Models, Principles and Techniques
+ mean, cov: np.ndarray, np.ndarray
+ The mean and the covariance matrix of the joint gaussian distribution.
Examples
--------
@@ -149,66 +145,78 @@ def to_joint_gaussian(self):
>>> cpd2 = LinearGaussianCPD('x2', [-5, 0.5], 4, ['x1'])
>>> cpd3 = LinearGaussianCPD('x3', [4, -1], 3, ['x2'])
>>> model.add_cpds(cpd1, cpd2, cpd3)
- >>> jgd = model.to_joint_gaussian()
- >>> jgd.variables
- ['x1', 'x2', 'x3']
- >>> jgd.mean
- array([[ 1. ],
- [-4.5],
- [ 8.5]])
- >>> jgd.covariance
+ >>> mean, cov = model.to_joint_gaussian()
+ >>> mean
+ array([ 1. ], [-4.5], [ 8.5])
+ >>> cov
array([[ 4., 2., -2.],
[ 2., 5., -5.],
[-2., -5., 8.]])
"""
variables = list(nx.topological_sort(self))
- mean = np.zeros(len(variables))
- covariance = np.zeros((len(variables), len(variables)))
-
- for node_idx in range(len(variables)):
- cpd = self.get_cpds(variables[node_idx])
- coefficients = cpd.mean.copy()
- coefficients.pop(0)
- mean[node_idx] = (
- sum(
- [
- coeff * mean[variables.index(parent)]
- for coeff, parent in zip(coefficients, cpd.evidence)
- ]
- )
- + cpd.mean[0]
- )
- covariance[node_idx, node_idx] = (
- sum(
- [
- coeff
- * coeff
- * covariance[variables.index(parent), variables.index(parent)]
- for coeff, parent in zip(coefficients, cpd.evidence)
- ]
- )
- + cpd.variance
- )
-
- for node_i_idx in range(len(variables)):
- for node_j_idx in range(len(variables)):
- if covariance[node_j_idx, node_i_idx] != 0:
- covariance[node_i_idx, node_j_idx] = covariance[
- node_j_idx, node_i_idx
- ]
- else:
- cpd_j = self.get_cpds(variables[node_j_idx])
- coefficients = cpd_j.mean.copy()
- coefficients.pop(0)
- covariance[node_i_idx, node_j_idx] = sum(
- [
- coeff * covariance[node_i_idx, variables.index(parent)]
- for coeff, parent in zip(coefficients, cpd_j.evidence)
- ]
- )
+ var_to_index = {var: i for i, var in enumerate(variables)}
+ n_nodes = len(self.nodes())
+
+ # Step 1: Compute the mean for each variable.
+ mean = {}
+ for var in variables:
+ cpd = self.get_cpds(node=var)
+ mean[var] = (
+ cpd.mean * (np.array([1] + [mean[u] for u in cpd.evidence]))
+ ).sum()
+ mean = np.array([mean[u] for u in variables])
+
+ # Step 2: Populate the adjacency matrix, and variance matrix
+ B = np.zeros((n_nodes, n_nodes))
+ omega = np.zeros((n_nodes, n_nodes))
+ for var in variables:
+ cpd = self.get_cpds(node=var)
+ for i, evidence_var in enumerate(cpd.evidence):
+ B[var_to_index[evidence_var], var_to_index[var]] = cpd.mean[i + 1]
+ omega[var_to_index[var], var_to_index[var]] = cpd.variance
+
+ # Step 3: Compute the implied covariance matrix
+ I = np.eye(n_nodes)
+ inv = np.linalg.inv((I - B))
+ implied_cov = inv.T @ omega @ inv
+
+ return mean, implied_cov
+
+ def simulate(self, n=1000, seed=None):
+ """
+ Simulates data from the given model.
+
+ Parameters
+ ----------
+ n: int
+ The number of samples to draw from the model.
+
+ seed: int (default: None)
+ Seed for the random number generator.
+
+ Returns
+ -------
+ pandas.DataFrame: generated samples
+ A pandas data frame with the generated samples.
- return GaussianDistribution(variables, mean, covariance)
+ Examples
+ --------
+ >>> from pgmpy.models import LinearGaussianBayesianNetwork
+ >>> from pgmpy.factors.continuous import LinearGaussianCPD
+ >>> model = LinearGaussianBayesianNetwork([('x1', 'x2'), ('x2', 'x3')])
+ >>> cpd1 = LinearGaussianCPD('x1', [1], 4)
+ >>> cpd2 = LinearGaussianCPD('x2', [-5, 0.5], 4, ['x1'])
+ >>> cpd3 = LinearGaussianCPD('x3', [4, -1], 3, ['x2'])
+ >>> model.add_cpds(cpd1, cpd2, cpd3)
+ >>> model.simulate(n=500, seed=42)
+ """
+ mean, cov = self.to_joint_gaussian()
+ variables = list(nx.topological_sort(self))
+ rng = np.random.default_rng(seed=seed)
+ return pd.DataFrame(
+ rng.multivariate_normal(mean=mean, cov=cov, size=n), columns=variables
+ )
def check_model(self):
"""
| diff --git a/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py b/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py
index ed125a0b8..dc26b18c0 100644
--- a/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py
+++ b/pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py
@@ -1,13 +1,13 @@
import unittest
+
+import numpy as np
import numpy.testing as np_test
import pandas as pd
-import numpy as np
from pgmpy.factors.continuous import LinearGaussianCPD
class TestLGCPD(unittest.TestCase):
- # @unittest.skip("TODO")
def test_class_init(self):
mu = np.array([7, 13])
sigma = np.array([[4, 3], [3, 6]])
@@ -85,9 +85,3 @@ def test_str(self):
cpd2.__str__(),
"P(y | x1, x2, x3) = N(1*x1 + " "4.56*x2 + 8*x3 + 0.67; 2)",
)
-
-
-# def test_mle_fit(self):
-# cpd = LinearGaussianCPD('Y', [0.2, -2, 3, 7], 9.6, ['X1', 'X2', 'X3'])
-# gbn_values = pd.read_csv('gbn_values.csv')
-# cpd.fit(gbn_values)
diff --git a/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py b/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py
index d282a46a0..e5249fd0a 100644
--- a/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py
+++ b/pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py
@@ -2,6 +2,7 @@
import numpy as np
import numpy.testing as np_test
+import pandas as pd
from pgmpy.factors.continuous import LinearGaussianCPD
from pgmpy.factors.discrete import TabularCPD
@@ -26,29 +27,23 @@ def test_cpds_simple(self):
self.assertEqual(cpd.variance, self.cpd1.variance)
self.assertEqual(cpd.mean, self.cpd1.mean)
- @unittest.skip("TODO")
def test_add_cpds(self):
self.model.add_cpds(self.cpd1)
cpd = self.model.get_cpds("x1")
self.assertEqual(cpd.variable, self.cpd1.variable)
self.assertEqual(cpd.variance, self.cpd1.variance)
- self.assertEqual(cpd.beta_0, self.cpd1.beta_0)
self.model.add_cpds(self.cpd2)
cpd = self.model.get_cpds("x2")
self.assertEqual(cpd.variable, self.cpd2.variable)
self.assertEqual(cpd.variance, self.cpd2.variance)
- self.assertEqual(cpd.beta_0, self.cpd2.beta_0)
self.assertEqual(cpd.evidence, self.cpd2.evidence)
- np_test.assert_array_equal(cpd.beta_vector, self.cpd2.beta_vector)
self.model.add_cpds(self.cpd3)
cpd = self.model.get_cpds("x3")
self.assertEqual(cpd.variable, self.cpd3.variable)
self.assertEqual(cpd.variance, self.cpd3.variance)
- self.assertEqual(cpd.beta_0, self.cpd3.beta_0)
self.assertEqual(cpd.evidence, self.cpd3.evidence)
- np_test.assert_array_equal(cpd.beta_vector, self.cpd3.beta_vector)
tab_cpd = TabularCPD(
"grade",
@@ -65,18 +60,16 @@ def test_add_cpds(self):
self.assertRaises(ValueError, self.model.add_cpds, 1)
self.assertRaises(ValueError, self.model.add_cpds, 1, tab_cpd)
- @unittest.skip("TODO")
def test_to_joint_gaussian(self):
self.model.add_cpds(self.cpd1, self.cpd2, self.cpd3)
- jgd = self.model.to_joint_gaussian()
- self.assertEqual(jgd.variables, ["x1", "x2", "x3"])
- np_test.assert_array_equal(jgd.mean, np.array([[1.0], [-4.5], [8.5]]))
- np_test.assert_array_equal(
- jgd.covariance,
+ mean, cov = self.model.to_joint_gaussian()
+ np_test.assert_array_almost_equal(mean, np.array([1.0, -4.5, 8.5]), decimal=3)
+ np_test.assert_array_almost_equal(
+ cov,
np.array([[4.0, 2.0, -2.0], [2.0, 5.0, -5.0], [-2.0, -5.0, 8.0]]),
+ decimal=3,
)
- @unittest.skip("TODO")
def test_check_model(self):
self.model.add_cpds(self.cpd1, self.cpd2, self.cpd3)
self.assertEqual(self.model.check_model(), True)
@@ -87,7 +80,6 @@ def test_check_model(self):
self.assertRaises(ValueError, self.model.check_model)
- @unittest.skip("TODO")
def test_not_implemented_methods(self):
self.assertRaises(ValueError, self.model.get_cardinality, "x1")
self.assertRaises(NotImplementedError, self.model.fit, [[1, 2, 3], [1, 5, 6]])
@@ -98,3 +90,20 @@ def test_not_implemented_methods(self):
self.assertRaises(
NotImplementedError, self.model.is_imap, [[1, 2, 3], [1, 5, 6]]
)
+
+ def test_simulate(self):
+ self.model.add_cpds(self.cpd1, self.cpd2, self.cpd3)
+ df_cont = self.model.simulate(n=10000, seed=42)
+
+ # Same model in terms of equations
+ rng = np.random.default_rng(seed=42)
+ x1 = 1 + rng.normal(0, 2, 10000)
+ x2 = -5 + 0.5 * x1 + rng.normal(0, 2, 10000)
+ x3 = 4 + -1 * x2 + rng.normal(0, np.sqrt(3), 10000)
+ df_equ = pd.DataFrame({"x1": x1, "x2": x2, "x3": x3})
+
+ np_test.assert_array_almost_equal(df_cont.mean(), df_equ.mean(), decimal=1)
+ np_test.assert_array_almost_equal(df_cont.cov(), df_equ.cov(), decimal=1)
+
+ def tearDown(self):
+ del self.model, self.cpd1, self.cpd2, self.cpd3
| [
{
"components": [
{
"doc": "Simulates data from the given model.\n\nParameters\n----------\nn: int\n The number of samples to draw from the model.\n\nseed: int (default: None)\n Seed for the random number generator.\n\nReturns\n-------\npandas.DataFrame: generated samples\n A pandas data ... | [
"pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py::TestLGBNMethods::test_simulate",
"pgmpy/tests/test_models/test_LinearGaussianBayesianNetwork.py::TestLGBNMethods::test_to_joint_gaussian"
] | [
"pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py::TestLGCPD::test_class_init",
"pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py::TestLGCPD::test_maximum_likelihood_estimator",
"pgmpy/tests/test_factors/test_continuous/test_Linear_Gaussian_CPD.py::TestLGCPD::test_str",
... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Adds simulation method to Linear Gaussian BN
### 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/models/LinearGaussianBayesianNetwork.py]
(definition of LinearGaussianBayesianNetwork.simulate:)
def simulate(self, n=1000, seed=None):
"""Simulates data from the given model.
Parameters
----------
n: int
The number of samples to draw from the model.
seed: int (default: None)
Seed for the random number generator.
Returns
-------
pandas.DataFrame: generated samples
A pandas data frame with the generated samples.
Examples
--------
>>> from pgmpy.models import LinearGaussianBayesianNetwork
>>> from pgmpy.factors.continuous import LinearGaussianCPD
>>> model = LinearGaussianBayesianNetwork([('x1', 'x2'), ('x2', 'x3')])
>>> cpd1 = LinearGaussianCPD('x1', [1], 4)
>>> cpd2 = LinearGaussianCPD('x2', [-5, 0.5], 4, ['x1'])
>>> cpd3 = LinearGaussianCPD('x3', [4, -1], 3, ['x2'])
>>> model.add_cpds(cpd1, cpd2, cpd3)
>>> model.simulate(n=500, seed=42)"""
[end of new definitions in pgmpy/models/LinearGaussianBayesianNetwork.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 | ||
googleapis__python-aiplatform-3834 | 3,834 | googleapis/python-aiplatform | null | 9d3561738d577129cb222417bf208166825d8043 | 2024-05-24T22:07:36Z | diff --git a/google/cloud/aiplatform/initializer.py b/google/cloud/aiplatform/initializer.py
index a615baa4bb..34b53fc26f 100644
--- a/google/cloud/aiplatform/initializer.py
+++ b/google/cloud/aiplatform/initializer.py
@@ -17,11 +17,12 @@
from concurrent import futures
+import functools
import inspect
import logging
import os
import types
-from typing import Iterator, List, Optional, Type, TypeVar, Tuple, Union
+from typing import Iterator, List, Optional, Sequence, Tuple, Type, TypeVar, Union
from google.api_core import client_options
from google.api_core import gapic_v1
@@ -108,6 +109,7 @@ def __init__(self):
self._service_account = None
self._api_endpoint = None
self._api_transport = None
+ self._request_metadata = None
def init(
self,
@@ -126,6 +128,7 @@ def init(
service_account: Optional[str] = None,
api_endpoint: Optional[str] = None,
api_transport: Optional[str] = None,
+ request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
):
"""Updates common initialization parameters with provided options.
@@ -188,6 +191,8 @@ def init(
Optional. The transport method which is either 'grpc' or 'rest'.
NOTE: "rest" transport functionality is currently in a
beta state (preview).
+ request_metadata:
+ Optional. Additional gRPC metadata to send with every client request.
Raises:
ValueError:
If experiment_description is provided but experiment is not.
@@ -235,6 +240,8 @@ def init(
self._network = network
if service_account is not None:
self._service_account = service_account
+ if request_metadata is not None:
+ self._request_metadata = request_metadata
# Finally, perform secondary state updates
if experiment_tensorboard and not isinstance(experiment_tensorboard, bool):
@@ -517,7 +524,11 @@ def create_client(
else:
kwargs["transport"] = self._api_transport
- return client_class(**kwargs)
+ client = client_class(**kwargs)
+ # We only wrap the client if the request_metadata is set at the creation time.
+ if self._request_metadata:
+ client = _ClientWrapperThatAddsDefaultMetadata(client)
+ return client
def _get_default_project_and_location(self) -> Tuple[str, str]:
return (
@@ -526,6 +537,57 @@ def _get_default_project_and_location(self) -> Tuple[str, str]:
)
+# Helper classes for adding default metadata to API requests.
+# We're solving multiple non-trivial issues here.
+# Intended behavior.
+# The first big question is whether calling `vertexai.init(request_metadata=...)`
+# should change the existing clients.
+# This question is non-trivial. Client's client options are immutable.
+# But changes to default project, location and credentials affect SDK calls immediately.
+# It can be argued that default metadata should affect previously created clients.
+# Implementation.
+# There are 3 kinds of clients:
+# 1) Raw GAPIC client (there are also different transports like "grpc" and "rest")
+# 2) ClientWithOverride with _is_temporary=True
+# 3) ClientWithOverride with _is_temporary=False
+# While a raw client or a non-temporary ClientWithOverride object can be patched once
+# (`callable._metadata for callable in client._transport._wrapped_methods.values()`),
+# a temporary `ClientWithOverride` creates new client at every call and they
+# need to be dynamically patched.
+# The temporary `ClientWithOverride` case requires dynamic wrapping/patching.
+# A client wrapper, that dynamically wraps methods to add metadata, solves all 3 cases.
+class _ClientWrapperThatAddsDefaultMetadata:
+ """A client wrapper that dynamically wraps methods to add default metadata."""
+
+ def __init__(self, client):
+ self._client = client
+
+ def __getattr__(self, name: str):
+ result = getattr(self._client, name)
+ if global_config._request_metadata and callable(result):
+ func = result
+ if "metadata" in inspect.signature(func).parameters:
+ return _FunctionWrapperThatAddsDefaultMetadata(func)
+ return result
+
+
+class _FunctionWrapperThatAddsDefaultMetadata:
+ """A function wrapper that wraps a function/method to add default metadata."""
+
+ def __init__(self, func):
+ self._func = func
+ functools.update_wrapper(self, func)
+
+ def __call__(self, *args, **kwargs):
+ # Start with default metadata (copy it)
+ metadata_list = list(global_config._request_metadata or [])
+ # Add per-request metadata (overrides defaults)
+ # The "metadata" argument is removed from "kwargs"
+ metadata_list.extend(kwargs.pop("metadata", []))
+ # Call the wrapped function with extra metadata
+ return self._func(*args, **kwargs, metadata=metadata_list)
+
+
# global config to store init parameters: ie, aiplatform.init(project=..., location=...)
global_config = _Config()
| diff --git a/tests/system/vertexai/test_generative_models.py b/tests/system/vertexai/test_generative_models.py
index 1282e99c26..292f8a0dfa 100644
--- a/tests/system/vertexai/test_generative_models.py
+++ b/tests/system/vertexai/test_generative_models.py
@@ -429,3 +429,12 @@ def test_chat_automatic_function_calling(self):
assert chat.history[-3].parts[0].function_call.name == "get_current_weather"
assert chat.history[-2].parts[0].function_response
assert chat.history[-2].parts[0].function_response.name == "get_current_weather"
+
+ def test_additional_request_metadata(self):
+ aiplatform.init(request_metadata=[("foo", "bar")])
+ model = generative_models.GenerativeModel(GEMINI_MODEL_NAME)
+ response = model.generate_content(
+ "Why is sky blue?",
+ generation_config=generative_models.GenerationConfig(temperature=0),
+ )
+ assert response
diff --git a/tests/unit/aiplatform/test_initializer.py b/tests/unit/aiplatform/test_initializer.py
index d3993014f0..455ee0791a 100644
--- a/tests/unit/aiplatform/test_initializer.py
+++ b/tests/unit/aiplatform/test_initializer.py
@@ -32,6 +32,7 @@
from google.cloud.aiplatform.utils import resource_manager_utils
from google.cloud.aiplatform.compat.services import (
model_service_client,
+ prediction_service_client_v1beta1,
)
import constants as test_constants
@@ -451,6 +452,62 @@ def test_init_with_only_project_does_not_override_set_creds(self):
initializer.global_config.init(project=_TEST_PROJECT_2)
assert initializer.global_config.credentials is creds
+ def test_create_client_with_request_metadata_model_service(self):
+ global_metadata = [
+ ("global_param", "value1"),
+ ]
+ request_metadata = [
+ ("request_param", "value2"),
+ ]
+ initializer.global_config.init(
+ project=_TEST_PROJECT,
+ location=_TEST_LOCATION,
+ request_metadata=global_metadata,
+ api_transport="rest",
+ )
+ client = initializer.global_config.create_client(
+ client_class=utils.ModelClientWithOverride
+ )
+ model_name = client.model_path(
+ project=_TEST_PROJECT,
+ location=_TEST_LOCATION,
+ model="model_id",
+ )
+ with patch("requests.sessions.Session.get") as mock_get:
+ mock_get.return_value.status_code = 200
+ mock_get.return_value.content = "{}"
+ client.get_model(name=model_name, metadata=request_metadata)
+ call_kwargs = mock_get.call_args_list[0][1]
+ headers = call_kwargs["headers"]
+ for metadata_key in ["global_param", "request_param"]:
+ assert metadata_key in headers
+
+ def test_create_client_with_request_metadata_prediction_service(self):
+ global_metadata = [
+ ("global_param", "value1"),
+ ]
+ request_metadata = [
+ ("request_param", "value2"),
+ ]
+ initializer.global_config.init(
+ project=_TEST_PROJECT,
+ location=_TEST_LOCATION,
+ request_metadata=global_metadata,
+ api_transport="rest",
+ )
+ client = initializer.global_config.create_client(
+ client_class=prediction_service_client_v1beta1.PredictionServiceClient
+ )
+ model_name = f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/publishers/google/models/gemini-1.0-pro"
+ with patch("requests.sessions.Session.post") as mock_post:
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.content = "{}"
+ client.generate_content(model=model_name, metadata=request_metadata)
+ call_kwargs = mock_post.call_args_list[0][1]
+ headers = call_kwargs["headers"]
+ for metadata_key in ["global_param", "request_param"]:
+ assert metadata_key in headers
+
class TestThreadPool:
def teardown_method(self):
| [
{
"components": [
{
"doc": "A client wrapper that dynamically wraps methods to add default metadata.",
"lines": [
559,
571
],
"name": "_ClientWrapperThatAddsDefaultMetadata",
"signature": "class _ClientWrapperThatAddsDefaultMetadata:",
"t... | [
"tests/unit/aiplatform/test_initializer.py::TestInit::test_create_client_with_request_metadata_model_service",
"tests/unit/aiplatform/test_initializer.py::TestInit::test_create_client_with_request_metadata_prediction_service"
] | [
"tests/unit/aiplatform/test_initializer.py::TestInit::test_init_project_sets_project",
"tests/unit/aiplatform/test_initializer.py::TestInit::test_not_init_project_gets_default_project",
"tests/unit/aiplatform/test_initializer.py::TestInit::test_infer_project_id",
"tests/unit/aiplatform/test_initializer.py::Te... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Added support for adding request metadata
feat: Added support for adding request metadata
When using the HTTP transport, this metadata is sent as HTTP headers.
Usage:
```
vertexai.init(
request_metadata=[("param1", "value1")],
)
```
----------
</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 google/cloud/aiplatform/initializer.py]
(definition of _ClientWrapperThatAddsDefaultMetadata:)
class _ClientWrapperThatAddsDefaultMetadata:
"""A client wrapper that dynamically wraps methods to add default metadata."""
(definition of _ClientWrapperThatAddsDefaultMetadata.__init__:)
def __init__(self, client):
(definition of _ClientWrapperThatAddsDefaultMetadata.__getattr__:)
def __getattr__(self, name: str):
(definition of _FunctionWrapperThatAddsDefaultMetadata:)
class _FunctionWrapperThatAddsDefaultMetadata:
"""A function wrapper that wraps a function/method to add default metadata."""
(definition of _FunctionWrapperThatAddsDefaultMetadata.__init__:)
def __init__(self, func):
(definition of _FunctionWrapperThatAddsDefaultMetadata.__call__:)
def __call__(self, *args, **kwargs):
[end of new definitions in google/cloud/aiplatform/initializer.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 | ||
slackapi__bolt-python-1085 | 1,085 | slackapi/bolt-python | null | dbe2333046b582c087fd19d6812c8a523835f53c | 2024-05-24T19:15:23Z | diff --git a/examples/wsgi/app.py b/examples/wsgi/app.py
new file mode 100644
index 000000000..d994ffbf9
--- /dev/null
+++ b/examples/wsgi/app.py
@@ -0,0 +1,19 @@
+from slack_bolt import App
+from slack_bolt.adapter.wsgi import SlackRequestHandler
+
+app = App()
+
+
+@app.event("app_mention")
+def handle_app_mentions(body, say, logger):
+ logger.info(body)
+ say("What's up?")
+
+
+api = SlackRequestHandler(app)
+
+# pip install -r requirements.txt
+# export SLACK_SIGNING_SECRET=***
+# export SLACK_BOT_TOKEN=xoxb-***
+# gunicorn app:api -b 0.0.0.0:3000 --log-level debug
+# ngrok http 3000
diff --git a/examples/wsgi/oauth_app.py b/examples/wsgi/oauth_app.py
new file mode 100644
index 000000000..bdb844fd4
--- /dev/null
+++ b/examples/wsgi/oauth_app.py
@@ -0,0 +1,23 @@
+from slack_bolt import App
+from slack_bolt.adapter.wsgi import SlackRequestHandler
+
+app = App()
+
+
+@app.event("app_mention")
+def handle_app_mentions(body, say, logger):
+ logger.info(body)
+ say("What's up?")
+
+
+api = SlackRequestHandler(app)
+
+# pip install -r requirements.txt
+
+# # -- OAuth flow -- #
+# export SLACK_SIGNING_SECRET=***
+# export SLACK_CLIENT_ID=111.111
+# export SLACK_CLIENT_SECRET=***
+# export SLACK_SCOPES=app_mentions:read,channels:history,im:history,chat:write
+
+# gunicorn oauth_app:api -b 0.0.0.0:3000 --log-level debug
diff --git a/examples/wsgi/requirements.txt b/examples/wsgi/requirements.txt
new file mode 100644
index 000000000..5c3ac5752
--- /dev/null
+++ b/examples/wsgi/requirements.txt
@@ -0,0 +1,1 @@
+gunicorn<23
diff --git a/slack_bolt/adapter/wsgi/__init__.py b/slack_bolt/adapter/wsgi/__init__.py
new file mode 100644
index 000000000..bf7cf78a4
--- /dev/null
+++ b/slack_bolt/adapter/wsgi/__init__.py
@@ -0,0 +1,3 @@
+from .handler import SlackRequestHandler
+
+__all__ = ["SlackRequestHandler"]
diff --git a/slack_bolt/adapter/wsgi/handler.py b/slack_bolt/adapter/wsgi/handler.py
new file mode 100644
index 000000000..55537e464
--- /dev/null
+++ b/slack_bolt/adapter/wsgi/handler.py
@@ -0,0 +1,85 @@
+from typing import Any, Callable, Dict, Iterable, List, Tuple
+
+from slack_bolt import App
+from slack_bolt.adapter.wsgi.http_request import WsgiHttpRequest
+from slack_bolt.adapter.wsgi.http_response import WsgiHttpResponse
+from slack_bolt.oauth.oauth_flow import OAuthFlow
+from slack_bolt.request import BoltRequest
+from slack_bolt.response import BoltResponse
+
+
+class SlackRequestHandler:
+ def __init__(self, app: App, path: str = "/slack/events"):
+ """Setup Bolt as a WSGI web framework, this will make your application compatible with WSGI web servers.
+ This can be used for production deployments.
+
+ With the default settings, `http://localhost:3000/slack/events`
+ Run Bolt with [gunicorn](https://gunicorn.org/)
+
+ # Python
+ app = App()
+
+ api = SlackRequestHandler(app)
+
+ # bash
+ export SLACK_SIGNING_SECRET=***
+
+ export SLACK_BOT_TOKEN=xoxb-***
+
+ gunicorn app:api -b 0.0.0.0:3000 --log-level debug
+
+ Args:
+ app: Your bolt application
+ path: The path to handle request from Slack (Default: `/slack/events`)
+ """
+ self.path = path
+ self.app = app
+
+ def dispatch(self, request: WsgiHttpRequest) -> BoltResponse:
+ return self.app.dispatch(
+ BoltRequest(body=request.get_body(), query=request.query_string, headers=request.get_headers())
+ )
+
+ def handle_installation(self, request: WsgiHttpRequest) -> BoltResponse:
+ oauth_flow: OAuthFlow = self.app.oauth_flow
+ return oauth_flow.handle_installation(
+ BoltRequest(body=request.get_body(), query=request.query_string, headers=request.get_headers())
+ )
+
+ def handle_callback(self, request: WsgiHttpRequest) -> BoltResponse:
+ oauth_flow: OAuthFlow = self.app.oauth_flow
+ return oauth_flow.handle_callback(
+ BoltRequest(body=request.get_body(), query=request.query_string, headers=request.get_headers())
+ )
+
+ def _get_http_response(self, request: WsgiHttpRequest) -> WsgiHttpResponse:
+ if request.method == "GET":
+ if self.app.oauth_flow is not None:
+ if request.path == self.app.oauth_flow.install_path:
+ bolt_response: BoltResponse = self.handle_installation(request)
+ return WsgiHttpResponse(
+ status=bolt_response.status, headers=bolt_response.headers, body=bolt_response.body
+ )
+ if request.path == self.app.oauth_flow.redirect_uri_path:
+ bolt_response: BoltResponse = self.handle_callback(request)
+ return WsgiHttpResponse(
+ status=bolt_response.status, headers=bolt_response.headers, body=bolt_response.body
+ )
+ if request.method == "POST" and request.path == self.path:
+ bolt_response: BoltResponse = self.dispatch(request)
+ return WsgiHttpResponse(status=bolt_response.status, headers=bolt_response.headers, body=bolt_response.body)
+ return WsgiHttpResponse(status=404, headers={"content-type": ["text/plain;charset=utf-8"]}, body="Not Found")
+
+ def __call__(
+ self,
+ environ: Dict[str, Any],
+ start_response: Callable[[str, List[Tuple[str, str]]], None],
+ ) -> Iterable[bytes]:
+ request = WsgiHttpRequest(environ)
+ if "HTTP" in request.protocol:
+ response: WsgiHttpResponse = self._get_http_response(
+ request=request,
+ )
+ start_response(response.status, response.get_headers())
+ return response.get_body()
+ raise TypeError(f"Unsupported SERVER_PROTOCOL: {request.protocol}")
diff --git a/slack_bolt/adapter/wsgi/http_request.py b/slack_bolt/adapter/wsgi/http_request.py
new file mode 100644
index 000000000..e410f4cc0
--- /dev/null
+++ b/slack_bolt/adapter/wsgi/http_request.py
@@ -0,0 +1,37 @@
+from typing import Any, Dict
+
+from .internals import ENCODING
+
+
+class WsgiHttpRequest:
+ """This Class uses the PEP 3333 standard to extract request information
+ from the WSGI web server running the application
+
+ PEP 3333: https://peps.python.org/pep-3333/
+ """
+
+ __slots__ = ("method", "path", "query_string", "protocol", "environ")
+
+ def __init__(self, environ: Dict[str, Any]):
+ self.method: str = environ.get("REQUEST_METHOD", "GET")
+ self.path: str = environ.get("PATH_INFO", "")
+ self.query_string: str = environ.get("QUERY_STRING", "")
+ self.protocol: str = environ.get("SERVER_PROTOCOL", "")
+ self.environ = environ
+
+ def get_headers(self) -> Dict[str, str]:
+ headers = {}
+ for key, value in self.environ.items():
+ if key in {"CONTENT_LENGTH", "CONTENT_TYPE"}:
+ name = key.lower().replace("_", "-")
+ headers[name] = value
+ if key.startswith("HTTP_"):
+ name = key[len("HTTP_"):].lower().replace("_", "-") # fmt: skip
+ headers[name] = value
+ return headers
+
+ def get_body(self) -> str:
+ if "wsgi.input" not in self.environ:
+ return ""
+ content_length = int(self.environ.get("CONTENT_LENGTH", 0))
+ return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
diff --git a/slack_bolt/adapter/wsgi/http_response.py b/slack_bolt/adapter/wsgi/http_response.py
new file mode 100644
index 000000000..1ad32e672
--- /dev/null
+++ b/slack_bolt/adapter/wsgi/http_response.py
@@ -0,0 +1,33 @@
+from http import HTTPStatus
+from typing import Dict, Iterable, List, Sequence, Tuple
+
+from .internals import ENCODING
+
+
+class WsgiHttpResponse:
+ """This Class uses the PEP 3333 standard to adapt bolt response information
+ for the WSGI web server running the application
+
+ PEP 3333: https://peps.python.org/pep-3333/
+ """
+
+ __slots__ = ("status", "_headers", "_body")
+
+ def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""):
+ _status = HTTPStatus(status)
+ self.status = f"{_status.value} {_status.phrase}"
+ self._headers = headers
+ self._body = bytes(body, ENCODING)
+
+ def get_headers(self) -> List[Tuple[str, str]]:
+ headers: List[Tuple[str, str]] = []
+ for key, value in self._headers.items():
+ if key.lower() == "content-length":
+ continue
+ headers.append((key, value[0]))
+
+ headers.append(("content-length", str(len(self._body))))
+ return headers
+
+ def get_body(self) -> Iterable[bytes]:
+ return [self._body]
diff --git a/slack_bolt/adapter/wsgi/internals.py b/slack_bolt/adapter/wsgi/internals.py
new file mode 100644
index 000000000..cda3e876a
--- /dev/null
+++ b/slack_bolt/adapter/wsgi/internals.py
@@ -0,0 +1,1 @@
+ENCODING = "utf-8" # The content encoding for Slack requests/responses is always utf-8
| diff --git a/tests/adapter_tests/wsgi/__init__.py b/tests/adapter_tests/wsgi/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/adapter_tests/wsgi/test_wsgi_http.py b/tests/adapter_tests/wsgi/test_wsgi_http.py
new file mode 100644
index 000000000..63ac62627
--- /dev/null
+++ b/tests/adapter_tests/wsgi/test_wsgi_http.py
@@ -0,0 +1,230 @@
+import json
+from time import time
+from urllib.parse import quote
+
+from slack_sdk.signature import SignatureVerifier
+from slack_sdk.web import WebClient
+
+from slack_bolt.adapter.wsgi import SlackRequestHandler
+from slack_bolt.app import App
+from slack_bolt.oauth.oauth_settings import OAuthSettings
+from tests.mock_web_api_server import assert_auth_test_count, cleanup_mock_web_api_server, setup_mock_web_api_server
+from tests.mock_wsgi_server import WsgiTestServer
+from tests.utils import remove_os_env_temporarily, restore_os_env
+
+
+class TestWsgiHttp:
+ signing_secret = "secret"
+ valid_token = "xoxb-valid"
+ mock_api_server_base_url = "http://localhost:8888"
+ signature_verifier = SignatureVerifier(signing_secret)
+ web_client = WebClient(
+ token=valid_token,
+ base_url=mock_api_server_base_url,
+ )
+
+ def setup_method(self):
+ self.old_os_env = remove_os_env_temporarily()
+ setup_mock_web_api_server(self)
+
+ def teardown_method(self):
+ cleanup_mock_web_api_server(self)
+ restore_os_env(self.old_os_env)
+
+ def generate_signature(self, body: str, timestamp: str):
+ return self.signature_verifier.generate_signature(
+ body=body,
+ timestamp=timestamp,
+ )
+
+ def build_raw_headers(self, timestamp: str, body: str = ""):
+ content_type = "application/json" if body.startswith("{") else "application/x-www-form-urlencoded"
+ return {
+ "host": "123.123.123",
+ "user-agent": "some slack thing",
+ "content-length": str(len(body)),
+ "accept": "application/json,*/*",
+ "accept-encoding": "gzip,deflate",
+ "content-type": content_type,
+ "x-forwarded-for": "123.123.123",
+ "x-forwarded-proto": "https",
+ "x-slack-request-timestamp": timestamp,
+ "x-slack-signature": self.generate_signature(body, timestamp),
+ }
+
+ def test_commands(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+
+ def command_handler(ack):
+ ack()
+
+ app.command("/hello-world")(command_handler)
+
+ body = (
+ "token=verification_token"
+ "&team_id=T111"
+ "&team_domain=test-domain"
+ "&channel_id=C111"
+ "&channel_name=random"
+ "&user_id=W111"
+ "&user_name=primary-owner"
+ "&command=%2Fhello-world"
+ "&text=Hi"
+ "&enterprise_id=E111"
+ "&enterprise_name=Org+Name"
+ "&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT111%2F111%2Fxxxxx"
+ "&trigger_id=111.111.xxx"
+ )
+
+ headers = self.build_raw_headers(str(int(time())), body)
+
+ wsgi_server = WsgiTestServer(SlackRequestHandler(app))
+
+ response = wsgi_server.http(method="POST", headers=headers, body=body)
+
+ assert response.status == "200 OK"
+ assert response.headers.get("content-type") == "text/plain;charset=utf-8"
+ assert_auth_test_count(self, 1)
+
+ def test_events(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+
+ def event_handler():
+ pass
+
+ app.event("app_mention")(event_handler)
+
+ body = json.dumps(
+ {
+ "token": "verification_token",
+ "team_id": "T111",
+ "enterprise_id": "E111",
+ "api_app_id": "A111",
+ "event": {
+ "client_msg_id": "9cbd4c5b-7ddf-4ede-b479-ad21fca66d63",
+ "type": "app_mention",
+ "text": "<@W111> Hi there!",
+ "user": "W222",
+ "ts": "1595926230.009600",
+ "team": "T111",
+ "channel": "C111",
+ "event_ts": "1595926230.009600",
+ },
+ "type": "event_callback",
+ "event_id": "Ev111",
+ "event_time": 1595926230,
+ "authed_users": ["W111"],
+ }
+ )
+ headers = self.build_raw_headers(str(int(time())), body)
+
+ wsgi_server = WsgiTestServer(SlackRequestHandler(app))
+ response = wsgi_server.http(method="POST", headers=headers, body=body)
+
+ assert response.status == "200 OK"
+ assert response.headers.get("content-type") == "text/plain;charset=utf-8"
+ assert_auth_test_count(self, 1)
+
+ def test_shortcuts(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+
+ def shortcut_handler(ack):
+ ack()
+
+ app.shortcut("test-shortcut")(shortcut_handler)
+
+ body_data = {
+ "type": "shortcut",
+ "token": "verification_token",
+ "action_ts": "111.111",
+ "team": {
+ "id": "T111",
+ "domain": "workspace-domain",
+ "enterprise_id": "E111",
+ "enterprise_name": "Org Name",
+ },
+ "user": {"id": "W111", "username": "primary-owner", "team_id": "T111"},
+ "callback_id": "test-shortcut",
+ "trigger_id": "111.111.xxxxxx",
+ }
+
+ body = f"payload={quote(json.dumps(body_data))}"
+ headers = self.build_raw_headers(str(int(time())), body)
+
+ wsgi_server = WsgiTestServer(SlackRequestHandler(app))
+ response = wsgi_server.http(method="POST", headers=headers, body=body)
+
+ assert response.status == "200 OK"
+ assert response.headers.get("content-type") == "text/plain;charset=utf-8"
+ assert_auth_test_count(self, 1)
+
+ def test_oauth(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ oauth_settings=OAuthSettings(
+ client_id="111.111",
+ client_secret="xxx",
+ scopes=["chat:write", "commands"],
+ ),
+ )
+
+ headers = self.build_raw_headers(str(int(time())))
+
+ wsgi_server = WsgiTestServer(SlackRequestHandler(app))
+ response = wsgi_server.http(method="GET", headers=headers, path="/slack/install")
+
+ assert response.status == "200 OK"
+ assert response.headers.get("content-type") == "text/html; charset=utf-8"
+ assert "https://slack.com/oauth/v2/authorize?state=" in response.body
+
+ def test_url_verification(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+
+ body_data = {
+ "token": "Jhj5dZrVaK7ZwHHjRyZWjbDl",
+ "challenge": "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P",
+ "type": "url_verification",
+ }
+
+ body = f"payload={quote(json.dumps(body_data))}"
+ headers = self.build_raw_headers(str(int(time())), body)
+
+ wsgi_server = WsgiTestServer(SlackRequestHandler(app))
+ response = wsgi_server.http(
+ method="POST",
+ headers=headers,
+ body=body,
+ )
+
+ assert response.status == "200 OK"
+ assert response.headers.get("content-type") == "application/json;charset=utf-8"
+ assert_auth_test_count(self, 1)
+
+ def test_unsupported_method(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+
+ body = ""
+ headers = self.build_raw_headers(str(int(time())), "")
+
+ wsgi_server = WsgiTestServer(SlackRequestHandler(app))
+ response = wsgi_server.http(method="PUT", headers=headers, body=body)
+
+ assert response.status == "404 Not Found"
+ assert response.headers.get("content-type") == "text/plain;charset=utf-8"
+ assert_auth_test_count(self, 1)
diff --git a/tests/mock_wsgi_server.py b/tests/mock_wsgi_server.py
new file mode 100644
index 000000000..a389a898e
--- /dev/null
+++ b/tests/mock_wsgi_server.py
@@ -0,0 +1,116 @@
+from typing import Dict, Iterable, Optional, Tuple
+
+from slack_bolt.adapter.wsgi import SlackRequestHandler
+
+ENCODING = "utf-8"
+
+
+class WsgiTestServerResponse:
+ def __init__(self):
+ self.status: Optional[str] = None
+ self._headers: Iterable[Tuple[str, str]] = []
+ self._body: Iterable[bytes] = []
+
+ @property
+ def headers(self) -> Dict[str, str]:
+ return {header[0]: header[1] for header in self._headers}
+
+ @property
+ def body(self, length: int = 0) -> str:
+ return "".join([chunk.decode(ENCODING) for chunk in self._body[length:]])
+
+
+class MockReadable:
+ def __init__(self, body: str):
+ self.body = body
+ self._body = bytes(body, ENCODING)
+
+ def get_content_length(self) -> int:
+ return len(self._body)
+
+ def read(self, size: int) -> bytes:
+ if size < 0:
+ raise ValueError("Size must be positive.")
+ if size == 0:
+ return b""
+ # The body can only be read once
+ _body = self._body[:size]
+ self._body = b""
+ return _body
+
+
+class WsgiTestServer:
+ def __init__(
+ self,
+ wsgi_app: SlackRequestHandler,
+ root_path: str = "",
+ version: Tuple[int, int] = (1, 0),
+ multithread: bool = False,
+ multiprocess: bool = False,
+ run_once: bool = False,
+ input_terminated: bool = True,
+ server_software: bool = "mock/0.0.0",
+ url_scheme: str = "https",
+ remote_addr: str = "127.0.0.1",
+ remote_port: str = "63263",
+ ):
+ self.root_path = root_path
+ self.wsgi_app = wsgi_app
+ self.environ = {
+ "wsgi.version": version,
+ "wsgi.multithread": multithread,
+ "wsgi.multiprocess": multiprocess,
+ "wsgi.run_once": run_once,
+ "wsgi.input_terminated": input_terminated,
+ "SERVER_SOFTWARE": server_software,
+ "wsgi.url_scheme": url_scheme,
+ "REMOTE_ADDR": remote_addr,
+ "REMOTE_PORT": remote_port,
+ }
+
+ def http(
+ self,
+ method: str,
+ headers: Dict[str, str],
+ body: Optional[str] = None,
+ path: str = "/slack/events",
+ query_string: str = "",
+ server_protocol: str = "HTTP/1.1",
+ server_name: str = "0.0.0.0",
+ server_port: str = "3000",
+ script_name: str = "",
+ ) -> WsgiTestServerResponse:
+ environ = dict(
+ self.environ,
+ **{
+ "REQUEST_METHOD": method,
+ "PATH_INFO": f"{self.root_path}{path}",
+ "QUERY_STRING": query_string,
+ "RAW_URI": f"{self.root_path}{path}?{query_string}",
+ "SERVER_PROTOCOL": server_protocol,
+ "SERVER_NAME": server_name,
+ "SERVER_PORT": server_port,
+ "SCRIPT_NAME": script_name,
+ },
+ )
+ for key, value in headers.items():
+ header_key = key.upper().replace("-", "_")
+ if header_key in {"CONTENT_LENGTH", "CONTENT_TYPE"}:
+ environ[header_key] = value
+ else:
+ environ[f"HTTP_{header_key}"] = value
+
+ if body is not None:
+ environ["wsgi.input"] = MockReadable(body)
+ if "CONTENT_LENGTH" not in environ:
+ environ["CONTENT_LENGTH"] = str(environ["wsgi.input"].get_content_length())
+
+ response = WsgiTestServerResponse()
+
+ def start_response(status, headers):
+ response.status = status
+ response._headers = headers
+
+ response._body = self.wsgi_app(environ=environ, start_response=start_response)
+
+ return response
| diff --git a/examples/wsgi/requirements.txt b/examples/wsgi/requirements.txt
new file mode 100644
index 000000000..5c3ac5752
--- /dev/null
+++ b/examples/wsgi/requirements.txt
@@ -0,0 +1,1 @@
+gunicorn<23
| [
{
"components": [
{
"doc": "",
"lines": [
8,
10
],
"name": "handle_app_mentions",
"signature": "def handle_app_mentions(body, say, logger):",
"type": "function"
}
],
"file": "examples/wsgi/app.py"
},
{
"components": ... | [
"tests/adapter_tests/wsgi/test_wsgi_http.py::TestWsgiHttp::test_commands",
"tests/adapter_tests/wsgi/test_wsgi_http.py::TestWsgiHttp::test_events",
"tests/adapter_tests/wsgi/test_wsgi_http.py::TestWsgiHttp::test_shortcuts",
"tests/adapter_tests/wsgi/test_wsgi_http.py::TestWsgiHttp::test_oauth",
"tests/adapt... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: add WSGI adapter
This PR introduced a WSGI adapter to bolt python, this will allow Bolt to be deployed in production without the need for an other WSGI compatible Web Framework like Flask
# Testing
1. Pull this branch
3. Use the `examples/wsgi/app.py` as starting point for a test app
4. Run `scripts/build_pypi_package.sh`
5. Use the `.whl` file found under `dist/` to run `pip install /path/to/dist/slack_bolt.whl`
6. Run `pip install gunicorn`
7. Run `gunicorn app:api -b 0.0.0.0:3000 --log-level debug` to start the application
### Category
* [ ] `slack_bolt.App` and/or its core components
* [ ] `slack_bolt.async_app.AsyncApp` and/or its core components
* [x] Adapters in `slack_bolt.adapter`
* [ ] Document pages under `/docs`
* [ ] Others
## Requirements
Please read the [Contributing guidelines](https://github.com/slackapi/bolt-python/blob/main/.github/contributing.md) and [Code of Conduct](https://slackhq.github.io/code-of-conduct) before creating this issue or pull request. By submitting, you are agreeing to those rules.
* [x] I've read and understood the [Contributing Guidelines](https://github.com/slackapi/bolt-python/blob/main/.github/contributing.md) and have done my best effort to follow them.
* [x] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct).
* [x] I've run `./scripts/install_all_and_run_tests.sh` after making 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 examples/wsgi/app.py]
(definition of handle_app_mentions:)
def handle_app_mentions(body, say, logger):
[end of new definitions in examples/wsgi/app.py]
[start of new definitions in examples/wsgi/oauth_app.py]
(definition of handle_app_mentions:)
def handle_app_mentions(body, say, logger):
[end of new definitions in examples/wsgi/oauth_app.py]
[start of new definitions in slack_bolt/adapter/wsgi/handler.py]
(definition of SlackRequestHandler:)
class SlackRequestHandler:
(definition of SlackRequestHandler.__init__:)
def __init__(self, app: App, path: str = "/slack/events"):
"""Setup Bolt as a WSGI web framework, this will make your application compatible with WSGI web servers.
This can be used for production deployments.
With the default settings, `http://localhost:3000/slack/events`
Run Bolt with [gunicorn](https://gunicorn.org/)
# Python
app = App()
api = SlackRequestHandler(app)
# bash
export SLACK_SIGNING_SECRET=***
export SLACK_BOT_TOKEN=xoxb-***
gunicorn app:api -b 0.0.0.0:3000 --log-level debug
Args:
app: Your bolt application
path: The path to handle request from Slack (Default: `/slack/events`)"""
(definition of SlackRequestHandler.dispatch:)
def dispatch(self, request: WsgiHttpRequest) -> BoltResponse:
(definition of SlackRequestHandler.handle_installation:)
def handle_installation(self, request: WsgiHttpRequest) -> BoltResponse:
(definition of SlackRequestHandler.handle_callback:)
def handle_callback(self, request: WsgiHttpRequest) -> BoltResponse:
(definition of SlackRequestHandler._get_http_response:)
def _get_http_response(self, request: WsgiHttpRequest) -> WsgiHttpResponse:
(definition of SlackRequestHandler.__call__:)
def __call__( self, environ: Dict[str, Any], start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]:
[end of new definitions in slack_bolt/adapter/wsgi/handler.py]
[start of new definitions in slack_bolt/adapter/wsgi/http_request.py]
(definition of WsgiHttpRequest:)
class WsgiHttpRequest:
"""This Class uses the PEP 3333 standard to extract request information
from the WSGI web server running the application
PEP 3333: https://peps.python.org/pep-3333/"""
(definition of WsgiHttpRequest.__init__:)
def __init__(self, environ: Dict[str, Any]):
(definition of WsgiHttpRequest.get_headers:)
def get_headers(self) -> Dict[str, str]:
(definition of WsgiHttpRequest.get_body:)
def get_body(self) -> str:
[end of new definitions in slack_bolt/adapter/wsgi/http_request.py]
[start of new definitions in slack_bolt/adapter/wsgi/http_response.py]
(definition of WsgiHttpResponse:)
class WsgiHttpResponse:
"""This Class uses the PEP 3333 standard to adapt bolt response information
for the WSGI web server running the application
PEP 3333: https://peps.python.org/pep-3333/"""
(definition of WsgiHttpResponse.__init__:)
def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""):
(definition of WsgiHttpResponse.get_headers:)
def get_headers(self) -> List[Tuple[str, str]]:
(definition of WsgiHttpResponse.get_body:)
def get_body(self) -> Iterable[bytes]:
[end of new definitions in slack_bolt/adapter/wsgi/http_response.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>> | dbe2333046b582c087fd19d6812c8a523835f53c | |
embeddings-benchmark__mteb-807 | 807 | embeddings-benchmark/mteb | null | 0ca3bc1219981af0c901b4918e78658453f3949b | 2024-05-24T10:25:59Z | diff --git a/docs/mmteb/points/807.jsonl b/docs/mmteb/points/807.jsonl
new file mode 100644
index 0000000000..ae60e6d5f0
--- /dev/null
+++ b/docs/mmteb/points/807.jsonl
@@ -0,0 +1,3 @@
+{"GitHub": "isaac-chung", "Review PR": 2}
+{"GitHub": "Muennighoff", "Review PR": 2}
+{"GitHub": "KennethEnevoldsen", "Bug fixes": 5}
\ No newline at end of file
diff --git a/mteb/__init__.py b/mteb/__init__.py
index 0fc38e6e7a..e6d4172ebf 100644
--- a/mteb/__init__.py
+++ b/mteb/__init__.py
@@ -10,6 +10,8 @@
from mteb.evaluation import *
from mteb.overview import TASKS_REGISTRY, get_task, get_tasks
+from .models import get_model, get_model_meta
+
__version__ = version("mteb") # fetch version from install metadata
@@ -20,4 +22,6 @@
"TASKS_REGISTRY",
"get_tasks",
"get_task",
+ "get_model",
+ "get_model_meta",
]
diff --git a/mteb/model_meta.py b/mteb/model_meta.py
new file mode 100644
index 0000000000..ca17af020c
--- /dev/null
+++ b/mteb/model_meta.py
@@ -0,0 +1,78 @@
+from __future__ import annotations
+
+from datetime import date
+from functools import partial
+from typing import Any, Callable, Literal
+
+from pydantic import BaseModel, BeforeValidator, TypeAdapter
+from sentence_transformers import SentenceTransformer
+from typing_extensions import Annotated
+
+from mteb.encoder_interface import Encoder, EncoderWithQueryCorpusEncode
+
+from .languages import ISO_LANGUAGE_SCRIPT
+
+Frameworks = Literal["Sentence Transformers", "PyTorch"]
+
+pastdate_adapter = TypeAdapter(date)
+STR_DATE = Annotated[
+ str, BeforeValidator(lambda value: str(pastdate_adapter.validate_python(value)))
+] # Allows the type to be a string, but ensures that the string is a valid date
+
+
+def sentence_transformers_loader(model_name: str, revision: str) -> SentenceTransformer:
+ return SentenceTransformer(model_name_or_path=model_name, revision=revision)
+
+
+class ModelMeta(BaseModel):
+ """The model metadata object.
+
+ Attributes:
+ loader: the function that loads the model. If None it will just default to loading the model using the sentence transformer library.
+ name: The name of the model, ideally the name on huggingface.
+ n_parameters: The number of parameters in the model, e.g. 7_000_000 for a 7M parameter model. Can be None if the the number of parameters is not known (e.g. for proprietary models) or
+ if the loader returns a SentenceTransformer model from which it can be derived.
+ memory_usage: The amount of memory the model uses in GB. Can be None if the memory usage is not known (e.g. for proprietary models).
+ max_tokens: The maximum number of tokens the model can handle. Can be None if the maximum number of tokens is not known (e.g. for proprietary
+ models).
+ embed_dim: The dimension of the embeddings produced by the model. Currently all models are assumed to produce fixed-size embeddings.
+ revision: The revision number of the model.
+ release_date: The date the model's revision was released.
+ license: The license under which the model is released. Required if open_source is True.
+ open_source: Whether the model is open source or proprietary.
+ framework: The framework the model is implemented in, can be a list of frameworks e.g. `["Sentence Transformers", "PyTorch"]`.
+ languages: The languages the model is intended for specified as a 3 letter language code followed by a script code e.g. "eng-Latn" for English
+ in the Latin script.
+ """
+
+ name: str
+ revision: str
+ release_date: STR_DATE
+ languages: list[ISO_LANGUAGE_SCRIPT]
+ loader: Callable[..., Encoder | EncoderWithQueryCorpusEncode] | None = None
+ n_parameters: int | None = None
+ memory_usage: float | None = None
+ max_tokens: int | None = None
+ embed_dim: int | None = None
+ license: str | None = None
+ open_source: bool | None = None
+ framework: list[Frameworks] = []
+
+ def to_dict(self):
+ dict_repr = self.model_dump()
+ loader = dict_repr.pop("loader", None)
+ dict_repr["loader"] = loader.__name__ if loader is not None else None
+ return dict_repr
+
+ def load_model(self, **kwargs: Any) -> Encoder | EncoderWithQueryCorpusEncode:
+ if self.loader is None:
+ loader = partial(
+ sentence_transformers_loader,
+ model_name=self.name,
+ revision=self.revision,
+ )
+ else:
+ loader = self.loader
+
+ model: Encoder | EncoderWithQueryCorpusEncode = loader(**kwargs) # type: ignore
+ return model
diff --git a/mteb/models/__init__.py b/mteb/models/__init__.py
new file mode 100644
index 0000000000..859e76b5d7
--- /dev/null
+++ b/mteb/models/__init__.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from mteb.encoder_interface import Encoder, EncoderWithQueryCorpusEncode
+from mteb.model_meta import ModelMeta
+
+from . import sentence_transformers_models
+
+
+def get_model(model_name: str) -> Encoder | EncoderWithQueryCorpusEncode:
+ """A function to fetch a model object by name.
+
+ Args:
+ model_name: Name of the model to fetch
+
+ Returns:
+ A model object
+ """
+ return models[model_name].load_model()
+
+
+def get_model_meta(model_name: str) -> ModelMeta:
+ """A function to fetch a model metadata object by name.
+
+ Args:
+ model_name: Name of the model to fetch
+
+ Returns:
+ A model metadata object
+ """
+ return models[model_name]
+
+
+model_modules = [sentence_transformers_models]
+models = {}
+
+
+for module in model_modules:
+ for mdl in module.__dict__.values():
+ if isinstance(mdl, ModelMeta):
+ models[mdl.name] = mdl
diff --git a/mteb/models/sentence_transformers_models.py b/mteb/models/sentence_transformers_models.py
new file mode 100644
index 0000000000..df289d6213
--- /dev/null
+++ b/mteb/models/sentence_transformers_models.py
@@ -0,0 +1,11 @@
+"""Implementation of Sentence Transformers model validated in MTEB."""
+
+from mteb.model_meta import ModelMeta
+
+ALL_MINILM_L6_V2 = ModelMeta(
+ name="sentence-transformers/all-MiniLM-L6-v2",
+ languages=["eng-Latn"],
+ open_source=True,
+ revision="e4ce9877abf3edfe10b0d82785e83bdcb973e22e",
+ release_date="2021-08-30",
+)
| diff --git a/tests/test_reproducible_workflow.py b/tests/test_reproducible_workflow.py
new file mode 100644
index 0000000000..ddc3dace57
--- /dev/null
+++ b/tests/test_reproducible_workflow.py
@@ -0,0 +1,29 @@
+from __future__ import annotations
+
+import logging
+
+import pytest
+
+import mteb
+from mteb import MTEB
+from mteb.encoder_interface import Encoder, EncoderWithQueryCorpusEncode
+from mteb.model_meta import ModelMeta
+
+logging.basicConfig(level=logging.INFO)
+
+
+@pytest.mark.parametrize("task_name", ["BornholmBitextMining"])
+@pytest.mark.parametrize("model_name", ["sentence-transformers/all-MiniLM-L6-v2"])
+def test_reproducibility_workflow(task_name: str, model_name: str):
+ """Test that a model and a task can be fetched and run in a reproducible fashion."""
+ model_meta = mteb.get_model_meta(model_name)
+ task = mteb.get_task(task_name)
+
+ assert isinstance(model_meta, ModelMeta)
+ assert isinstance(task, mteb.AbsTask)
+
+ model = mteb.get_model(model_name)
+ assert isinstance(model, (Encoder, EncoderWithQueryCorpusEncode))
+
+ eval = MTEB(tasks=[task])
+ eval.run(model, output_folder="tests/results", overwrite_results=True)
| diff --git a/docs/mmteb/points/807.jsonl b/docs/mmteb/points/807.jsonl
new file mode 100644
index 0000000000..ae60e6d5f0
--- /dev/null
+++ b/docs/mmteb/points/807.jsonl
@@ -0,0 +1,3 @@
+{"GitHub": "isaac-chung", "Review PR": 2}
+{"GitHub": "Muennighoff", "Review PR": 2}
+{"GitHub": "KennethEnevoldsen", "Bug fixes": 5}
\ No newline at end of file
| [
{
"components": [
{
"doc": "",
"lines": [
23,
24
],
"name": "sentence_transformers_loader",
"signature": "def sentence_transformers_loader(model_name: str, revision: str) -> SentenceTransformer:",
"type": "function"
},
{
... | [
"tests/test_reproducible_workflow.py::test_reproducibility_workflow[sentence-transformers/all-MiniLM-L6-v2-BornholmBitextMining]"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
add model meta to create reproducible workflow
- Add outline for model meta object
- Added a single model as a an example
- Added test for the reproducible workflow
The intention is that a reproducible workflow should then look like:
```python
# assuming the same mteb and sent. trf. version
model_meta = mteb.get_model(model_name)
task = mteb.get_task(task_name)
model = model_meta.load_model() # load model either using custom loader or sentence transformer (with revision)
eval = MTEB(tasks=[task])
eval.run(model, output_folder="tests/results", overwrite_results=True)
```
For running models we can the simply have tasks like:
1) implement model
2) ensures that it runs on all tasks types
Running the models then become simple:
```python
eval = MTEB(tasks=mteb.get_tasks())
for mdl_name in models:
model_meta = mteb.get_model(mdl_name)
mdl = model_meta.load_model()
eval.run(mdl)
```
We can start with this already now e.g. on classification tasks.
<!-- If you are not submitting for a dataset, feel free to remove the content below -->
<!-- add additional description, question etc. related to the new dataset -->
## Checklist for adding MMTEB dataset
<!--
Before you commit here is a checklist you should complete before submitting
if you are not
-->
Reason for dataset addition:
<!-- Add reason for adding dataset here. E.g. it covers task/language/domain previously not covered -->
- [ ] I have tested that the dataset runs with the `mteb` package.
- [ ] I have run the following models on the task (adding the results to the pr). These can be run using the `mteb -m {model_name} -t {task_name}` command.
- [ ] `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2`
- [ ] `intfloat/multilingual-e5-small`
- [ ] I have checked that the performance is neither trivial (both models gain close to perfect scores) nor random (both models gain close to random scores).
- [ ] If the dataset is too big (e.g. >2048 examples), considering using `self.stratified_subsampling() under dataset_transform()`
- [ ] I have filled out the metadata object in the dataset file (find documentation on it [here](https://github.com/embeddings-benchmark/mteb/blob/main/docs/adding_a_dataset.md#2-creating-the-metadata-object)).
- [ ] Run tests locally to make sure nothing is broken using `make test`.
- [ ] Run the formatter to format the code using `make lint`.
- [ ] I have added points for my submission to the [points folder](https://github.com/embeddings-benchmark/mteb/blob/main/docs/mmteb/points.md) using the PR number as the filename (e.g. `438.jsonl`).
----------
</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/model_meta.py]
(definition of sentence_transformers_loader:)
def sentence_transformers_loader(model_name: str, revision: str) -> SentenceTransformer:
(definition of ModelMeta:)
class ModelMeta(BaseModel):
"""The model metadata object.
Attributes:
loader: the function that loads the model. If None it will just default to loading the model using the sentence transformer library.
name: The name of the model, ideally the name on huggingface.
n_parameters: The number of parameters in the model, e.g. 7_000_000 for a 7M parameter model. Can be None if the the number of parameters is not known (e.g. for proprietary models) or
if the loader returns a SentenceTransformer model from which it can be derived.
memory_usage: The amount of memory the model uses in GB. Can be None if the memory usage is not known (e.g. for proprietary models).
max_tokens: The maximum number of tokens the model can handle. Can be None if the maximum number of tokens is not known (e.g. for proprietary
models).
embed_dim: The dimension of the embeddings produced by the model. Currently all models are assumed to produce fixed-size embeddings.
revision: The revision number of the model.
release_date: The date the model's revision was released.
license: The license under which the model is released. Required if open_source is True.
open_source: Whether the model is open source or proprietary.
framework: The framework the model is implemented in, can be a list of frameworks e.g. `["Sentence Transformers", "PyTorch"]`.
languages: The languages the model is intended for specified as a 3 letter language code followed by a script code e.g. "eng-Latn" for English
in the Latin script."""
(definition of ModelMeta.to_dict:)
def to_dict(self):
(definition of ModelMeta.load_model:)
def load_model(self, **kwargs: Any) -> Encoder | EncoderWithQueryCorpusEncode:
[end of new definitions in mteb/model_meta.py]
[start of new definitions in mteb/models/__init__.py]
(definition of get_model:)
def get_model(model_name: str) -> Encoder | EncoderWithQueryCorpusEncode:
"""A function to fetch a model object by name.
Args:
model_name: Name of the model to fetch
Returns:
A model object"""
(definition of get_model_meta:)
def get_model_meta(model_name: str) -> ModelMeta:
"""A function to fetch a model metadata object by name.
Args:
model_name: Name of the model to fetch
Returns:
A model metadata object"""
[end of new definitions in mteb/models/__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>> | b580b95fc91a7e7e675d27c3ae9a9df64ddad169 | |
googleapis__python-aiplatform-3831 | 3,831 | googleapis/python-aiplatform | null | 09b3e028cb2c075d4a12e8cdbb9c1616c10c63ed | 2024-05-23T23:25:46Z | diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 542bbbea25..bb358f0808 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,3 +1,3 @@
{
- ".": "1.56.0"
+ ".": "1.55.0"
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8b06132ad..1fdeacfff5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,29 +1,5 @@
# Changelog
-## [1.56.0](https://github.com/googleapis/python-aiplatform/compare/v1.55.0...v1.56.0) (2024-06-18)
-
-
-### Features
-
-* Add `retry_timeout` to EvalTask in `vertexai.preview.evaluation` ([4d9ee9d](https://github.com/googleapis/python-aiplatform/commit/4d9ee9dc6c046fd71e2f3176981a2a108fbbaeeb))
-* Add hybrid query example to vector search sample. ([510da5e](https://github.com/googleapis/python-aiplatform/commit/510da5ef3bcaa507288571fc7e066f578fde329f))
-* Add metric classes for 2 pairwise metrics for rapid evaluation SDK. ([831c8e4](https://github.com/googleapis/python-aiplatform/commit/831c8e45ee88f70efcdaba7dfed1856837074357))
-* Add pipeline_job_name to allow PipelineJob.get(pipeline_job_name) ([32e3b22](https://github.com/googleapis/python-aiplatform/commit/32e3b22993a83414ee60e52b0c95bd8b63543787))
-* Add sample code show how to create an optimized private online store in Vertex AI Feature Store. ([e352175](https://github.com/googleapis/python-aiplatform/commit/e3521751ecb79d5f711658c39d2dd5b204c191c5))
-* GenAI - Context Caching - add get() classmethod and refresh() instance method ([6be874a](https://github.com/googleapis/python-aiplatform/commit/6be874a7c6c43b7acbf5926e38e56d2ab367f5a1))
-* GenAI - Context Caching - also print model_name and expire_time. ([d548c11](https://github.com/googleapis/python-aiplatform/commit/d548c1128d8b6abc7ed8007436bc868a688fcace))
-* GenAI - Tuning - Added support for CMEK ([eb651bc](https://github.com/googleapis/python-aiplatform/commit/eb651bc2ed60ba12d88998115470c12d858892ef))
-
-
-### Bug Fixes
-
-* Do not reset aiplatform.Experiment or aiplatform.ExperimentRun unnecessarily when running tensorboard uploader. ([28a091a](https://github.com/googleapis/python-aiplatform/commit/28a091ab609ae3c086bb35ee4901c61108a4e75e))
-
-
-### Documentation
-
-* Update the documentation for the `time_series_dataset` and `video_dataset` classes ([d5dc7b5](https://github.com/googleapis/python-aiplatform/commit/d5dc7b5697eb4c7e86ec9e108454a30c8c7028d7))
-
## [1.55.0](https://github.com/googleapis/python-aiplatform/compare/v1.54.1...v1.55.0) (2024-06-12)
diff --git a/google/cloud/aiplatform/gapic_version.py b/google/cloud/aiplatform/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/gapic_version.py
+++ b/google/cloud/aiplatform/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/models.py b/google/cloud/aiplatform/models.py
index 86f60db044..12c65b82f7 100644
--- a/google/cloud/aiplatform/models.py
+++ b/google/cloud/aiplatform/models.py
@@ -23,6 +23,7 @@
from typing import (
Any,
Dict,
+ Iterator,
List,
NamedTuple,
Optional,
@@ -233,6 +234,7 @@ def __init__(
self.authorized_session = None
self.raw_predict_request_url = None
+ self.stream_raw_predict_request_url = None
@property
def _prediction_client(self) -> utils.PredictionClientWithOverride:
@@ -618,6 +620,7 @@ def _construct_sdk_resource_from_gapic(
)
endpoint.authorized_session = None
endpoint.raw_predict_request_url = None
+ endpoint.stream_raw_predict_request_url = None
return endpoint
@@ -1722,15 +1725,381 @@ def raw_predict(
"""
if not self.authorized_session:
self.credentials._scopes = constants.base.DEFAULT_AUTHED_SCOPES
- self.raw_predict_request_url = f"https://{self.location}-{constants.base.API_BASE_PATH}/v1/projects/{self.project}/locations/{self.location}/endpoints/{self.name}:rawPredict"
self.authorized_session = google_auth_requests.AuthorizedSession(
self.credentials
)
+ if self.raw_predict_request_url is None:
+ self.raw_predict_request_url = f"https://{self.location}-{constants.base.API_BASE_PATH}/v1/projects/{self.project}/locations/{self.location}/endpoints/{self.name}:rawPredict"
+
return self.authorized_session.post(
url=self.raw_predict_request_url, data=body, headers=headers
)
+ def stream_raw_predict(
+ self, body: bytes, headers: Dict[str, str]
+ ) -> Iterator[requests.models.Response]:
+ """Makes a streaming prediction request using arbitrary headers.
+
+ Example usage:
+ ```
+ my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)
+ for stream_response in my_endpoint.stream_raw_predict(
+ body = b'{"instances":[{"feat_1":val_1, "feat_2":val_2}]}'
+ headers = {'Content-Type':'application/json'}
+ ):
+ status_code = response.status_code
+ stream_result = json.dumps(response.text)
+ ```
+
+ Args:
+ body (bytes):
+ The body of the prediction request in bytes. This must not
+ exceed 10 mb per request.
+ headers (Dict[str, str]):
+ The header of the request as a dictionary. There are no
+ restrictions on the header.
+
+ Yields:
+ predictions (Iterator[requests.models.Response]):
+ The streaming prediction results.
+ """
+ if not self.authorized_session:
+ self.credentials._scopes = constants.base.DEFAULT_AUTHED_SCOPES
+ self.authorized_session = google_auth_requests.AuthorizedSession(
+ self.credentials
+ )
+
+ if self.stream_raw_predict_request_url is None:
+ self.stream_raw_predict_request_url = f"https://{self.location}-{constants.base.API_BASE_PATH}/v1/projects/{self.project}/locations/{self.location}/endpoints/{self.name}:streamRawPredict"
+
+ with self.authorized_session.post(
+ url=self.stream_raw_predict_request_url,
+ data=body,
+ headers=headers,
+ stream=True,
+ ) as resp:
+ for line in resp.iter_lines():
+ yield line
+
+ def direct_predict(
+ self,
+ inputs: List,
+ parameters: Optional[Dict] = None,
+ timeout: Optional[float] = None,
+ ) -> Prediction:
+ """Makes a direct (gRPC) prediction against this Endpoint for a pre-built image.
+
+ Args:
+ inputs (List):
+ Required. The inputs that are the input to the prediction call.
+ A DeployedModel may have an upper limit on the number of
+ instances it supports per request, and when it is exceeded the
+ prediction call errors in case of AutoML Models, or, in case of
+ customer created Models, the behaviour is as documented by that
+ Model. The schema of any single instance may be specified via
+ Endpoint's DeployedModels'
+ [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
+ [PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
+ ``instance_schema_uri``.
+ parameters (Dict):
+ Optional. The parameters that govern the prediction. The schema
+ of the parameters may be specified via Endpoint's
+ DeployedModels'
+ [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
+ [PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
+ ``parameters_schema_uri``.
+ timeout (Optional[float]):
+ Optional. The timeout for this request in seconds.
+
+ Returns:
+ prediction (aiplatform.Prediction):
+ The resulting prediction.
+ """
+ self.wait()
+
+ prediction_response = self._prediction_client.direct_predict(
+ request={
+ "endpoint": self._gca_resource.name,
+ "inputs": inputs,
+ "parameters": parameters,
+ },
+ timeout=timeout,
+ )
+
+ return Prediction(
+ predictions=[
+ json_format.MessageToDict(item)
+ for item in prediction_response.outputs.pb
+ ],
+ metadata=None,
+ deployed_model_id=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ async def direct_predict_async(
+ self,
+ inputs: List,
+ *,
+ parameters: Optional[Dict] = None,
+ timeout: Optional[float] = None,
+ ) -> Prediction:
+ """Makes an asynchronous direct (gRPC) prediction against this Endpoint for a pre-built image.
+
+ Example usage:
+ ```
+ response = await my_endpoint.direct_predict_async(inputs=[...])
+ my_predictions = response.predictions
+ ```
+
+ Args:
+ inputs (List):
+ Required. The inputs that are the input to the prediction call.
+ A DeployedModel may have an upper limit on the number of
+ instances it supports per request, and when it is exceeded the
+ prediction call errors in case of AutoML Models, or, in case of
+ customer created Models, the behaviour is as documented by that
+ Model. The schema of any single instance may be specified via
+ Endpoint's DeployedModels'
+ [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
+ [PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
+ ``instance_schema_uri``.
+ parameters (Dict):
+ Optional. The parameters that govern the prediction. The schema
+ of the parameters may be specified via Endpoint's
+ DeployedModels'
+ [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
+ [PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
+ ``parameters_schema_uri``.
+ timeout (Optional[float]):
+ Optional. The timeout for this request in seconds.
+
+ Returns:
+ prediction (aiplatform.Prediction):
+ The resulting prediction.
+ """
+ self.wait()
+
+ prediction_response = await self._prediction_async_client.direct_predict(
+ request={
+ "endpoint": self._gca_resource.name,
+ "inputs": inputs,
+ "parameters": parameters,
+ },
+ timeout=timeout,
+ )
+
+ return Prediction(
+ predictions=[
+ json_format.MessageToDict(item)
+ for item in prediction_response.outputs.pb
+ ],
+ metadata=None,
+ deployed_model_id=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ def stream_direct_predict(
+ self,
+ inputs_iterator: Iterator[List],
+ parameters: Optional[Dict] = None,
+ timeout: Optional[float] = None,
+ ) -> Iterator[Prediction]:
+ """Makes a streaming direct (gRPC) prediction against this Endpoint for a pre-built image.
+
+ Args:
+ inputs_iterator (Iterator[List]):
+ Required. An iterator of the inputs that are the input to the
+ prediction call. A DeployedModel may have an upper limit on the
+ number of instances it supports per request, and when it is
+ exceeded the prediction call errors in case of AutoML Models, or,
+ in case of customer created Models, the behaviour is as
+ documented by that Model. The schema of any single instance may
+ be specified via Endpoint's DeployedModels'
+ [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
+ [PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
+ ``instance_schema_uri``.
+ parameters (Dict):
+ Optional. The parameters that govern the prediction. The schema
+ of the parameters may be specified via Endpoint's
+ DeployedModels'
+ [Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
+ [PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
+ ``parameters_schema_uri``.
+ timeout (Optional[float]):
+ Optional. The timeout for this request in seconds.
+
+ Yields:
+ predictions (Iterator[aiplatform.Prediction]):
+ The resulting streamed predictions.
+ """
+ self.wait()
+ for resp in self._prediction_client.stream_direct_predict(
+ requests=(
+ {
+ "endpoint": self._gca_resource.name,
+ "inputs": inputs,
+ "parameters": parameters,
+ }
+ for inputs in inputs_iterator
+ ),
+ timeout=timeout,
+ ):
+ yield Prediction(
+ predictions=[
+ json_format.MessageToDict(item) for item in resp.outputs.pb
+ ],
+ metadata=None,
+ deployed_model_id=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ def direct_raw_predict(
+ self,
+ method_name: str,
+ request: bytes,
+ timeout: Optional[float] = None,
+ ) -> Prediction:
+ """Makes a direct (gRPC) prediction request using arbitrary headers for a custom container.
+
+ Example usage:
+ ```
+ my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)
+ response = my_endpoint.direct_raw_predict(request=b'...')
+ ```
+
+ Args:
+ method_name (str):
+ Fully qualified name of the API method being invoked to perform
+ prediction.
+ request (bytes):
+ The body of the prediction request in bytes.
+ timeout (Optional[float]):
+ Optional. The timeout for this request in seconds.
+
+ Returns:
+ prediction (aiplatform.Prediction):
+ The resulting prediction.
+ """
+ self.wait()
+
+ prediction_response = self._prediction_client.direct_raw_predict(
+ request={
+ "endpoint": self._gca_resource.name,
+ "method_name": method_name,
+ "input": request,
+ },
+ timeout=timeout,
+ )
+
+ return Prediction(
+ predictions=prediction_response.output,
+ metadata=None,
+ deployed_model_id=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ async def direct_raw_predict_async(
+ self,
+ method_name: str,
+ request: bytes,
+ timeout: Optional[float] = None,
+ ) -> Prediction:
+ """Makes a direct (gRPC) prediction request for a custom container.
+
+ Example usage:
+ ```
+ my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)
+ response = await my_endpoint.direct_raw_predict(request=b'...')
+ ```
+
+ Args:
+ method_name (str):
+ Fully qualified name of the API method being invoked to perform
+ prediction.
+ request (bytes):
+ The body of the prediction request in bytes.
+ timeout (Optional[float]):
+ Optional. The timeout for this request in seconds.
+
+ Returns:
+ prediction (aiplatform.Prediction):
+ The resulting prediction.
+ """
+ self.wait()
+
+ prediction_response = await self._prediction_async_client.direct_raw_predict(
+ request={
+ "endpoint": self._gca_resource.name,
+ "method_name": method_name,
+ "input": request,
+ },
+ timeout=timeout,
+ )
+
+ return Prediction(
+ predictions=prediction_response.output,
+ metadata=None,
+ deployed_model_id=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ def stream_direct_raw_predict(
+ self,
+ method_name: str,
+ requests: Iterator[bytes],
+ timeout: Optional[float] = None,
+ ) -> Iterator[Prediction]:
+ """Makes a direct (gRPC) streaming prediction request for a custom container.
+
+ Example usage:
+ ```
+ my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)
+ for stream_response in my_endpoint.stream_direct_raw_predict(
+ request=b'...'
+ ):
+ yield stream_response
+ ```
+
+ Args:
+ method_name (str):
+ Fully qualified name of the API method being invoked to perform
+ prediction.
+ requests (Iterator[bytes]):
+ The body of the prediction requests in bytes.
+ timeout (Optional[float]):
+ Optional. The timeout for this request in seconds.
+
+ Yields:
+ predictions (Iterator[aiplatform.Prediction]):
+ The resulting streamed predictions.
+ """
+ self.wait()
+
+ for resp in self._prediction_client.stream_direct_raw_predict(
+ requests=(
+ {
+ "endpoint": self._gca_resource.name,
+ "method_name": method_name,
+ "input": request,
+ }
+ for request in requests
+ ),
+ timeout=timeout,
+ ):
+ yield Prediction(
+ predictions=resp.output,
+ metadata=None,
+ deployed_model_id=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
def explain(
self,
instances: List[Dict],
diff --git a/google/cloud/aiplatform/v1/schema/predict/instance/gapic_version.py b/google/cloud/aiplatform/v1/schema/predict/instance/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/predict/instance/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/predict/instance/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1/schema/predict/instance_v1/gapic_version.py b/google/cloud/aiplatform/v1/schema/predict/instance_v1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/predict/instance_v1/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/predict/instance_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1/schema/predict/params/gapic_version.py b/google/cloud/aiplatform/v1/schema/predict/params/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/predict/params/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/predict/params/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1/schema/predict/params_v1/gapic_version.py b/google/cloud/aiplatform/v1/schema/predict/params_v1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/predict/params_v1/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/predict/params_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1/schema/predict/prediction/gapic_version.py b/google/cloud/aiplatform/v1/schema/predict/prediction/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/predict/prediction/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/predict/prediction/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1/schema/predict/prediction_v1/gapic_version.py b/google/cloud/aiplatform/v1/schema/predict/prediction_v1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/predict/prediction_v1/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/predict/prediction_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1/schema/trainingjob/definition/gapic_version.py b/google/cloud/aiplatform/v1/schema/trainingjob/definition/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/trainingjob/definition/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/trainingjob/definition/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1/schema/trainingjob/definition_v1/gapic_version.py b/google/cloud/aiplatform/v1/schema/trainingjob/definition_v1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1/schema/trainingjob/definition_v1/gapic_version.py
+++ b/google/cloud/aiplatform/v1/schema/trainingjob/definition_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/predict/instance/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/predict/instance/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/predict/instance/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/predict/instance/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/predict/instance_v1beta1/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/predict/instance_v1beta1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/predict/instance_v1beta1/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/predict/instance_v1beta1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/predict/params/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/predict/params/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/predict/params/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/predict/params/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/predict/params_v1beta1/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/predict/params_v1beta1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/predict/params_v1beta1/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/predict/params_v1beta1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/predict/prediction/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/predict/prediction/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/predict/prediction/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/predict/prediction/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/predict/prediction_v1beta1/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/predict/prediction_v1beta1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/predict/prediction_v1beta1/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/predict/prediction_v1beta1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition_v1beta1/gapic_version.py b/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition_v1beta1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition_v1beta1/gapic_version.py
+++ b/google/cloud/aiplatform/v1beta1/schema/trainingjob/definition_v1beta1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform/version.py b/google/cloud/aiplatform/version.py
index 7be4372eb1..1b6e78fc8e 100644
--- a/google/cloud/aiplatform/version.py
+++ b/google/cloud/aiplatform/version.py
@@ -15,4 +15,4 @@
# limitations under the License.
#
-__version__ = "1.56.0"
+__version__ = "1.55.0"
diff --git a/google/cloud/aiplatform_v1/gapic_version.py b/google/cloud/aiplatform_v1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform_v1/gapic_version.py
+++ b/google/cloud/aiplatform_v1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/google/cloud/aiplatform_v1beta1/gapic_version.py b/google/cloud/aiplatform_v1beta1/gapic_version.py
index 948d563c27..e5a03373b2 100644
--- a/google/cloud/aiplatform_v1beta1/gapic_version.py
+++ b/google/cloud/aiplatform_v1beta1/gapic_version.py
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-__version__ = "1.56.0" # {x-release-please-version}
+__version__ = "1.55.0" # {x-release-please-version}
diff --git a/pypi/_vertex_ai_placeholder/version.py b/pypi/_vertex_ai_placeholder/version.py
index 331922c846..d4b2dd619d 100644
--- a/pypi/_vertex_ai_placeholder/version.py
+++ b/pypi/_vertex_ai_placeholder/version.py
@@ -15,4 +15,4 @@
# limitations under the License.
#
-__version__ = "1.56.0"
+__version__ = "1.55.0"
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json
index 4769e1be18..3162187456 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-aiplatform",
- "version": "1.56.0"
+ "version": "1.55.0"
},
"snippets": [
{
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json
index 53a4e1a5e2..2426d3ae1c 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-aiplatform",
- "version": "1.56.0"
+ "version": "1.55.0"
},
"snippets": [
{
| diff --git a/tests/unit/aiplatform/test_endpoints.py b/tests/unit/aiplatform/test_endpoints.py
index 5b725d8728..4185594440 100644
--- a/tests/unit/aiplatform/test_endpoints.py
+++ b/tests/unit/aiplatform/test_endpoints.py
@@ -95,6 +95,11 @@
_TEST_METADATA = {"foo": "bar"}
_TEST_PREDICTION = test_constants.EndpointConstants._TEST_PREDICTION
_TEST_INSTANCES = [[1.0, 2.0, 3.0], [1.0, 3.0, 4.0]]
+_TEST_RAW_INPUTS = b"input bytes"
+_TEST_RAW_OUTPUTS = b"output bytes"
+_TEST_INPUTS = [{"dtype": "BOOL"}]
+_TEST_OUTPUTS = [{"dtype": "STRING"}]
+_TEST_METHOD_NAME = "test-method-name"
_TEST_CREDENTIALS = mock.Mock(spec=auth_credentials.AnonymousCredentials())
_TEST_SERVICE_ACCOUNT = test_constants.ProjectConstants._TEST_SERVICE_ACCOUNT
@@ -522,6 +527,78 @@ def predict_async_client_predict_mock():
yield predict_mock
+@pytest.fixture
+def predict_client_direct_predict_mock():
+ with mock.patch.object(
+ prediction_service_client.PredictionServiceClient, "direct_predict"
+ ) as direct_predict_mock:
+ direct_predict_mock.return_value = gca_prediction_service.DirectPredictResponse(
+ outputs=_TEST_OUTPUTS
+ )
+ yield direct_predict_mock
+
+
+@pytest.fixture
+def predict_client_direct_predict_async_mock():
+ response = gca_prediction_service.DirectPredictResponse(outputs=_TEST_OUTPUTS)
+ with mock.patch.object(
+ target=prediction_service_async_client.PredictionServiceAsyncClient,
+ attribute="direct_predict",
+ return_value=response,
+ ) as direct_predict_mock:
+ yield direct_predict_mock
+
+
+@pytest.fixture
+def predict_client_direct_raw_predict_mock():
+ with mock.patch.object(
+ prediction_service_client.PredictionServiceClient, "direct_raw_predict"
+ ) as direct_raw_predict_mock:
+ direct_raw_predict_mock.return_value = (
+ gca_prediction_service.DirectRawPredictResponse(output=_TEST_RAW_OUTPUTS)
+ )
+ yield direct_raw_predict_mock
+
+
+@pytest.fixture
+def predict_client_direct_raw_predict_async_mock():
+ response = gca_prediction_service.DirectRawPredictResponse(output=_TEST_RAW_OUTPUTS)
+ with mock.patch.object(
+ target=prediction_service_async_client.PredictionServiceAsyncClient,
+ attribute="direct_raw_predict",
+ return_value=response,
+ ) as direct_raw_predict_mock:
+ yield direct_raw_predict_mock
+
+
+@pytest.fixture
+def predict_client_stream_direct_predict_mock():
+ with mock.patch.object(
+ prediction_service_client.PredictionServiceClient, "stream_direct_predict"
+ ) as stream_direct_predict_mock:
+ stream_direct_predict_mock.return_value = (
+ gca_prediction_service.StreamDirectPredictResponse(outputs=_TEST_OUTPUTS),
+ gca_prediction_service.StreamDirectPredictResponse(outputs=_TEST_OUTPUTS),
+ )
+ yield stream_direct_predict_mock
+
+
+@pytest.fixture
+def predict_client_stream_direct_raw_predict_mock():
+ with mock.patch.object(
+ prediction_service_client.PredictionServiceClient, "stream_direct_raw_predict"
+ ) as stream_direct_raw_predict_mock:
+ stream_direct_raw_predict_mock.return_value = (
+ gca_prediction_service.StreamDirectRawPredictResponse(
+ output=_TEST_RAW_OUTPUTS
+ ),
+ gca_prediction_service.StreamDirectRawPredictResponse(
+ output=_TEST_RAW_OUTPUTS
+ ),
+ )
+ yield stream_direct_raw_predict_mock
+
+
@pytest.fixture
def predict_client_explain_mock():
with mock.patch.object(
@@ -2149,6 +2226,394 @@ def test_predict_with_timeout_not_explicitly_set(self, predict_client_predict_mo
timeout=None,
)
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_direct_predict(self, predict_client_direct_predict_mock):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = test_endpoint.direct_predict(inputs=_TEST_INPUTS)
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_predict_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "inputs": _TEST_INPUTS,
+ "parameters": None,
+ },
+ timeout=None,
+ )
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_direct_predict_with_parameters(self, predict_client_direct_predict_mock):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = test_endpoint.direct_predict(
+ inputs=_TEST_INPUTS, parameters={"param": 3.0}
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_predict_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "inputs": _TEST_INPUTS,
+ "parameters": {"param": 3.0},
+ },
+ timeout=None,
+ )
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_direct_predict_with_timeout(self, predict_client_direct_predict_mock):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = test_endpoint.direct_predict(
+ inputs=_TEST_INPUTS, timeout=10.0
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_predict_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "inputs": _TEST_INPUTS,
+ "parameters": None,
+ },
+ timeout=10.0,
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ async def test_direct_predict_async(self, predict_client_direct_predict_async_mock):
+ """Tests the Endpoint.predict_async method."""
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = await test_endpoint.direct_predict_async(
+ inputs=_TEST_INPUTS, parameters=None
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_predict_async_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "inputs": _TEST_INPUTS,
+ "parameters": None,
+ },
+ timeout=None,
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ async def test_direct_predict_async_with_parameters(
+ self, predict_client_direct_predict_async_mock
+ ):
+ """Tests the Endpoint.predict_async method."""
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = await test_endpoint.direct_predict_async(
+ inputs=_TEST_INPUTS, parameters={"param": 3.0}
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_predict_async_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "inputs": _TEST_INPUTS,
+ "parameters": {"param": 3.0},
+ },
+ timeout=None,
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ async def test_direct_predict_async_with_timeout(
+ self, predict_client_direct_predict_async_mock
+ ):
+ """Tests the Endpoint.predict_async method."""
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = await test_endpoint.direct_predict_async(
+ inputs=_TEST_INPUTS, timeout=10.0
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_predict_async_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "inputs": _TEST_INPUTS,
+ "parameters": None,
+ },
+ timeout=10.0,
+ )
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_direct_raw_predict(self, predict_client_direct_raw_predict_mock):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = test_endpoint.direct_raw_predict(
+ method_name=_TEST_METHOD_NAME, request=_TEST_RAW_INPUTS
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_RAW_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_raw_predict_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "method_name": _TEST_METHOD_NAME,
+ "input": _TEST_RAW_INPUTS,
+ },
+ timeout=None,
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ async def test_direct_raw_predict_async(
+ self, predict_client_direct_raw_predict_async_mock
+ ):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = await test_endpoint.direct_raw_predict_async(
+ method_name=_TEST_METHOD_NAME, request=_TEST_RAW_INPUTS
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_RAW_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_raw_predict_async_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "method_name": _TEST_METHOD_NAME,
+ "input": _TEST_RAW_INPUTS,
+ },
+ timeout=None,
+ )
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_direct_raw_predict_with_timeout(
+ self, predict_client_direct_raw_predict_mock
+ ):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction = test_endpoint.direct_raw_predict(
+ method_name=_TEST_METHOD_NAME, request=_TEST_RAW_INPUTS, timeout=10.0
+ )
+
+ true_prediction = models.Prediction(
+ predictions=_TEST_RAW_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ )
+
+ assert true_prediction == test_prediction
+ predict_client_direct_raw_predict_mock.assert_called_once_with(
+ request={
+ "endpoint": _TEST_ENDPOINT_NAME,
+ "method_name": _TEST_METHOD_NAME,
+ "input": _TEST_RAW_INPUTS,
+ },
+ timeout=10.0,
+ )
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_stream_direct_predict(self, predict_client_stream_direct_predict_mock):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction_iterator = test_endpoint.stream_direct_predict(
+ inputs_iterator=iter([_TEST_INPUTS]), parameters=None
+ )
+ test_prediction = list(test_prediction_iterator)
+
+ true_prediction = [
+ models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ ]
+
+ assert true_prediction == test_prediction
+ predict_client_stream_direct_predict_mock.assert_called_once()
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_stream_direct_predict_with_parameters(
+ self, predict_client_stream_direct_predict_mock
+ ):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction_iterator = test_endpoint.stream_direct_predict(
+ inputs_iterator=iter([_TEST_INPUTS]), parameters={"param": 3.0}
+ )
+ test_prediction = list(test_prediction_iterator)
+
+ true_prediction = [
+ models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ ]
+
+ assert true_prediction == test_prediction
+ predict_client_stream_direct_predict_mock.assert_called_once()
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_stream_direct_predict_with_timeout(
+ self, predict_client_stream_direct_predict_mock
+ ):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction_iterator = test_endpoint.stream_direct_predict(
+ inputs_iterator=iter([_TEST_INPUTS]), parameters=None, timeout=10.0
+ )
+ test_prediction = list(test_prediction_iterator)
+
+ true_prediction = [
+ models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ models.Prediction(
+ predictions=_TEST_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ ]
+
+ assert true_prediction == test_prediction
+ predict_client_stream_direct_predict_mock.assert_called_once()
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_stream_direct_raw_predict(
+ self, predict_client_stream_direct_raw_predict_mock
+ ):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction_iterator = test_endpoint.stream_direct_raw_predict(
+ method_name=_TEST_METHOD_NAME, requests=iter([_TEST_RAW_INPUTS])
+ )
+ test_prediction = list(test_prediction_iterator)
+
+ true_prediction = [
+ models.Prediction(
+ predictions=_TEST_RAW_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ models.Prediction(
+ predictions=_TEST_RAW_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ ]
+
+ assert true_prediction == test_prediction
+ predict_client_stream_direct_raw_predict_mock.assert_called_once()
+
+ @pytest.mark.usefixtures("get_endpoint_mock")
+ def test_stream_direct_raw_predict_with_timeout(
+ self, predict_client_stream_direct_raw_predict_mock
+ ):
+ test_endpoint = models.Endpoint(_TEST_ID)
+ test_prediction_iterator = test_endpoint.stream_direct_raw_predict(
+ method_name=_TEST_METHOD_NAME,
+ requests=iter([_TEST_RAW_INPUTS]),
+ timeout=10.0,
+ )
+ test_prediction = list(test_prediction_iterator)
+
+ true_prediction = [
+ models.Prediction(
+ predictions=_TEST_RAW_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ models.Prediction(
+ predictions=_TEST_RAW_OUTPUTS,
+ deployed_model_id=None,
+ metadata=None,
+ model_version_id=None,
+ model_resource_name=None,
+ ),
+ ]
+
+ assert true_prediction == test_prediction
+ predict_client_stream_direct_raw_predict_mock.assert_called_once()
+
@pytest.mark.usefixtures("get_endpoint_mock")
def test_explain_with_timeout(self, predict_client_explain_mock):
test_endpoint = models.Endpoint(_TEST_ID)
| diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 542bbbea25..bb358f0808 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,3 +1,3 @@
{
- ".": "1.56.0"
+ ".": "1.55.0"
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8b06132ad..1fdeacfff5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,29 +1,5 @@
# Changelog
-## [1.56.0](https://github.com/googleapis/python-aiplatform/compare/v1.55.0...v1.56.0) (2024-06-18)
-
-
-### Features
-
-* Add `retry_timeout` to EvalTask in `vertexai.preview.evaluation` ([4d9ee9d](https://github.com/googleapis/python-aiplatform/commit/4d9ee9dc6c046fd71e2f3176981a2a108fbbaeeb))
-* Add hybrid query example to vector search sample. ([510da5e](https://github.com/googleapis/python-aiplatform/commit/510da5ef3bcaa507288571fc7e066f578fde329f))
-* Add metric classes for 2 pairwise metrics for rapid evaluation SDK. ([831c8e4](https://github.com/googleapis/python-aiplatform/commit/831c8e45ee88f70efcdaba7dfed1856837074357))
-* Add pipeline_job_name to allow PipelineJob.get(pipeline_job_name) ([32e3b22](https://github.com/googleapis/python-aiplatform/commit/32e3b22993a83414ee60e52b0c95bd8b63543787))
-* Add sample code show how to create an optimized private online store in Vertex AI Feature Store. ([e352175](https://github.com/googleapis/python-aiplatform/commit/e3521751ecb79d5f711658c39d2dd5b204c191c5))
-* GenAI - Context Caching - add get() classmethod and refresh() instance method ([6be874a](https://github.com/googleapis/python-aiplatform/commit/6be874a7c6c43b7acbf5926e38e56d2ab367f5a1))
-* GenAI - Context Caching - also print model_name and expire_time. ([d548c11](https://github.com/googleapis/python-aiplatform/commit/d548c1128d8b6abc7ed8007436bc868a688fcace))
-* GenAI - Tuning - Added support for CMEK ([eb651bc](https://github.com/googleapis/python-aiplatform/commit/eb651bc2ed60ba12d88998115470c12d858892ef))
-
-
-### Bug Fixes
-
-* Do not reset aiplatform.Experiment or aiplatform.ExperimentRun unnecessarily when running tensorboard uploader. ([28a091a](https://github.com/googleapis/python-aiplatform/commit/28a091ab609ae3c086bb35ee4901c61108a4e75e))
-
-
-### Documentation
-
-* Update the documentation for the `time_series_dataset` and `video_dataset` classes ([d5dc7b5](https://github.com/googleapis/python-aiplatform/commit/d5dc7b5697eb4c7e86ec9e108454a30c8c7028d7))
-
## [1.55.0](https://github.com/googleapis/python-aiplatform/compare/v1.54.1...v1.55.0) (2024-06-12)
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json
index 4769e1be18..3162187456 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-aiplatform",
- "version": "1.56.0"
+ "version": "1.55.0"
},
"snippets": [
{
diff --git a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json
index 53a4e1a5e2..2426d3ae1c 100644
--- a/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json
+++ b/samples/generated_samples/snippet_metadata_google.cloud.aiplatform.v1beta1.json
@@ -8,7 +8,7 @@
],
"language": "PYTHON",
"name": "google-cloud-aiplatform",
- "version": "1.56.0"
+ "version": "1.55.0"
},
"snippets": [
{
| [
{
"components": [
{
"doc": "Makes a streaming prediction request using arbitrary headers.\n\nExample usage:\n ```\n my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)\n for stream_response in my_endpoint.stream_raw_predict(\n body = b'{\"instances\":[{\"feat_1\":val_1, \"feat_2\":val_2... | [
"tests/unit/aiplatform/test_endpoints.py::TestEndpoint::test_direct_predict",
"tests/unit/aiplatform/test_endpoints.py::TestEndpoint::test_direct_predict_with_parameters",
"tests/unit/aiplatform/test_endpoints.py::TestEndpoint::test_direct_predict_with_timeout",
"tests/unit/aiplatform/test_endpoints.py::TestE... | [
"tests/unit/aiplatform/test_endpoints.py::TestEndpoint::test_constructor",
"tests/unit/aiplatform/test_endpoints.py::TestEndpoint::test_lazy_constructor_with_endpoint_id",
"tests/unit/aiplatform/test_endpoints.py::TestEndpoint::test_lazy_constructor_with_endpoint_name",
"tests/unit/aiplatform/test_endpoints.p... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Endpoint.stream_raw_predict
feat: Endpoint.stream_raw_predict
feat: Endpoint.direct_predict
feat: Endpoint.direct_predict_async
feat: Endpoint.stream_direct_predict
feat: Endpoint.direct_raw_predict
feat: Endpoint.direct_raw_predict_async
feat: Endpoint.stream_direct_raw_predict
----------
</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 google/cloud/aiplatform/models.py]
(definition of Endpoint.stream_raw_predict:)
def stream_raw_predict( self, body: bytes, headers: Dict[str, str] ) -> Iterator[requests.models.Response]:
"""Makes a streaming prediction request using arbitrary headers.
Example usage:
```
my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)
for stream_response in my_endpoint.stream_raw_predict(
body = b'{"instances":[{"feat_1":val_1, "feat_2":val_2}]}'
headers = {'Content-Type':'application/json'}
):
status_code = response.status_code
stream_result = json.dumps(response.text)
```
Args:
body (bytes):
The body of the prediction request in bytes. This must not
exceed 10 mb per request.
headers (Dict[str, str]):
The header of the request as a dictionary. There are no
restrictions on the header.
Yields:
predictions (Iterator[requests.models.Response]):
The streaming prediction results."""
(definition of Endpoint.direct_predict:)
def direct_predict( self, inputs: List, parameters: Optional[Dict] = None, timeout: Optional[float] = None, ) -> Prediction:
"""Makes a direct (gRPC) prediction against this Endpoint for a pre-built image.
Args:
inputs (List):
Required. The inputs that are the input to the prediction call.
A DeployedModel may have an upper limit on the number of
instances it supports per request, and when it is exceeded the
prediction call errors in case of AutoML Models, or, in case of
customer created Models, the behaviour is as documented by that
Model. The schema of any single instance may be specified via
Endpoint's DeployedModels'
[Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
[PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
``instance_schema_uri``.
parameters (Dict):
Optional. The parameters that govern the prediction. The schema
of the parameters may be specified via Endpoint's
DeployedModels'
[Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
[PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
``parameters_schema_uri``.
timeout (Optional[float]):
Optional. The timeout for this request in seconds.
Returns:
prediction (aiplatform.Prediction):
The resulting prediction."""
(definition of Endpoint.stream_direct_predict:)
def stream_direct_predict( self, inputs_iterator: Iterator[List], parameters: Optional[Dict] = None, timeout: Optional[float] = None, ) -> Iterator[Prediction]:
"""Makes a streaming direct (gRPC) prediction against this Endpoint for a pre-built image.
Args:
inputs_iterator (Iterator[List]):
Required. An iterator of the inputs that are the input to the
prediction call. A DeployedModel may have an upper limit on the
number of instances it supports per request, and when it is
exceeded the prediction call errors in case of AutoML Models, or,
in case of customer created Models, the behaviour is as
documented by that Model. The schema of any single instance may
be specified via Endpoint's DeployedModels'
[Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
[PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
``instance_schema_uri``.
parameters (Dict):
Optional. The parameters that govern the prediction. The schema
of the parameters may be specified via Endpoint's
DeployedModels'
[Model's][google.cloud.aiplatform.v1beta1.DeployedModel.model]
[PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
``parameters_schema_uri``.
timeout (Optional[float]):
Optional. The timeout for this request in seconds.
Yields:
predictions (Iterator[aiplatform.Prediction]):
The resulting streamed predictions."""
(definition of Endpoint.direct_raw_predict:)
def direct_raw_predict( self, method_name: str, request: bytes, timeout: Optional[float] = None, ) -> Prediction:
"""Makes a direct (gRPC) prediction request using arbitrary headers for a custom container.
Example usage:
```
my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)
response = my_endpoint.direct_raw_predict(request=b'...')
```
Args:
method_name (str):
Fully qualified name of the API method being invoked to perform
prediction.
request (bytes):
The body of the prediction request in bytes.
timeout (Optional[float]):
Optional. The timeout for this request in seconds.
Returns:
prediction (aiplatform.Prediction):
The resulting prediction."""
(definition of Endpoint.stream_direct_raw_predict:)
def stream_direct_raw_predict( self, method_name: str, requests: Iterator[bytes], timeout: Optional[float] = None, ) -> Iterator[Prediction]:
"""Makes a direct (gRPC) streaming prediction request for a custom container.
Example usage:
```
my_endpoint = aiplatform.Endpoint(ENDPOINT_ID)
for stream_response in my_endpoint.stream_direct_raw_predict(
request=b'...'
):
yield stream_response
```
Args:
method_name (str):
Fully qualified name of the API method being invoked to perform
prediction.
requests (Iterator[bytes]):
The body of the prediction requests in bytes.
timeout (Optional[float]):
Optional. The timeout for this request in seconds.
Yields:
predictions (Iterator[aiplatform.Prediction]):
The resulting streamed predictions."""
[end of new definitions in google/cloud/aiplatform/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>> | 67358fa6a830eb842f6b52d09061af4a41b54af6 | |
google-deepmind__optax-971 | 971 | google-deepmind/optax | null | ae0de8f30a170ebb3061ee18c206368b2524a003 | 2024-05-23T16:33:11Z | diff --git a/docs/api/losses.rst b/docs/api/losses.rst
index bcc9cd38a..698bbb87d 100644
--- a/docs/api/losses.rst
+++ b/docs/api/losses.rst
@@ -14,13 +14,18 @@ Losses
kl_divergence
l2_loss
log_cosh
+ multiclass_hinge_loss
+ multiclass_perceptron_loss
+ multiclass_sparsemax_loss
ntxent
+ perceptron_loss
safe_softmax_cross_entropy
sigmoid_binary_cross_entropy
sigmoid_focal_loss
smooth_labels
softmax_cross_entropy
softmax_cross_entropy_with_integer_labels
+ sparsemax_loss
squared_error
@@ -44,6 +49,7 @@ Connectionist temporal classification loss
Hinge loss
~~~~~~~~~~
.. autofunction:: hinge_loss
+.. autofunction:: multiclass_hinge_loss
Huber loss
~~~~~~~~~~
@@ -66,6 +72,11 @@ Normalized temperature scaled cross-entropy (NT-Xent) loss
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: ntxent
+Perceptron
+~~~~~~~~~~~
+.. autofunction:: perceptron_loss
+.. autofunction:: multiclass_perceptron_loss
+
Sigmoid binary cross-entropy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: sigmoid_binary_cross_entropy
@@ -84,5 +95,10 @@ Soft-max cross-entropy
.. autofunction:: softmax_cross_entropy
.. autofunction:: softmax_cross_entropy_with_integer_labels
+Sparsemax
+~~~~~~~~~
+.. autofunction:: sparsemax_loss
+.. autofunction:: multiclass_sparsemax_loss
+
diff --git a/optax/losses/_classification.py b/optax/losses/_classification.py
index 397ba25ab..327fcb93d 100644
--- a/optax/losses/_classification.py
+++ b/optax/losses/_classification.py
@@ -21,6 +21,8 @@
import jax
import jax.numpy as jnp
+from optax import projections
+
def sigmoid_binary_cross_entropy(
logits,
@@ -679,3 +681,36 @@ def sigmoid_focal_loss(
loss)
return loss
+
+
+def _multiclass_sparsemax_loss(
+ scores: chex.Array, label: chex.Array
+) -> chex.Array:
+ scores = jnp.asarray(scores)
+ proba = projections.projection_simplex(scores)
+ # Fenchel conjugate of the Gini negentropy, defined by:
+ # cumulant = jnp.dot(proba, scores) + 0.5 * jnp.dot(proba, (1 - proba)).
+ scores = (scores - scores[label]).at[label].set(0.0)
+ return (jnp.dot(proba, jnp.where(proba, scores, 0.0))
+ + 0.5 * (1.0 - jnp.dot(proba, proba)))
+
+
+def multiclass_sparsemax_loss(
+ scores: chex.Array,
+ labels: chex.Array,
+) -> chex.Array:
+ """Multiclass sparsemax loss.
+
+ Args:
+ scores: scores produced by the model.
+ labels: ground-truth integer labels.
+
+ Returns:
+ loss values
+
+ References:
+ From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label
+ Classification. André F. T. Martins, Ramón Fernandez Astudillo.
+ ICML 2016.
+ """
+ return jax.vmap(_multiclass_sparsemax_loss)(scores, labels)
| diff --git a/optax/losses/_classification_test.py b/optax/losses/_classification_test.py
index b87d520ea..473633319 100644
--- a/optax/losses/_classification_test.py
+++ b/optax/losses/_classification_test.py
@@ -23,6 +23,8 @@
import jax.numpy as jnp
import jax.test_util as jaxtest
import numpy as np
+
+from optax import projections
from optax.losses import _classification
@@ -447,6 +449,29 @@ def reference_impl(label, logit):
result = _classification.sparsemax_loss(scores, labels)
np.testing.assert_allclose(result, expected, atol=1e-4)
+ def test_multi_class_zero_loss(self):
+ # Check that putting large scores on the correct class gives a zero loss.
+ labels = jnp.array([1, 0, 2])
+ scores = jnp.array([[0.0, 1e5, 0.0],
+ [1e5, 0.0, 0.0],
+ [0.0, 0.0, 1e5]])
+ losses = _classification.multiclass_sparsemax_loss(scores, labels)
+ np.testing.assert_allclose(losses, np.array([0.0, 0.0, 0.0]), atol=1e-4)
+
+ def test_multi_class_gradient(self):
+ # Check that the gradient is correct.
+ def loss_mean(scores, labels):
+ return jnp.mean(_classification.multiclass_sparsemax_loss(scores, labels))
+
+ labels = jnp.array([1, 0, 2])
+ scores = jnp.array([[0.0, 1e5, 0.0],
+ [1e5, 0.0, 0.0],
+ [0.0, 0.0, 1e5]])
+ grad = jax.grad(loss_mean)(scores, labels)
+ projection_vmap = jax.vmap(projections.projection_simplex)
+ grad_expected = projection_vmap(scores) - jax.nn.one_hot(labels, 3)
+ np.testing.assert_allclose(grad, grad_expected, atol=1e-4)
+
class ConvexKLDivergenceTest(parameterized.TestCase):
| diff --git a/docs/api/losses.rst b/docs/api/losses.rst
index bcc9cd38a..698bbb87d 100644
--- a/docs/api/losses.rst
+++ b/docs/api/losses.rst
@@ -14,13 +14,18 @@ Losses
kl_divergence
l2_loss
log_cosh
+ multiclass_hinge_loss
+ multiclass_perceptron_loss
+ multiclass_sparsemax_loss
ntxent
+ perceptron_loss
safe_softmax_cross_entropy
sigmoid_binary_cross_entropy
sigmoid_focal_loss
smooth_labels
softmax_cross_entropy
softmax_cross_entropy_with_integer_labels
+ sparsemax_loss
squared_error
@@ -44,6 +49,7 @@ Connectionist temporal classification loss
Hinge loss
~~~~~~~~~~
.. autofunction:: hinge_loss
+.. autofunction:: multiclass_hinge_loss
Huber loss
~~~~~~~~~~
@@ -66,6 +72,11 @@ Normalized temperature scaled cross-entropy (NT-Xent) loss
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: ntxent
+Perceptron
+~~~~~~~~~~~
+.. autofunction:: perceptron_loss
+.. autofunction:: multiclass_perceptron_loss
+
Sigmoid binary cross-entropy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autofunction:: sigmoid_binary_cross_entropy
@@ -84,5 +95,10 @@ Soft-max cross-entropy
.. autofunction:: softmax_cross_entropy
.. autofunction:: softmax_cross_entropy_with_integer_labels
+Sparsemax
+~~~~~~~~~
+.. autofunction:: sparsemax_loss
+.. autofunction:: multiclass_sparsemax_loss
+
| [
{
"components": [
{
"doc": "",
"lines": [
686,
695
],
"name": "_multiclass_sparsemax_loss",
"signature": "def _multiclass_sparsemax_loss( scores: chex.Array, label: chex.Array ) -> chex.Array:",
"type": "function"
},
{
... | [
"optax/losses/_classification_test.py::SparsemaxTest::test_multi_class_gradient",
"optax/losses/_classification_test.py::SparsemaxTest::test_multi_class_zero_loss"
] | [
"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... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add multiclass_sparsemax_loss.
Add multiclass_sparsemax_loss.
----------
</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/_classification.py]
(definition of _multiclass_sparsemax_loss:)
def _multiclass_sparsemax_loss( scores: chex.Array, label: chex.Array ) -> chex.Array:
(definition of multiclass_sparsemax_loss:)
def multiclass_sparsemax_loss( scores: chex.Array, labels: chex.Array, ) -> chex.Array:
"""Multiclass sparsemax loss.
Args:
scores: scores produced by the model.
labels: ground-truth integer labels.
Returns:
loss values
References:
From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label
Classification. André F. T. Martins, Ramón Fernandez Astudillo.
ICML 2016."""
[end of new definitions in optax/losses/_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>> | 1e08bccf195ac54e7d9d766eb5e69345bf0e3230 | |
pvlib__pvlib-python-2053 | 2,053 | pvlib/pvlib-python | 0.10 | 19c9598355b8243038bdeb1253d219e0371f71af | 2024-05-17T23:39:44Z | diff --git a/docs/sphinx/source/reference/index.rst b/docs/sphinx/source/reference/index.rst
index 9083f85bdd..8a990ac923 100644
--- a/docs/sphinx/source/reference/index.rst
+++ b/docs/sphinx/source/reference/index.rst
@@ -20,3 +20,4 @@ API reference
bifacial
scaling
location
+ transformer
diff --git a/docs/sphinx/source/reference/transformer.rst b/docs/sphinx/source/reference/transformer.rst
new file mode 100644
index 0000000000..293f301296
--- /dev/null
+++ b/docs/sphinx/source/reference/transformer.rst
@@ -0,0 +1,11 @@
+.. currentmodule:: pvlib
+
+Transformer losses
+==================
+
+Methods to account for losses in transformers
+
+.. autosummary::
+ :toctree: generated/
+
+ transformer.simple_efficiency
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 119881157b..f6665a60d2 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -24,6 +24,8 @@ Deprecations
Enhancements
~~~~~~~~~~~~
+* Add a simple transformer efficiency model :py:func:`pvlib.transformer.simple_efficiency`.
+ (:issue:`1269`, :pull:`2053`)
* Add function :py:func:`pvlib.shading.shaded_fraction1d`, to calculate the
shade perpendicular to ``axis_azimuth``. The function is applicable to both
fixed-tilt and one-axis tracking systems.
@@ -58,6 +60,7 @@ Requirements
Contributors
~~~~~~~~~~~~
* Cliff Hansen (:ghuser:`cwhanse`)
+* Kurt Rhee (:ghuser:`kurt-rhee`)
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
* Ioannis Sifnaios (:ghuser:`IoannisSifnaios`)
diff --git a/pvlib/transformer.py b/pvlib/transformer.py
new file mode 100644
index 0000000000..3b66b0beb3
--- /dev/null
+++ b/pvlib/transformer.py
@@ -0,0 +1,117 @@
+"""
+This module contains functions for transformer modeling.
+
+Transformer models calculate AC power output and losses at a given input power.
+"""
+
+
+def simple_efficiency(
+ input_power, no_load_loss, load_loss, transformer_rating
+):
+ r'''
+ Calculate the power at the output terminal of the transformer
+ after taking into account efficiency using a simple calculation.
+
+ The equation used in this function can be derived from [1]_.
+
+ For a zero input power, the output power will be negative.
+ This means the transformer will consume energy from the grid at night if
+ it stays connected (due to the parallel impedance in the equivalent
+ circuit).
+ If the input power is negative, the output power will be even more
+ negative; so the model can be used bidirectionally when drawing
+ energy from the grid.
+
+ Parameters
+ ----------
+ input_power : numeric
+ The real AC power input to the transformer. [W]
+
+ no_load_loss : numeric
+ The constant losses experienced by a transformer, even
+ when the transformer is not under load. Fraction of transformer rating,
+ value from 0 to 1. [unitless]
+
+ load_loss: numeric
+ The load dependent losses experienced by the transformer.
+ Fraction of transformer rating, value from 0 to 1. [unitless]
+
+ transformer_rating: numeric
+ The nominal output power of the transformer. [VA]
+
+ Returns
+ -------
+ output_power : numeric
+ Real AC power output. [W]
+
+ Notes
+ -------
+ First, assume that the load loss :math:`L_{load}` (as a fraction of rated power
+ :math:`P_{nom}`) is proportional to the square of output power:
+
+ .. math::
+
+ L_{load}(P_{out}) &= L_{load}(P_{rated}) \times (P_{out} / P_{nom})^2
+
+ &= L_{full, load} \times (P_{out} / P_{nom})^2
+
+ Total loss is the constant no-load loss plus the variable load loss:
+
+ .. math::
+
+ L_{total}(P_{out}) &= L_{no, load} + L_{load}(P_{out})
+
+ &= L_{no, load} + L_{full, load} \times (P_{out} / P_{nom})^2
+
+
+ By conservation of energy, total loss is the difference between input and
+ output power:
+
+ .. math::
+
+ \frac{P_{in}}{P_{nom}} &= \frac{P_{out}}{P_{nom}} + L_{total}(P_{out})
+
+ &= \frac{P_{out}}{P_{nom}} + L_{no, load} + L_{full, load} \times (P_{out} / P_{nom})^2
+
+ Now use the quadratic formula to solve for :math:`P_{out}` as a function of
+ :math:`P_{in}`.
+
+ .. math::
+
+ \frac{P_{out}}{P_{nom}} &= \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
+
+ a &= L_{full, load}
+
+ b &= 1
+
+ c &= L_{no, load} - P_{in} / P_{nom}
+
+ Therefore:
+
+ .. math::
+
+ P_{out} = P_{nom} \frac{-1 \pm \sqrt{1 - 4 L_{full, load}
+
+ \times (L_{no, load} - P_{in}/P_{nom})}}{2 L_{full, load}}
+
+ The positive root should be chosen, so that the output power is
+ positive.
+
+
+ References
+ ----------
+ .. [1] Central Station Engineers of the Westinghouse Electric Corporation,
+ "Electrical Transmission and Distribution Reference Book" 4th Edition.
+ pg. 101.
+ ''' # noqa: E501
+
+ input_power_normalized = input_power / transformer_rating
+
+ a = load_loss
+ b = 1
+ c = no_load_loss - input_power_normalized
+
+ output_power_normalized = (-b + (b**2 - 4*a*c)**0.5) / (2 * a)
+
+ output_power = output_power_normalized * transformer_rating
+ return output_power
| diff --git a/pvlib/tests/test_transformer.py b/pvlib/tests/test_transformer.py
new file mode 100644
index 0000000000..0739a9e95a
--- /dev/null
+++ b/pvlib/tests/test_transformer.py
@@ -0,0 +1,60 @@
+import pandas as pd
+
+from numpy.testing import assert_allclose
+
+from pvlib import transformer
+
+
+def test_simple_efficiency():
+
+ # define test inputs
+ input_power = pd.Series([
+ -800.0,
+ 436016.609823837,
+ 1511820.16603752,
+ 1580687.44677249,
+ 1616441.79660171
+ ])
+ no_load_loss = 0.002
+ load_loss = 0.007
+ transformer_rating = 2750000
+
+ # define expected test results
+ expected_output_power = pd.Series([
+ -6300.10103234071,
+ 430045.854892526,
+ 1500588.39919874,
+ 1568921.77089526,
+ 1604389.62839879
+ ])
+
+ # run test function with test inputs
+ calculated_output_power = transformer.simple_efficiency(
+ input_power=input_power,
+ no_load_loss=no_load_loss,
+ load_loss=load_loss,
+ transformer_rating=transformer_rating
+ )
+
+ # determine if expected results are obtained
+ assert_allclose(calculated_output_power, expected_output_power)
+
+
+def test_simple_efficiency_known_values():
+ no_load_loss = 0.005
+ load_loss = 0.01
+ rating = 1000
+ args = (no_load_loss, load_loss, rating)
+
+ # verify correct behavior at no-load condition
+ assert_allclose(
+ transformer.simple_efficiency(no_load_loss*rating, *args),
+ 0.0
+ )
+
+ # verify correct behavior at rated condition
+ assert_allclose(
+ transformer.simple_efficiency(rating*(1 + no_load_loss + load_loss),
+ *args),
+ rating,
+ )
| diff --git a/docs/sphinx/source/reference/index.rst b/docs/sphinx/source/reference/index.rst
index 9083f85bdd..8a990ac923 100644
--- a/docs/sphinx/source/reference/index.rst
+++ b/docs/sphinx/source/reference/index.rst
@@ -20,3 +20,4 @@ API reference
bifacial
scaling
location
+ transformer
diff --git a/docs/sphinx/source/reference/transformer.rst b/docs/sphinx/source/reference/transformer.rst
new file mode 100644
index 0000000000..293f301296
--- /dev/null
+++ b/docs/sphinx/source/reference/transformer.rst
@@ -0,0 +1,11 @@
+.. currentmodule:: pvlib
+
+Transformer losses
+==================
+
+Methods to account for losses in transformers
+
+.. autosummary::
+ :toctree: generated/
+
+ transformer.simple_efficiency
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 119881157b..f6665a60d2 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -24,6 +24,8 @@ Deprecations
Enhancements
~~~~~~~~~~~~
+* Add a simple transformer efficiency model :py:func:`pvlib.transformer.simple_efficiency`.
+ (:issue:`1269`, :pull:`2053`)
* Add function :py:func:`pvlib.shading.shaded_fraction1d`, to calculate the
shade perpendicular to ``axis_azimuth``. The function is applicable to both
fixed-tilt and one-axis tracking systems.
@@ -58,6 +60,7 @@ Requirements
Contributors
~~~~~~~~~~~~
* Cliff Hansen (:ghuser:`cwhanse`)
+* Kurt Rhee (:ghuser:`kurt-rhee`)
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
* Ioannis Sifnaios (:ghuser:`IoannisSifnaios`)
| [
{
"components": [
{
"doc": "Calculate the power at the output terminal of the transformer\nafter taking into account efficiency using a simple calculation.\n\nThe equation used in this function can be derived from [1]_.\n\nFor a zero input power, the output power will be negative.\nThis means the ... | [
"pvlib/tests/test_transformer.py::test_simple_efficiency",
"pvlib/tests/test_transformer.py::test_simple_efficiency_known_values"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Add a simple transformer effficiency model to pvlib
<!-- 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] Closes #1269
- [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): -->
Described in the issue link. Please look out for issues with the rendering of latex in the docstring. I am not a sphinx or latex expert.
----------
</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/transformer.py]
(definition of simple_efficiency:)
def simple_efficiency( input_power, no_load_loss, load_loss, transformer_rating ):
"""Calculate the power at the output terminal of the transformer
after taking into account efficiency using a simple calculation.
The equation used in this function can be derived from [1]_.
For a zero input power, the output power will be negative.
This means the transformer will consume energy from the grid at night if
it stays connected (due to the parallel impedance in the equivalent
circuit).
If the input power is negative, the output power will be even more
negative; so the model can be used bidirectionally when drawing
energy from the grid.
Parameters
----------
input_power : numeric
The real AC power input to the transformer. [W]
no_load_loss : numeric
The constant losses experienced by a transformer, even
when the transformer is not under load. Fraction of transformer rating,
value from 0 to 1. [unitless]
load_loss: numeric
The load dependent losses experienced by the transformer.
Fraction of transformer rating, value from 0 to 1. [unitless]
transformer_rating: numeric
The nominal output power of the transformer. [VA]
Returns
-------
output_power : numeric
Real AC power output. [W]
Notes
-------
First, assume that the load loss :math:`L_{load}` (as a fraction of rated power
:math:`P_{nom}`) is proportional to the square of output power:
.. math::
L_{load}(P_{out}) &= L_{load}(P_{rated}) \times (P_{out} / P_{nom})^2
&= L_{full, load} \times (P_{out} / P_{nom})^2
Total loss is the constant no-load loss plus the variable load loss:
.. math::
L_{total}(P_{out}) &= L_{no, load} + L_{load}(P_{out})
&= L_{no, load} + L_{full, load} \times (P_{out} / P_{nom})^2
By conservation of energy, total loss is the difference between input and
output power:
.. math::
\frac{P_{in}}{P_{nom}} &= \frac{P_{out}}{P_{nom}} + L_{total}(P_{out})
&= \frac{P_{out}}{P_{nom}} + L_{no, load} + L_{full, load} \times (P_{out} / P_{nom})^2
Now use the quadratic formula to solve for :math:`P_{out}` as a function of
:math:`P_{in}`.
.. math::
\frac{P_{out}}{P_{nom}} &= \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
a &= L_{full, load}
b &= 1
c &= L_{no, load} - P_{in} / P_{nom}
Therefore:
.. math::
P_{out} = P_{nom} \frac{-1 \pm \sqrt{1 - 4 L_{full, load}
\times (L_{no, load} - P_{in}/P_{nom})}}{2 L_{full, load}}
The positive root should be chosen, so that the output power is
positive.
References
----------
.. [1] Central Station Engineers of the Westinghouse Electric Corporation,
"Electrical Transmission and Distribution Reference Book" 4th Edition.
pg. 101."""
[end of new definitions in pvlib/transformer.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>
Transformers
**problem**
As an energy analyst, I need to know energy at point of interconnect, and that includes detailed transformer efficiency and losses, as well as ac collection losses and curtailment
**solution**
A transformer load / no-load model
**alternatives**
Roll your own, but then this risks everyone using slightly different, possibly flawed models, precisely one of the issues pvlib tries to solve
**Additional context**
* Related to #1020 and maybe #96
* a reverse model would be useful for battery storage
* copy or use pysam?
----------
I think this would be a nice addition. The modelling is relatively easy and spec sheets often have the needed info.
Hey @mikofski,
@kevinsa5 and @AdamRJensen brought this up during the PVPMC pvlib session. I'd like to take a stab at it if there are no objections. PlantPredict uses this very simple model from McCann, Lawrence , ABB Electrical Transmission and Distribution Reference, P.101.
https://terabase.atlassian.net/servicedesk/customer/portal/3/article/1292304413
I would also like to write a blog post that documents how to create a pull request for a pvlib upgrade using the transformer model as a real world example.
If it helps I did some nuts & bolts talks at UC BIDS a few years back:
- https://bids.github.io/dats/posts/2017-10-04-github-oss-f17.html
- https://bids.github.io/dats/posts/2018-09-10-github-oss.html
Mark those are awesome references, I will definitely riff off of them.
--------------------
</issues> | 6af80da35a7c96059c534ee38be9123bcfc7f50f |
tobymao__sqlglot-3489 | 3,489 | tobymao/sqlglot | null | 5b64475bfd2d6a0ddcb3d0adb60d06dca62421a0 | 2024-05-16T04:15:34Z | diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py
index 3dfdd84753..7615203bfb 100644
--- a/sqlglot/dialects/clickhouse.py
+++ b/sqlglot/dialects/clickhouse.py
@@ -15,6 +15,7 @@
build_json_extract_path,
rename_func,
var_map_sql,
+ timestamptrunc_sql,
)
from sqlglot.helper import is_int, seq_get
from sqlglot.tokens import Token, TokenType
@@ -761,6 +762,9 @@ class Generator(generator.Generator):
"SHA256" if e.text("length") == "256" else "SHA512", e.this
),
exp.UnixToTime: _unix_to_time_sql,
+ exp.TimestampTrunc: timestamptrunc_sql(zone=True),
+ exp.Variance: rename_func("varSamp"),
+ exp.Stddev: rename_func("stddevSamp"),
}
PROPERTIES_LOCATION = {
diff --git a/sqlglot/dialects/databricks.py b/sqlglot/dialects/databricks.py
index d7fbb35f20..87d19fc6e3 100644
--- a/sqlglot/dialects/databricks.py
+++ b/sqlglot/dialects/databricks.py
@@ -57,7 +57,7 @@ class Generator(Spark.Generator):
),
exp.DatetimeDiff: _timestamp_diff,
exp.TimestampDiff: _timestamp_diff,
- exp.DatetimeTrunc: timestamptrunc_sql,
+ exp.DatetimeTrunc: timestamptrunc_sql(),
exp.JSONExtract: lambda self, e: self.binary(e, ":"),
exp.Select: transforms.preprocess(
[
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index 3cdf39bb01..213190f51a 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -772,8 +772,14 @@ def func(self: Generator, expression: exp.Expression) -> str:
return func
-def timestamptrunc_sql(self: Generator, expression: exp.TimestampTrunc) -> str:
- return self.func("DATE_TRUNC", unit_to_str(expression), expression.this)
+def timestamptrunc_sql(zone: bool = False) -> t.Callable[[Generator, exp.TimestampTrunc], str]:
+ def _timestamptrunc_sql(self: Generator, expression: exp.TimestampTrunc) -> str:
+ args = [unit_to_str(expression), expression.this]
+ if zone:
+ args.append(expression.args.get("zone"))
+ return self.func("DATE_TRUNC", *args)
+
+ return _timestamptrunc_sql
def no_timestamp_sql(self: Generator, expression: exp.Timestamp) -> str:
diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index ca089a0d3e..19f2f4afb7 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -458,7 +458,7 @@ class Generator(generator.Generator):
exp.TimestampDiff: lambda self, e: self.func(
"DATE_DIFF", exp.Literal.string(e.unit), e.expression, e.this
),
- exp.TimestampTrunc: timestamptrunc_sql,
+ exp.TimestampTrunc: timestamptrunc_sql(),
exp.TimeStrToDate: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.DATE)),
exp.TimeStrToTime: timestrtotime_sql,
exp.TimeStrToUnix: lambda self, e: self.func(
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py
index 34831ca47d..9473d4ad6e 100644
--- a/sqlglot/dialects/postgres.py
+++ b/sqlglot/dialects/postgres.py
@@ -543,7 +543,7 @@ class Generator(generator.Generator):
exp.Substring: _substring_sql,
exp.TimeFromParts: rename_func("MAKE_TIME"),
exp.TimestampFromParts: rename_func("MAKE_TIMESTAMP"),
- exp.TimestampTrunc: timestamptrunc_sql,
+ exp.TimestampTrunc: timestamptrunc_sql(),
exp.TimeStrToTime: timestrtotime_sql,
exp.TimeToStr: lambda self, e: self.func("TO_CHAR", e.this, self.format_time(e)),
exp.ToChar: lambda self, e: self.function_fallback_sql(e),
diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py
index a52cee12f1..1285281c7d 100644
--- a/sqlglot/dialects/presto.py
+++ b/sqlglot/dialects/presto.py
@@ -420,7 +420,7 @@ class Generator(generator.Generator):
exp.StructExtract: struct_extract_sql,
exp.Table: transforms.preprocess([_unnest_sequence]),
exp.Timestamp: no_timestamp_sql,
- exp.TimestampTrunc: timestamptrunc_sql,
+ exp.TimestampTrunc: timestamptrunc_sql(),
exp.TimeStrToDate: timestrtotime_sql,
exp.TimeStrToTime: timestrtotime_sql,
exp.TimeStrToUnix: lambda self, e: self.func(
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index 9625faad51..c98fe6f669 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -843,7 +843,7 @@ class Generator(generator.Generator):
exp.TimestampDiff: lambda self, e: self.func(
"TIMESTAMPDIFF", e.unit, e.expression, e.this
),
- exp.TimestampTrunc: timestamptrunc_sql,
+ exp.TimestampTrunc: timestamptrunc_sql(),
exp.TimeStrToTime: timestrtotime_sql,
exp.TimeToStr: lambda self, e: self.func(
"TO_CHAR", exp.cast(e.this, exp.DataType.Type.TIMESTAMP), self.format_time(e)
| diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py
index 66251114bb..7bd892e542 100644
--- a/tests/dialects/test_dialect.py
+++ b/tests/dialects/test_dialect.py
@@ -1019,6 +1019,19 @@ def test_time(self):
},
)
+ self.validate_all(
+ "TIMESTAMP_TRUNC(x, DAY, 'UTC')",
+ write={
+ "": "TIMESTAMP_TRUNC(x, DAY, 'UTC')",
+ "duckdb": "DATE_TRUNC('DAY', x)",
+ "presto": "DATE_TRUNC('DAY', x)",
+ "postgres": "DATE_TRUNC('DAY', x)",
+ "snowflake": "DATE_TRUNC('DAY', x)",
+ "databricks": "DATE_TRUNC('DAY', x)",
+ "clickhouse": "DATE_TRUNC('DAY', x, 'UTC')",
+ },
+ )
+
for unit in ("DAY", "MONTH", "YEAR"):
self.validate_all(
f"{unit}(x)",
diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py
index bc2c63f54a..03dea9389c 100644
--- a/tests/dialects/test_duckdb.py
+++ b/tests/dialects/test_duckdb.py
@@ -742,6 +742,28 @@ def test_duckdb(self):
)
self.validate_identity("COPY lineitem (l_orderkey) TO 'orderkey.tbl' WITH (DELIMITER '|')")
+ self.validate_all(
+ "VARIANCE(a)",
+ write={
+ "duckdb": "VARIANCE(a)",
+ "clickhouse": "varSamp(a)",
+ },
+ )
+ self.validate_all(
+ "STDDEV(a)",
+ write={
+ "duckdb": "STDDEV(a)",
+ "clickhouse": "stddevSamp(a)",
+ },
+ )
+ self.validate_all(
+ "DATE_TRUNC('DAY', x)",
+ write={
+ "duckdb": "DATE_TRUNC('DAY', x)",
+ "clickhouse": "DATE_TRUNC('DAY', x)",
+ },
+ )
+
def test_array_index(self):
with self.assertLogs(helper_logger) as cm:
self.validate_all(
| [] | [
"tests/dialects/test_dialect.py::TestDialect::test_time",
"tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb"
] | [
"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_defin... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(clickhouse): support generate TimestampTrunc, Variance, Stddev
References:
* https://clickhouse.com/docs/en/sql-reference/functions/date-time-functions#date_trunc
* https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/varsamp
* https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/stddevsamp
----------
</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>
</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-bigquery-1919 | 1,919 | googleapis/python-bigquery | null | 32b2c35d7ea5312b0da344518f56985a967ddd0b | 2024-05-15T18:43:00Z | diff --git a/google/cloud/bigquery/format_options.py b/google/cloud/bigquery/format_options.py
index 1208565a9..ad5591b1c 100644
--- a/google/cloud/bigquery/format_options.py
+++ b/google/cloud/bigquery/format_options.py
@@ -105,6 +105,21 @@ def enable_list_inference(self) -> bool:
def enable_list_inference(self, value: bool) -> None:
self._properties["enableListInference"] = value
+ @property
+ def map_target_type(self) -> str:
+ """Indicates whether to simplify the representation of parquet maps to only show keys and values."""
+
+ return self._properties.get("mapTargetType")
+
+ @map_target_type.setter
+ def map_target_type(self, value: str) -> None:
+ """Sets the map target type.
+
+ Args:
+ value: The map target type (eg ARRAY_OF_STRUCT).
+ """
+ self._properties["mapTargetType"] = value
+
@classmethod
def from_api_repr(cls, resource: Dict[str, bool]) -> "ParquetOptions":
"""Factory: construct an instance from a resource dict.
| diff --git a/tests/unit/test_format_options.py b/tests/unit/test_format_options.py
index c8fecbfa6..94a01570f 100644
--- a/tests/unit/test_format_options.py
+++ b/tests/unit/test_format_options.py
@@ -54,11 +54,17 @@ def test_from_api_repr(self):
)
assert not config.enum_as_string
assert config.enable_list_inference
+ assert config.map_target_type is None
def test_to_api_repr(self):
config = self._get_target_class()()
config.enum_as_string = True
config.enable_list_inference = False
+ config.map_target_type = "ARRAY_OF_STRUCT"
result = config.to_api_repr()
- assert result == {"enumAsString": True, "enableListInference": False}
+ assert result == {
+ "enumAsString": True,
+ "enableListInference": False,
+ "mapTargetType": "ARRAY_OF_STRUCT",
+ }
| [
{
"components": [
{
"doc": "Sets the map target type.\n\nArgs:\n value: The map target type (eg ARRAY_OF_STRUCT).",
"lines": [
115,
121
],
"name": "ParquetOptions.map_target_type",
"signature": "def map_target_type(self, value: str) -> None:",
... | [
"tests/unit/test_format_options.py::TestParquetOptions::test_from_api_repr",
"tests/unit/test_format_options.py::TestParquetOptions::test_to_api_repr"
] | [
"tests/unit/test_format_options.py::TestAvroOptions::test_ctor",
"tests/unit/test_format_options.py::TestAvroOptions::test_from_api_repr",
"tests/unit/test_format_options.py::TestAvroOptions::test_to_api_repr",
"tests/unit/test_format_options.py::TestParquetOptions::test_ctor"
] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: add support for map target type in Parquet options
The map target type creates a schema without the added key_value repeated field.
----------
</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 google/cloud/bigquery/format_options.py]
(definition of ParquetOptions.map_target_type:)
def map_target_type(self, value: str) -> None:
"""Sets the map target type.
Args:
value: The map target type (eg ARRAY_OF_STRUCT)."""
[end of new definitions in google/cloud/bigquery/format_options.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>> | 3359ef37b90243bea2d9e68bb996fe5d736f304c | ||
tobymao__sqlglot-3485 | 3,485 | tobymao/sqlglot | null | 6e7f37af86a4f36ec47ea4ef3519e5c97376e090 | 2024-05-15T14:29:44Z | diff --git a/sqlglot/dialects/athena.py b/sqlglot/dialects/athena.py
index f2deec8820..5fc7e52422 100644
--- a/sqlglot/dialects/athena.py
+++ b/sqlglot/dialects/athena.py
@@ -13,6 +13,8 @@ class Parser(Trino.Parser):
}
class Generator(Trino.Generator):
+ WITH_PROPERTIES_PREFIX = "TBLPROPERTIES"
+
PROPERTIES_LOCATION = {
**Trino.Generator.PROPERTIES_LOCATION,
exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
@@ -32,6 +34,3 @@ def property_sql(self, expression: exp.Property) -> str:
return (
f"{self.property_name(expression, string_key=True)}={self.sql(expression, 'value')}"
)
-
- def with_properties(self, properties: exp.Properties) -> str:
- return self.properties(properties, prefix=self.seg("TBLPROPERTIES"))
diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py
index 900b1e715a..47fb0ce628 100644
--- a/sqlglot/dialects/bigquery.py
+++ b/sqlglot/dialects/bigquery.py
@@ -570,6 +570,7 @@ class Generator(generator.Generator):
SUPPORTS_TO_NUMBER = False
NAMED_PLACEHOLDER_TOKEN = "@"
HEX_FUNC = "TO_HEX"
+ WITH_PROPERTIES_PREFIX = "OPTIONS"
TRANSFORMS = {
**generator.Generator.TRANSFORMS,
@@ -907,9 +908,6 @@ def intersect_op(self, expression: exp.Intersect) -> str:
self.unsupported("INTERSECT without DISTINCT is not supported in BigQuery")
return f"INTERSECT{' DISTINCT' if expression.args.get('distinct') else ' ALL'}"
- def with_properties(self, properties: exp.Properties) -> str:
- return self.properties(properties, prefix=self.seg("OPTIONS"))
-
def version_sql(self, expression: exp.Version) -> str:
if expression.name == "TIMESTAMP":
expression.set("this", "SYSTEM_TIME")
diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py
index 2f746c09f0..b12e2002fd 100644
--- a/sqlglot/dialects/hive.py
+++ b/sqlglot/dialects/hive.py
@@ -254,7 +254,7 @@ class Tokenizer(tokens.Tokenizer):
"REFRESH": TokenType.REFRESH,
"TIMESTAMP AS OF": TokenType.TIMESTAMP_SNAPSHOT,
"VERSION AS OF": TokenType.VERSION_SNAPSHOT,
- "WITH SERDEPROPERTIES": TokenType.SERDE_PROPERTIES,
+ "SERDEPROPERTIES": TokenType.SERDE_PROPERTIES,
}
NUMERIC_LITERALS = {
@@ -332,7 +332,7 @@ class Parser(parser.Parser):
PROPERTY_PARSERS = {
**parser.Parser.PROPERTY_PARSERS,
- "WITH SERDEPROPERTIES": lambda self: exp.SerdeProperties(
+ "SERDEPROPERTIES": lambda self: exp.SerdeProperties(
expressions=self._parse_wrapped_csv(self._parse_property)
),
}
@@ -443,6 +443,7 @@ class Generator(generator.Generator):
LAST_DAY_SUPPORTS_DATE_PART = False
JSON_PATH_SINGLE_QUOTE_ESCAPE = True
SUPPORTS_TO_NUMBER = False
+ WITH_PROPERTIES_PREFIX = "TBLPROPERTIES"
EXPRESSIONS_WITHOUT_NESTED_CTES = {
exp.Insert,
@@ -562,7 +563,6 @@ class Generator(generator.Generator):
exp.UnixToTime: _unix_to_time_sql,
exp.UnixToTimeStr: rename_func("FROM_UNIXTIME"),
exp.PartitionedByProperty: lambda self, e: f"PARTITIONED BY {self.sql(e, 'this')}",
- exp.SerdeProperties: lambda self, e: self.properties(e, prefix="WITH SERDEPROPERTIES"),
exp.NumberToStr: rename_func("FORMAT_NUMBER"),
exp.National: lambda self, e: self.national_sql(e, prefix=""),
exp.ClusteredColumnConstraint: lambda self,
@@ -628,9 +628,6 @@ def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
expression.this.this if isinstance(expression.this, exp.Order) else expression.this,
)
- def with_properties(self, properties: exp.Properties) -> str:
- return self.properties(properties, prefix=self.seg("TBLPROPERTIES"))
-
def datatype_sql(self, expression: exp.DataType) -> str:
if expression.this in self.PARAMETERIZABLE_TEXT_TYPES and (
not expression.expressions or expression.expressions[0].name == "MAX"
@@ -665,3 +662,23 @@ def struct_sql(self, expression: exp.Struct) -> str:
values.append(e)
return self.func("STRUCT", *values)
+
+ def alterset_sql(self, expression: exp.AlterSet) -> str:
+ exprs = self.expressions(expression, flat=True)
+ exprs = f" {exprs}" if exprs else ""
+ location = self.sql(expression, "location")
+ location = f" LOCATION {location}" if location else ""
+ file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
+ file_format = f" FILEFORMAT {file_format}" if file_format else ""
+ serde = self.sql(expression, "serde")
+ serde = f" SERDE {serde}" if serde else ""
+ tags = self.expressions(expression, key="tag", flat=True, sep="")
+ tags = f" TAGS {tags}" if tags else ""
+
+ return f"SET{serde}{exprs}{location}{file_format}{tags}"
+
+ def serdeproperties_sql(self, expression: exp.SerdeProperties) -> str:
+ prefix = "WITH " if expression.args.get("with") else ""
+ exprs = self.expressions(expression, flat=True)
+
+ return f"{prefix}SERDEPROPERTIES ({exprs})"
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py
index 953f45d403..03a493e767 100644
--- a/sqlglot/dialects/postgres.py
+++ b/sqlglot/dialects/postgres.py
@@ -609,3 +609,15 @@ def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
expressions = [f"{self.sql(e)} @@ {this}" for e in expression.expressions]
sql = " OR ".join(expressions)
return f"({sql})" if len(expressions) > 1 else sql
+
+ def alterset_sql(self, expression: exp.AlterSet) -> str:
+ exprs = self.expressions(expression, flat=True)
+ exprs = f"({exprs})" if exprs else ""
+
+ access_method = self.sql(expression, "access_method")
+ access_method = f"ACCESS METHOD {access_method}" if access_method else ""
+ tablespace = self.sql(expression, "tablespace")
+ tablespace = f"TABLESPACE {tablespace}" if tablespace else ""
+ option = self.sql(expression, "option")
+
+ return f"SET {exprs}{access_method}{tablespace}{option}"
diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py
index 656c5ba67e..d3388e7ac7 100644
--- a/sqlglot/dialects/redshift.py
+++ b/sqlglot/dialects/redshift.py
@@ -142,6 +142,8 @@ class Generator(Postgres.Generator):
MULTI_ARG_DISTINCT = True
COPY_PARAMS_ARE_WRAPPED = False
HEX_FUNC = "TO_HEX"
+ # Redshift doesn't have `WITH` as part of their with_properties so we remove it
+ WITH_PROPERTIES_PREFIX = " "
TYPE_MAPPING = {
**Postgres.Generator.TYPE_MAPPING,
@@ -375,10 +377,6 @@ def unnest_sql(self, expression: exp.Unnest) -> str:
alias = self.expressions(expression.args.get("alias"), key="columns", flat=True)
return f"{arg} AS {alias}" if alias else arg
- def with_properties(self, properties: exp.Properties) -> str:
- """Redshift doesn't have `WITH` as part of their with_properties so we remove it"""
- return self.properties(properties, prefix=" ", suffix="")
-
def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
if expression.is_type(exp.DataType.Type.JSON):
# Redshift doesn't support a JSON type, so casting to it is treated as a noop
@@ -401,3 +399,13 @@ def datatype_sql(self, expression: exp.DataType) -> str:
expression.append("expressions", exp.var("MAX"))
return super().datatype_sql(expression)
+
+ def alterset_sql(self, expression: exp.AlterSet) -> str:
+ exprs = self.expressions(expression, flat=True)
+ exprs = f" TABLE PROPERTIES ({exprs})" if exprs else ""
+ location = self.sql(expression, "location")
+ location = f" LOCATION {location}" if location else ""
+ file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
+ file_format = f" FILE FORMAT {file_format}" if file_format else ""
+
+ return f"SET{exprs}{location}{file_format}"
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index 1233961206..c35b2c3e95 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -426,7 +426,6 @@ class Parser(parser.Parser):
ALTER_PARSERS = {
**parser.Parser.ALTER_PARSERS,
- "SET": lambda self: self._parse_set(tag=self._match_text_seq("TAG")),
"UNSET": lambda self: self.expression(
exp.Set,
tag=self._match_text_seq("TAG"),
@@ -773,6 +772,9 @@ class Generator(generator.Generator):
COPY_PARAMS_ARE_WRAPPED = False
COPY_PARAMS_EQ_REQUIRED = True
STAR_EXCEPT = "EXCLUDE"
+ WITH_PROPERTIES_PREFIX = ""
+ WITH_PROPERTIES_SEP = " "
+ WITH_PROPERTIES_WRAPPED = False
TRANSFORMS = {
**generator.Generator.TRANSFORMS,
@@ -1042,9 +1044,6 @@ def swaptable_sql(self, expression: exp.SwapTable) -> str:
this = self.sql(expression, "this")
return f"SWAP WITH {this}"
- def with_properties(self, properties: exp.Properties) -> str:
- return self.properties(properties, wrapped=False, prefix=self.seg(""), sep=" ")
-
def cluster_sql(self, expression: exp.Cluster) -> str:
return f"CLUSTER BY ({self.expressions(expression, flat=True)})"
@@ -1071,3 +1070,15 @@ def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
)
return self.func("APPROX_PERCENTILE", expression.this, expression.args.get("quantile"))
+
+ def alterset_sql(self, expression: exp.AlterSet) -> str:
+ exprs = self.expressions(expression, flat=True)
+ exprs = f" {exprs}" if exprs else ""
+ file_format = self.expressions(expression, key="file_format", flat=True, sep=" ")
+ file_format = f" STAGE_FILE_FORMAT = ({file_format})" if file_format else ""
+ copy_options = self.expressions(expression, key="copy_options", flat=True, sep=" ")
+ copy_options = f" STAGE_COPY_OPTIONS = ({copy_options})" if copy_options else ""
+ tag = self.expressions(expression, key="tag", flat=True)
+ tag = f" TAG {tag}" if tag else ""
+
+ return f"SET{exprs}{file_format}{copy_options}{tag}"
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index eae1bb0725..52b48dc95d 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -1644,6 +1644,20 @@ class AlterSortKey(Expression):
arg_types = {"this": False, "expressions": False, "compound": False}
+class AlterSet(Expression):
+ arg_types = {
+ "expressions": False,
+ "option": False,
+ "tablespace": False,
+ "access_method": False,
+ "file_format": False,
+ "copy_options": False,
+ "tag": False,
+ "location": False,
+ "serde": False,
+ }
+
+
class RenameColumn(Expression):
arg_types = {"this": True, "to": True, "exists": False}
@@ -2506,6 +2520,10 @@ class DataBlocksizeProperty(Property):
}
+class DataDeletionProperty(Property):
+ arg_types = {"on": True, "filter_col": False, "retention_period": False}
+
+
class DefinerProperty(Property):
arg_types = {"this": True}
@@ -2728,7 +2746,7 @@ class SchemaCommentProperty(Property):
class SerdeProperties(Property):
- arg_types = {"expressions": True}
+ arg_types = {"expressions": True, "with": False}
class SetProperty(Property):
@@ -2797,8 +2815,13 @@ class WithJournalTableProperty(Property):
class WithSystemVersioningProperty(Property):
- # this -> history table name, expression -> data consistency check
- arg_types = {"this": False, "expression": False}
+ arg_types = {
+ "on": False,
+ "this": False,
+ "data_consistency": False,
+ "retention_period": False,
+ "with": True,
+ }
class Properties(Expression):
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index 4ec5935c5c..cca06c47fc 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -359,6 +359,11 @@ class Generator(metaclass=_Generator):
# The HEX function name
HEX_FUNC = "HEX"
+ # The keywords to use when prefixing & separating WITH based properties
+ WITH_PROPERTIES_PREFIX = "WITH"
+ WITH_PROPERTIES_SEP = ", "
+ WITH_PROPERTIES_WRAPPED = True
+
TYPE_MAPPING = {
exp.DataType.Type.NCHAR: "CHAR",
exp.DataType.Type.NVARCHAR: "VARCHAR",
@@ -417,6 +422,7 @@ class Generator(metaclass=_Generator):
exp.Cluster: exp.Properties.Location.POST_SCHEMA,
exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
+ exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA,
exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
exp.DictRange: exp.Properties.Location.POST_SCHEMA,
exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
@@ -958,6 +964,12 @@ def create_sql(self, expression: exp.Create) -> str:
)
)
+ if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
+ properties_sql = self.sep() + properties_sql
+ elif not self.pretty:
+ # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
+ properties_sql = f" {properties_sql}"
+
begin = " BEGIN" if expression.args.get("begin") else ""
end = " END" if expression.args.get("end") else ""
@@ -1343,13 +1355,17 @@ def properties_sql(self, expression: exp.Properties) -> str:
elif p_loc == exp.Properties.Location.POST_SCHEMA:
root_properties.append(p)
- return self.root_properties(
- exp.Properties(expressions=root_properties)
- ) + self.with_properties(exp.Properties(expressions=with_properties))
+ root_props = self.root_properties(exp.Properties(expressions=root_properties))
+ with_props = self.with_properties(exp.Properties(expressions=with_properties))
+
+ if root_props and with_props and not self.pretty:
+ with_props = " " + with_props
+
+ return root_props + with_props
def root_properties(self, properties: exp.Properties) -> str:
if properties.expressions:
- return self.sep() + self.expressions(properties, indent=False, sep=" ")
+ return self.expressions(properties, indent=False, sep=" ")
return ""
def properties(
@@ -1368,7 +1384,12 @@ def properties(
return ""
def with_properties(self, properties: exp.Properties) -> str:
- return self.properties(properties, prefix=self.seg("WITH"))
+ return self.properties(
+ properties,
+ wrapped=self.WITH_PROPERTIES_WRAPPED,
+ prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""),
+ sep=self.WITH_PROPERTIES_SEP,
+ )
def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
properties_locs = defaultdict(list)
@@ -1536,19 +1557,25 @@ def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
return f"{data_sql}{statistics_sql}"
def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
- sql = "WITH(SYSTEM_VERSIONING=ON"
-
- if expression.this:
- history_table = self.sql(expression, "this")
- sql = f"{sql}(HISTORY_TABLE={history_table}"
+ this = self.sql(expression, "this")
+ this = f"HISTORY_TABLE={this}" if this else ""
+ data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
+ data_consistency = (
+ f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
+ )
+ retention_period: t.Optional[str] = self.sql(expression, "retention_period")
+ retention_period = (
+ f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
+ )
- if expression.expression:
- data_consistency_check = self.sql(expression, "expression")
- sql = f"{sql}, DATA_CONSISTENCY_CHECK={data_consistency_check}"
+ if this:
+ on_sql = self.func("ON", this, data_consistency, retention_period)
+ else:
+ on_sql = "ON" if expression.args.get("on") else "OFF"
- sql = f"{sql})"
+ sql = f"SYSTEM_VERSIONING={on_sql}"
- return f"{sql})"
+ return f"WITH({sql})" if expression.args.get("with") else sql
def insert_sql(self, expression: exp.Insert) -> str:
hint = self.sql(expression, "hint")
@@ -3031,6 +3058,10 @@ def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
new_column = self.sql(expression, "to")
return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
+ def alterset_sql(self, expression: exp.AlterSet) -> str:
+ exprs = self.expressions(expression, flat=True)
+ return f"SET {exprs}"
+
def altertable_sql(self, expression: exp.AlterTable) -> str:
actions = expression.args["actions"]
@@ -3889,3 +3920,15 @@ def copy_sql(self, expression: exp.Copy) -> str:
def semicolon_sql(self, expression: exp.Semicolon) -> str:
return ""
+
+ def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
+ on_sql = "ON" if expression.args.get("on") else "OFF"
+ filter_col: t.Optional[str] = self.sql(expression, "filter_column")
+ filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
+ retention_period: t.Optional[str] = self.sql(expression, "retention_period")
+ retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
+
+ if filter_col or retention_period:
+ on_sql = self.func("ON", filter_col, retention_period)
+
+ return f"DATA_DELETION={on_sql}"
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index f290b67779..e292f22677 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -791,6 +791,7 @@ class Parser(metaclass=_Parser):
"CONTAINS": lambda self: self._parse_contains_property(),
"COPY": lambda self: self._parse_copy_property(),
"DATABLOCKSIZE": lambda self, **kwargs: self._parse_datablocksize(**kwargs),
+ "DATA_DELETION": lambda self: self._parse_data_deletion_property(),
"DEFINER": lambda self: self._parse_definer(),
"DETERMINISTIC": lambda self: self.expression(
exp.StabilityProperty, this=exp.Literal.string("IMMUTABLE")
@@ -943,6 +944,7 @@ class Parser(metaclass=_Parser):
"DELETE": lambda self: self.expression(exp.Delete, where=self._parse_where()),
"DROP": lambda self: self._parse_alter_table_drop(),
"RENAME": lambda self: self._parse_alter_table_rename(),
+ "SET": lambda self: self._parse_alter_table_set(),
}
ALTER_ALTER_PARSERS = {
@@ -1884,23 +1886,65 @@ def _parse_volatile_property(self) -> exp.VolatileProperty | exp.StabilityProper
return self.expression(exp.StabilityProperty, this=exp.Literal.string("VOLATILE"))
- def _parse_system_versioning_property(self) -> exp.WithSystemVersioningProperty:
- self._match_pair(TokenType.EQ, TokenType.ON)
+ def _parse_retention_period(self) -> exp.Var:
+ # Parse TSQL's HISTORY_RETENTION_PERIOD: {INFINITE | <number> DAY | DAYS | MONTH ...}
+ number = self._parse_number()
+ number_str = f"{number} " if number else ""
+ unit = self._parse_var(any_token=True)
+ return exp.var(f"{number_str}{unit}")
- prop = self.expression(exp.WithSystemVersioningProperty)
+ def _parse_system_versioning_property(
+ self, with_: bool = False
+ ) -> exp.WithSystemVersioningProperty:
+ self._match(TokenType.EQ)
+ prop = self.expression(
+ exp.WithSystemVersioningProperty,
+ **{ # type: ignore
+ "on": True,
+ "with": with_,
+ },
+ )
+
+ if self._match_text_seq("OFF"):
+ prop.set("on", False)
+ return prop
+
+ self._match(TokenType.ON)
if self._match(TokenType.L_PAREN):
- self._match_text_seq("HISTORY_TABLE", "=")
- prop.set("this", self._parse_table_parts())
+ while self._curr and not self._match(TokenType.R_PAREN):
+ if self._match_text_seq("HISTORY_TABLE", "="):
+ prop.set("this", self._parse_table_parts())
+ elif self._match_text_seq("DATA_CONSISTENCY_CHECK", "="):
+ prop.set("data_consistency", self._advance_any() and self._prev.text.upper())
+ elif self._match_text_seq("HISTORY_RETENTION_PERIOD", "="):
+ prop.set("retention_period", self._parse_retention_period())
- if self._match(TokenType.COMMA):
- self._match_text_seq("DATA_CONSISTENCY_CHECK", "=")
- prop.set("expression", self._advance_any() and self._prev.text.upper())
+ self._match(TokenType.COMMA)
- self._match_r_paren()
+ return prop
+
+ def _parse_data_deletion_property(self) -> exp.DataDeletionProperty:
+ self._match(TokenType.EQ)
+ on = self._match_text_seq("ON") or not self._match_text_seq("OFF")
+ prop = self.expression(exp.DataDeletionProperty, on=on)
+
+ if self._match(TokenType.L_PAREN):
+ while self._curr and not self._match(TokenType.R_PAREN):
+ if self._match_text_seq("FILTER_COLUMN", "="):
+ prop.set("filter_column", self._parse_column())
+ elif self._match_text_seq("RETENTION_PERIOD", "="):
+ prop.set("retention_period", self._parse_retention_period())
+
+ self._match(TokenType.COMMA)
return prop
def _parse_with_property(self) -> t.Optional[exp.Expression] | t.List[exp.Expression]:
+ if self._match_text_seq("(", "SYSTEM_VERSIONING"):
+ prop = self._parse_system_versioning_property(with_=True)
+ self._match_r_paren()
+ return prop
+
if self._match(TokenType.L_PAREN, advance=False):
return self._parse_wrapped_properties()
@@ -1915,6 +1959,9 @@ def _parse_with_property(self) -> t.Optional[exp.Expression] | t.List[exp.Expres
elif self._match_text_seq("NO", "DATA"):
return self._parse_withdata(no=True)
+ if self._match(TokenType.SERDE_PROPERTIES, advance=False):
+ return self._parse_serde_properties(with_=True)
+
if not self._next:
return None
@@ -2402,6 +2449,21 @@ def _parse_row(self) -> t.Optional[exp.RowFormatSerdeProperty | exp.RowFormatDel
return None
return self._parse_row_format()
+ def _parse_serde_properties(self, with_: bool = False) -> t.Optional[exp.SerdeProperties]:
+ index = self._index
+ with_ = with_ or self._match_text_seq("WITH")
+
+ if not self._match(TokenType.SERDE_PROPERTIES):
+ self._retreat(index)
+ return None
+ return self.expression(
+ exp.SerdeProperties,
+ **{ # type: ignore
+ "expressions": self._parse_wrapped_properties(),
+ "with": with_,
+ },
+ )
+
def _parse_row_format(
self, match_row: bool = False
) -> t.Optional[exp.RowFormatSerdeProperty | exp.RowFormatDelimitedProperty]:
@@ -2411,11 +2473,7 @@ def _parse_row_format(
if self._match_text_seq("SERDE"):
this = self._parse_string()
- serde_properties = None
- if self._match(TokenType.SERDE_PROPERTIES):
- serde_properties = self.expression(
- exp.SerdeProperties, expressions=self._parse_wrapped_properties()
- )
+ serde_properties = self._parse_serde_properties()
return self.expression(
exp.RowFormatSerdeProperty, this=this, serde_properties=serde_properties
@@ -5942,6 +6000,41 @@ def _parse_alter_table_rename(self) -> t.Optional[exp.RenameTable | exp.RenameCo
self._match_text_seq("TO")
return self.expression(exp.RenameTable, this=self._parse_table(schema=True))
+ def _parse_alter_table_set(self) -> exp.AlterSet:
+ alter_set = self.expression(exp.AlterSet)
+
+ if self._match(TokenType.L_PAREN, advance=False) or self._match_text_seq(
+ "TABLE", "PROPERTIES"
+ ):
+ alter_set.set("expressions", self._parse_wrapped_csv(self._parse_conjunction))
+ elif self._match_text_seq("FILESTREAM_ON", advance=False):
+ alter_set.set("expressions", [self._parse_conjunction()])
+ elif self._match_texts(("LOGGED", "UNLOGGED")):
+ alter_set.set("option", exp.var(self._prev.text.upper()))
+ elif self._match_text_seq("WITHOUT") and self._match_texts(("CLUSTER", "OIDS")):
+ alter_set.set("option", exp.var(f"WITHOUT {self._prev.text.upper()}"))
+ elif self._match_text_seq("LOCATION"):
+ alter_set.set("location", self._parse_field())
+ elif self._match_text_seq("ACCESS", "METHOD"):
+ alter_set.set("access_method", self._parse_field())
+ elif self._match_text_seq("TABLESPACE"):
+ alter_set.set("tablespace", self._parse_field())
+ elif self._match_text_seq("FILE", "FORMAT") or self._match_text_seq("FILEFORMAT"):
+ alter_set.set("file_format", [self._parse_field()])
+ elif self._match_text_seq("STAGE_FILE_FORMAT"):
+ alter_set.set("file_format", self._parse_wrapped_options())
+ elif self._match_text_seq("STAGE_COPY_OPTIONS"):
+ alter_set.set("copy_options", self._parse_wrapped_options())
+ elif self._match_text_seq("TAG") or self._match_text_seq("TAGS"):
+ alter_set.set("tag", self._parse_csv(self._parse_conjunction))
+ else:
+ if self._match_text_seq("SERDE"):
+ alter_set.set("serde", self._parse_field())
+
+ alter_set.set("expressions", [self._parse_properties()])
+
+ return alter_set
+
def _parse_alter(self) -> exp.AlterTable | exp.Command:
start = self._prev
| diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py
index 6b6117eac5..245994629e 100644
--- a/tests/dialects/test_postgres.py
+++ b/tests/dialects/test_postgres.py
@@ -733,6 +733,13 @@ def test_ddl(self):
self.validate_identity("TRUNCATE TABLE t1 RESTRICT")
self.validate_identity("TRUNCATE TABLE t1 CONTINUE IDENTITY CASCADE")
self.validate_identity("TRUNCATE TABLE t1 RESTART IDENTITY RESTRICT")
+ self.validate_identity("ALTER TABLE t1 SET LOGGED")
+ self.validate_identity("ALTER TABLE t1 SET UNLOGGED")
+ self.validate_identity("ALTER TABLE t1 SET WITHOUT CLUSTER")
+ self.validate_identity("ALTER TABLE t1 SET WITHOUT OIDS")
+ self.validate_identity("ALTER TABLE t1 SET ACCESS METHOD method")
+ self.validate_identity("ALTER TABLE t1 SET TABLESPACE tablespace")
+ self.validate_identity("ALTER TABLE t1 SET (fillfactor = 5, autovacuum_enabled = TRUE)")
self.validate_identity(
"CREATE TABLE t (vid INT NOT NULL, CONSTRAINT ht_vid_nid_fid_idx EXCLUDE (INT4RANGE(vid, nid) WITH &&, INT4RANGE(fid, fid, '[]') WITH &&))"
)
diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py
index 2b29a94bb0..3925e3256d 100644
--- a/tests/dialects/test_redshift.py
+++ b/tests/dialects/test_redshift.py
@@ -509,6 +509,9 @@ def test_alter_table(self):
self.validate_identity("ALTER TABLE t ALTER DISTSTYLE EVEN")
self.validate_identity("ALTER TABLE t ALTER DISTSTYLE AUTO")
self.validate_identity("ALTER TABLE t ALTER DISTSTYLE KEY DISTKEY c")
+ self.validate_identity("ALTER TABLE t SET TABLE PROPERTIES ('a' = '5', 'b' = 'c')")
+ self.validate_identity("ALTER TABLE t SET LOCATION 's3://bucket/folder/'")
+ self.validate_identity("ALTER TABLE t SET FILE FORMAT AVRO")
self.validate_identity(
"ALTER TABLE t ALTER DISTKEY c",
"ALTER TABLE t ALTER DISTSTYLE KEY DISTKEY c",
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py
index e868274538..91f780773d 100644
--- a/tests/dialects/test_snowflake.py
+++ b/tests/dialects/test_snowflake.py
@@ -45,7 +45,6 @@ def test_snowflake(self):
self.validate_identity("ALTER TABLE table1 CLUSTER BY (name DESC)")
self.validate_identity("SELECT rename, replace")
- self.validate_identity("ALTER TABLE table1 SET TAG foo.bar = 'baz'")
self.validate_identity("SELECT TIMEADD(HOUR, 2, CAST('09:05:03' AS TIME))")
self.validate_identity("SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS MAP(VARCHAR, INT))")
self.validate_identity("SELECT CAST(OBJECT_CONSTRUCT('a', 1) AS OBJECT(a CHAR NOT NULL))")
@@ -89,11 +88,6 @@ def test_snowflake(self):
self.validate_identity("a$b") # valid snowflake identifier
self.validate_identity("SELECT REGEXP_LIKE(a, b, c)")
self.validate_identity("CREATE TABLE foo (bar FLOAT AUTOINCREMENT START 0 INCREMENT 1)")
- self.validate_identity("ALTER TABLE IF EXISTS foo SET TAG a = 'a', b = 'b', c = 'c'")
- self.validate_identity("ALTER TABLE foo UNSET TAG a, b, c")
- self.validate_identity("ALTER TABLE foo SET COMMENT = 'bar'")
- self.validate_identity("ALTER TABLE foo SET CHANGE_TRACKING = FALSE")
- self.validate_identity("ALTER TABLE foo UNSET DATA_RETENTION_TIME_IN_DAYS, CHANGE_TRACKING")
self.validate_identity("COMMENT IF EXISTS ON TABLE foo IS 'bar'")
self.validate_identity("SELECT CONVERT_TIMEZONE('UTC', 'America/Los_Angeles', col)")
self.validate_identity("ALTER TABLE a SWAP WITH b")
@@ -1940,3 +1934,20 @@ def test_querying_semi_structured_data(self):
self.validate_identity("SELECT $1:a.b", "SELECT GET_PATH($1, 'a.b')")
self.validate_identity("SELECT t.$23:a.b", "SELECT GET_PATH(t.$23, 'a.b')")
self.validate_identity("SELECT t.$17:a[0].b[0].c", "SELECT GET_PATH(t.$17, 'a[0].b[0].c')")
+
+ def test_alter_set_unset(self):
+ self.validate_identity("ALTER TABLE tbl SET DATA_RETENTION_TIME_IN_DAYS=1")
+ self.validate_identity("ALTER TABLE tbl SET DEFAULT_DDL_COLLATION='test'")
+ self.validate_identity("ALTER TABLE foo SET COMMENT='bar'")
+ self.validate_identity("ALTER TABLE foo SET CHANGE_TRACKING=FALSE")
+ self.validate_identity("ALTER TABLE table1 SET TAG foo.bar = 'baz'")
+ self.validate_identity("ALTER TABLE IF EXISTS foo SET TAG a = 'a', b = 'b', c = 'c'")
+ self.validate_identity(
+ """ALTER TABLE tbl SET STAGE_FILE_FORMAT = (TYPE = CSV FIELD_DELIMITER = '|' NULL_IF = () FIELD_OPTIONALLY_ENCLOSED_BY = '"' TIMESTAMP_FORMAT = 'TZHTZM YYYY-MM-DD HH24:MI:SS.FF9' DATE_FORMAT = 'TZHTZM YYYY-MM-DD HH24:MI:SS.FF9' BINARY_FORMAT = BASE64)""",
+ )
+ self.validate_identity(
+ """ALTER TABLE tbl SET STAGE_COPY_OPTIONS = (ON_ERROR = SKIP_FILE SIZE_LIMIT = 5 PURGE = TRUE MATCH_BY_COLUMN_NAME = CASE_SENSITIVE)"""
+ )
+
+ self.validate_identity("ALTER TABLE foo UNSET TAG a, b, c")
+ self.validate_identity("ALTER TABLE foo UNSET DATA_RETENTION_TIME_IN_DAYS, CHANGE_TRACKING")
diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py
index ac28cb9dab..45a46579ed 100644
--- a/tests/dialects/test_tsql.py
+++ b/tests/dialects/test_tsql.py
@@ -192,16 +192,9 @@ def test_tsql(self):
)
self.validate_all(
- """
- CREATE TABLE x(
- [zip_cd] [varchar](5) NULL NOT FOR REPLICATION,
- [zip_cd_mkey] [varchar](5) NOT NULL,
- CONSTRAINT [pk_mytable] PRIMARY KEY CLUSTERED ([zip_cd_mkey] ASC)
- WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF) ON [INDEX]
- ) ON [SECONDARY]
- """,
+ """CREATE TABLE x ([zip_cd] VARCHAR(5) NULL NOT FOR REPLICATION, [zip_cd_mkey] VARCHAR(5) NOT NULL, CONSTRAINT [pk_mytable] PRIMARY KEY CLUSTERED ([zip_cd_mkey] ASC) WITH (PAD_INDEX=ON, STATISTICS_NORECOMPUTE=OFF) ON [INDEX]) ON [SECONDARY]""",
write={
- "tsql": "CREATE TABLE x ([zip_cd] VARCHAR(5) NULL NOT FOR REPLICATION, [zip_cd_mkey] VARCHAR(5) NOT NULL, CONSTRAINT [pk_mytable] PRIMARY KEY CLUSTERED ([zip_cd_mkey] ASC) WITH (PAD_INDEX=ON, STATISTICS_NORECOMPUTE=OFF) ON [INDEX]) ON [SECONDARY]",
+ "tsql": "CREATE TABLE x ([zip_cd] VARCHAR(5) NULL NOT FOR REPLICATION, [zip_cd_mkey] VARCHAR(5) NOT NULL, CONSTRAINT [pk_mytable] PRIMARY KEY CLUSTERED ([zip_cd_mkey] ASC) WITH (PAD_INDEX=ON, STATISTICS_NORECOMPUTE=OFF) ON [INDEX]) ON [SECONDARY]",
"spark2": "CREATE TABLE x (`zip_cd` VARCHAR(5), `zip_cd_mkey` VARCHAR(5) NOT NULL, CONSTRAINT `pk_mytable` PRIMARY KEY (`zip_cd_mkey`))",
},
)
@@ -770,18 +763,32 @@ def test_ddl(self):
expression.sql(dialect="tsql"), "ALTER TABLE dbo.DocExe DROP CONSTRAINT FK_Column_B"
)
- for clusterd_keyword in ("CLUSTERED", "NONCLUSTERED"):
+ for clustered_keyword in ("CLUSTERED", "NONCLUSTERED"):
self.validate_identity(
'CREATE TABLE "dbo"."benchmark" ('
'"name" CHAR(7) NOT NULL, '
'"internal_id" VARCHAR(10) NOT NULL, '
- f'UNIQUE {clusterd_keyword} ("internal_id" ASC))',
+ f'UNIQUE {clustered_keyword} ("internal_id" ASC))',
"CREATE TABLE [dbo].[benchmark] ("
"[name] CHAR(7) NOT NULL, "
"[internal_id] VARCHAR(10) NOT NULL, "
- f"UNIQUE {clusterd_keyword} ([internal_id] ASC))",
+ f"UNIQUE {clustered_keyword} ([internal_id] ASC))",
)
+ self.validate_identity(
+ "ALTER TABLE tbl SET SYSTEM_VERSIONING=ON(HISTORY_TABLE=db.tbl, DATA_CONSISTENCY_CHECK=OFF, HISTORY_RETENTION_PERIOD=5 DAYS)"
+ )
+ self.validate_identity(
+ "ALTER TABLE tbl SET SYSTEM_VERSIONING=ON(HISTORY_TABLE=db.tbl, HISTORY_RETENTION_PERIOD=INFINITE)"
+ )
+ self.validate_identity("ALTER TABLE tbl SET SYSTEM_VERSIONING=OFF")
+ self.validate_identity("ALTER TABLE tbl SET FILESTREAM_ON = 'test'")
+ self.validate_identity(
+ "ALTER TABLE tbl SET DATA_DELETION=ON(FILTER_COLUMN=col, RETENTION_PERIOD=5 MONTHS)"
+ )
+ self.validate_identity("ALTER TABLE tbl SET DATA_DELETION=ON")
+ self.validate_identity("ALTER TABLE tbl SET DATA_DELETION=OFF")
+
self.validate_identity(
"CREATE PROCEDURE foo AS BEGIN DELETE FROM bla WHERE foo < CURRENT_TIMESTAMP - 7 END",
"CREATE PROCEDURE foo AS BEGIN DELETE FROM bla WHERE foo < GETDATE() - 7 END",
diff --git a/tests/test_parser.py b/tests/test_parser.py
index 00d5a13aea..d5aeee2fba 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -856,6 +856,26 @@ def test_values_as_identifier(self):
with self.subTest(dialect):
self.assertEqual(parse_one(sql, dialect=dialect).sql(dialect=dialect), sql)
+ def test_alter_set(self):
+ sqls = [
+ "ALTER TABLE tbl SET TBLPROPERTIES ('x'='1', 'Z'='2')",
+ "ALTER TABLE tbl SET SERDE 'test' WITH SERDEPROPERTIES ('k'='v', 'kay'='vee')",
+ "ALTER TABLE tbl SET SERDEPROPERTIES ('k'='v', 'kay'='vee')",
+ "ALTER TABLE tbl SET LOCATION 'new_location'",
+ "ALTER TABLE tbl SET FILEFORMAT file_format",
+ "ALTER TABLE tbl SET TAGS ('tag1' = 't1', 'tag2' = 't2')",
+ ]
+
+ for dialect in (
+ "hive",
+ "spark2",
+ "spark",
+ "databricks",
+ ):
+ for sql in sqls:
+ with self.subTest(f"Testing query '{sql}' for dialect {dialect}"):
+ self.assertEqual(parse_one(sql, dialect=dialect).sql(dialect=dialect), sql)
+
def test_distinct_from(self):
self.assertIsInstance(parse_one("a IS DISTINCT FROM b OR c IS DISTINCT FROM d"), exp.Or)
| [] | [
"tests/dialects/test_snowflake.py::TestSnowflake::test_alter_set_unset",
"tests/dialects/test_tsql.py::TestTSQL::test_tsql"
] | [
"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_p... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat!: Add ALTER TABLE SET
Introduce support for `ALTER TABLE ... SET ...` across first class dialects.
Design notes:
----------------
- Create an `exp.AlterSet` node belonging in `ALTER_PARSERS` that will hold the arguments across all mentioned dialects
- Create `exp.DataDeletionProperty` to parse T-SQL's `DATA_DELETION` argument
- Modify `exp.WithSystemVersioningProperty` and `exp.SerdeProperties` to optionally include the `WITH` keyword as a boolean arg
- Utilize `parse_properties` as a catch-all since many options are parsed as such already & to parse simple statements like `ALTER TABLE ... SET <opt> = <val>` as "anonymous" `exp.Property` which solves the need of more manual parsing
Docs
-----------
[T-SQL](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-table-transact-sql?view=sql-server-ver16) | [Postgres](https://www.postgresql.org/docs/current/sql-altertable.html) | [Spark](https://spark.apache.org/docs/latest/sql-ref-syntax-ddl-alter-table.html) | [Hive](https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl) | [Databricks](https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-ddl-alter-table.html) | [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/alter-table) | [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html) | [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#alter_table_set_options_statement)
----------
</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>
</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 | ||
pydicom__pydicom-2056 | 2,056 | pydicom/pydicom | 2.4 | 81940957fe08f4124318edfc9309c989d76ab811 | 2024-05-14T00:06:13Z | diff --git a/doc/guides/decoding/decoder_options.rst b/doc/guides/decoding/decoder_options.rst
index 0caa0b58e6..7dbd9badc6 100644
--- a/doc/guides/decoding/decoder_options.rst
+++ b/doc/guides/decoding/decoder_options.rst
@@ -7,14 +7,15 @@ Pixel Data Decoder Options
.. currentmodule:: pydicom.pixels.decoders.base
The following applies to the functions and class methods that use the
-:doc:`pixels</reference/pixels>` backend for decoding pixel data. This includes functions
-such as :func:`~pydicom.pixels.pixel_array` and :func:`~pydicom.pixels.iter_pixels`
-as well as the following methods of the :class:`~Decoder` class:
+:doc:`pixels</reference/pixels>` backend for decoding pixel data:
-* :meth:`Decoder.as_array`
-* :meth:`Decoder.as_buffer`
-* :meth:`Decoder.iter_array`
-* :meth:`Decoder.iter_buffer`
+* :func:`~pydicom.pixels.pixel_array`
+* :func:`~pydicom.pixels.iter_pixels`
+* :func:`~pydicom.pixels.decompress`
+* :meth:`Decoder.as_array()<pydicom.pixels.Decoder.as_array>`
+* :meth:`Decoder.as_buffer()<pydicom.pixels.Decoder.as_buffer>`
+* :meth:`Decoder.iter_array()<pydicom.pixels.Decoder.iter_array>`
+* :meth:`Decoder.iter_buffer()<pydicom.pixels.Decoder.iter_array>`
*Image Pixel* Options
=====================
@@ -67,9 +68,13 @@ Image Processing Options
========================
The following options may be used with any transfer syntax for controlling the
-processing applied after decoding to a NumPy :class:`~numpy.ndarray` using
-:func:`~pydicom.pixels.pixel_array`, :func:`~pydicom.pixels.iter_pixels`,
-:meth:`Decoder.as_array` or :meth:`Decoder.iter_array`.
+processing applied after decoding using:
+
+* :func:`~pydicom.pixels.pixel_array`
+* :func:`~pydicom.pixels.iter_pixels`
+* :func:`~pydicom.pixels.decompress`
+* :meth:`Decoder.as_array()<pydicom.pixels.Decoder.as_array>`
+* :meth:`Decoder.iter_array()<pydicom.pixels.Decoder.iter_array>`
* `as_rgb`: :class:`bool` - if ``True`` (default) then convert pixel data with a
YCbCr :ref:`photometric interpretation<photometric_interpretation>`
diff --git a/doc/reference/pixels.rst b/doc/reference/pixels.rst
index 41e1474446..38282e6187 100644
--- a/doc/reference/pixels.rst
+++ b/doc/reference/pixels.rst
@@ -26,6 +26,8 @@ Utility functions
:toctree: generated/
as_pixel_options
+ compress
+ decompress
get_decoder
get_encoder
iter_pixels
diff --git a/doc/reference/pixels.utils.rst b/doc/reference/pixels.utils.rst
index 38024f45e6..31b2b40ee2 100644
--- a/doc/reference/pixels.utils.rst
+++ b/doc/reference/pixels.utils.rst
@@ -12,6 +12,8 @@ Pixel data related utility functions.
:toctree: generated/
as_pixel_options
+ compress
+ decompress
expand_ybr422
get_expected_length
get_image_pixel_ids
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index f8a79bd311..f5a5b5f06d 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -182,13 +182,15 @@ Enhancements
* Added two functions for returning pixel data as a NumPy :class:`~numpy.ndarray`
from a path to a dataset while minimizing memory-usage: :func:`~pydicom.pixels.pixel_array`
and :func:`~pydicom.pixels.iter_pixels`.
+* Added two functions for compressing and decompressing datasets using the new
+ decoding backend: :func:`~pydicom.pixels.compress` and :func:`~pydicom.pixels.decompress`.
* Added support for the following transfer syntaxes to :meth:`Dataset.compress()
<pydicom.dataset.Dataset.compress>` (:issue:`1997`):
- * *JPEG-LS Lossless* with :attr:`~pydicom.pixels.encoders.base.JPEGLSLosslessEncoder`
- * *JPEG-LS Near Lossless* with :attr:`~pydicom.pixels.encoders.base.JPEGLSNearLosslessEncoder`
- * *JPEG 2000 Lossless* with :attr:`~pydicom.pixels.encoders.base.JPEG2000LosslessEncoder`
- * *JPEG 2000* with :attr:`~pydicom.pixels.encoders.base.JPEG2000Encoder`
+ * *JPEG-LS Lossless* with :attr:`~pydicom.pixels.encoders.JPEGLSLosslessEncoder`
+ * *JPEG-LS Near Lossless* with :attr:`~pydicom.pixels.encoders.JPEGLSNearLosslessEncoder`
+ * *JPEG 2000 Lossless* with :attr:`~pydicom.pixels.encoders.JPEG2000LosslessEncoder`
+ * *JPEG 2000* with :attr:`~pydicom.pixels.encoders.JPEG2000Encoder`
See the :doc:`JPEG-LS</guides/encoding/jpeg_ls>` and :doc:`JPEG 2000
</guides/encoding/jpeg_2k>` encoding guides for more information.
@@ -285,7 +287,7 @@ Deprecations
* :func:`~pydicom.pixels.utils.reshape_pixel_array`
* :func:`~pydicom.pixels.utils.unpack_bits`
- * :func:`~pydicom.pixel_data_handlers.util.dtype_corrected_for_endianness` will be
+ * :func:`pydicom.pixel_data_handlers.util.dtype_corrected_for_endianness` will be
removed in v4.0.
diff --git a/src/pydicom/dataelem.py b/src/pydicom/dataelem.py
index 4e913be3b2..67170a5846 100644
--- a/src/pydicom/dataelem.py
+++ b/src/pydicom/dataelem.py
@@ -227,7 +227,7 @@ def __init__(
else:
self.value = value # calls property setter which will convert
self.file_tell = file_value_tell
- self.is_undefined_length = is_undefined_length
+ self.is_undefined_length: bool = is_undefined_length
self.private_creator: str | None = None
def validate(self, value: Any) -> None:
diff --git a/src/pydicom/pixels/__init__.py b/src/pydicom/pixels/__init__.py
index d4b1533964..9aaad4d23d 100644
--- a/src/pydicom/pixels/__init__.py
+++ b/src/pydicom/pixels/__init__.py
@@ -12,6 +12,8 @@
)
from pydicom.pixels.utils import (
as_pixel_options,
+ compress,
+ decompress,
iter_pixels,
pack_bits,
pixel_array,
diff --git a/src/pydicom/pixels/utils.py b/src/pydicom/pixels/utils.py
index c4aa8110b7..c13fdcdc51 100644
--- a/src/pydicom/pixels/utils.py
+++ b/src/pydicom/pixels/utils.py
@@ -19,10 +19,17 @@
from pydicom.charset import default_encoding
from pydicom._dicom_dict import DicomDictionary
-
+from pydicom.encaps import encapsulate, encapsulate_extended
from pydicom.misc import warn_and_log
from pydicom.tag import BaseTag
-from pydicom.uid import UID
+from pydicom.uid import (
+ UID,
+ JPEGLSNearLossless,
+ JPEG2000,
+ ExplicitVRLittleEndian,
+ generate_uid,
+)
+from pydicom.valuerep import VR
if TYPE_CHECKING: # pragma: no cover
from pydicom.dataset import Dataset
@@ -173,6 +180,8 @@ def _array_common(
def as_pixel_options(ds: "Dataset", **kwargs: Any) -> dict[str, Any]:
"""Return a dict containing the image pixel element values from `ds`.
+ .. versionadded:: 3.0
+
Parameters
----------
ds : pydicom.dataset.Dataset
@@ -223,6 +232,363 @@ def as_pixel_options(ds: "Dataset", **kwargs: Any) -> dict[str, Any]:
return opts
+def compress(
+ ds: "Dataset",
+ transfer_syntax_uid: str,
+ arr: "np.ndarray | None" = None,
+ *,
+ encoding_plugin: str = "",
+ encapsulate_ext: bool = False,
+ new_instance_uid: bool = True,
+ jls_error: int | None = None,
+ j2k_cr: list[float] | None = None,
+ j2k_psnr: list[float] | None = None,
+ **kwargs: Any,
+) -> "Dataset":
+ """Compress uncompressed pixel data and update `ds` in-place with the
+ resulting :dcm:`encapsulated<part05/sect_A.4.html>` codestream.
+
+ .. versionadded:: 3.0
+
+ The dataset `ds` must already have the following
+ :dcm:`Image Pixel<part03/sect_C.7.6.3.html>` module elements present
+ with correct values that correspond to the resulting compressed
+ pixel data:
+
+ * (0028,0002) *Samples per Pixel*
+ * (0028,0004) *Photometric Interpretation*
+ * (0028,0008) *Number of Frames* (if more than 1 frame will be present)
+ * (0028,0010) *Rows*
+ * (0028,0011) *Columns*
+ * (0028,0100) *Bits Allocated*
+ * (0028,0101) *Bits Stored*
+ * (0028,0103) *Pixel Representation*
+
+ If *Samples per Pixel* is greater than 1 then the following element
+ is also required:
+
+ * (0028,0006) *Planar Configuration*
+
+ This method will add the file meta dataset if none is present and add
+ or modify the following elements:
+
+ * (0002,0010) *Transfer Syntax UID*
+ * (7FE0,0010) *Pixel Data*
+
+ If the compressed pixel data is too large for encapsulation using a
+ basic offset table then an :dcm:`extended offset table
+ <part03/sect_C.7.6.3.html>` will also be used, in which case the
+ following elements will also be added:
+
+ * (7FE0,0001) *Extended Offset Table*
+ * (7FE0,0002) *Extended Offset Table Lengths*
+
+ If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
+ Instance UID* value will be generated.
+
+ **Supported Transfer Syntax UIDs**
+
+ +-----------------------------------------------+-----------+----------------------------------+
+ | UID | Plugins | Encoding Guide |
+ +------------------------+----------------------+ | |
+ | Name | Value | | |
+ +========================+======================+===========+==================================+
+ | *JPEG-LS Lossless* |1.2.840.10008.1.2.4.80| pyjpegls | :doc:`JPEG-LS |
+ +------------------------+----------------------+ | </guides/encoding/jpeg_ls>` |
+ | *JPEG-LS Near Lossless*|1.2.840.10008.1.2.4.81| | |
+ +------------------------+----------------------+-----------+----------------------------------+
+ | *JPEG 2000 Lossless* |1.2.840.10008.1.2.4.90| pylibjpeg | :doc:`JPEG 2000 |
+ +------------------------+----------------------+ | </guides/encoding/jpeg_2k>` |
+ | *JPEG 2000* |1.2.840.10008.1.2.4.91| | |
+ +------------------------+----------------------+-----------+----------------------------------+
+ | *RLE Lossless* | 1.2.840.10008.1.2.5 | pydicom, | :doc:`RLE Lossless |
+ | | | pylibjpeg,| </guides/encoding/rle_lossless>` |
+ | | | gdcm | |
+ +------------------------+----------------------+-----------+----------------------------------+
+
+ Examples
+ --------
+
+ Compress the existing uncompressed *Pixel Data* in place:
+
+ >>> from pydicom import examples
+ >>> from pydicom.pixels import compress
+ >>> from pydicom.uid import RLELossless
+ >>> ds = examples.ct
+ >>> compress(ds, RLELossless)
+ >>> ds.save_as("ct_rle_lossless.dcm")
+
+ Parameters
+ ----------
+ ds : pydicom.dataset.Dataset
+ The dataset to be compressed.
+ transfer_syntax_uid : pydicom.uid.UID
+ The UID of the :dcm:`transfer syntax<part05/chapter_10.html>` to
+ use when compressing the pixel data.
+ arr : numpy.ndarray, optional
+ Compress the uncompressed pixel data in `arr` and use it
+ to set the *Pixel Data*. If `arr` is not used then the existing
+ uncompressed *Pixel Data* in the dataset will be compressed instead.
+ The :attr:`~numpy.ndarray.shape`, :class:`~numpy.dtype` and
+ contents of the array should match the dataset.
+ encoding_plugin : str, optional
+ Use `encoding_plugin` to compress the pixel data. See the
+ :doc:`user guide </old/image_data_compression>` for a list of
+ plugins available for each UID and their dependencies. If not
+ specified then all available plugins will be tried (default).
+ encapsulate_ext : bool, optional
+ If ``True`` then force the addition of an extended offset table.
+ If ``False`` (default) then an extended offset table
+ will be added if needed for large amounts of compressed *Pixel
+ Data*, otherwise just the basic offset table will be used.
+ new_instance_uid : bool, optional
+ If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
+ value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
+ keep the original value.
+ jls_error : int, optional
+ **JPEG-LS Near Lossless only**. The allowed absolute compression error
+ in the pixel values.
+ j2k_cr : list[float], optional
+ **JPEG 2000 only**. A list of the compression ratios to use for each
+ quality layer. There must be at least one quality layer and the
+ minimum allowable compression ratio is ``1``. When using multiple
+ quality layers they should be ordered in decreasing value from left
+ to right. For example, to use 2 quality layers with 20x and 5x
+ compression ratios then `j2k_cr` should be ``[20, 5]``. Cannot be
+ used with `j2k_psnr`.
+ j2k_psnr : list[float], optional
+ **JPEG 2000 only**. A list of the peak signal-to-noise ratios (in dB)
+ to use for each quality layer. There must be at least one quality
+ layer and when using multiple quality layers they should be ordered
+ in increasing value from left to right. For example, to use 2
+ quality layers with PSNR of 80 and 300 then `j2k_psnr` should be
+ ``[80, 300]``. Cannot be used with `j2k_cr`.
+ **kwargs
+ Optional keyword parameters for the encoding plugin may also be
+ present. See the :doc:`encoding plugins options
+ </guides/encoding/encoder_plugin_options>` for more information.
+ """
+ from pydicom.dataset import FileMetaDataset
+ from pydicom.pixels import get_encoder
+
+ # Disallow overriding the dataset's image pixel module element values
+ for option in _IMAGE_PIXEL.values():
+ kwargs.pop(option, None)
+
+ uid = UID(transfer_syntax_uid)
+ encoder = get_encoder(uid)
+ if not encoder.is_available:
+ missing = "\n".join([f" {s}" for s in encoder.missing_dependencies])
+ raise RuntimeError(
+ f"The pixel data encoder for '{uid.name}' is unavailable because all "
+ f"of its plugins are missing dependencies:\n{missing}"
+ )
+
+ if uid == JPEGLSNearLossless and jls_error is not None:
+ kwargs["jls_error"] = jls_error
+
+ if uid == JPEG2000:
+ if j2k_cr is not None:
+ kwargs["j2k_cr"] = j2k_cr
+
+ if j2k_psnr is not None:
+ kwargs["j2k_psnr"] = j2k_psnr
+
+ if arr is None:
+ # Encode the current uncompressed *Pixel Data*
+ frame_iterator = encoder.iter_encode(
+ ds, encoding_plugin=encoding_plugin, **kwargs
+ )
+ else:
+ # Encode from an array
+ opts = as_pixel_options(ds, **kwargs)
+ frame_iterator = encoder.iter_encode(
+ arr, encoding_plugin=encoding_plugin, **opts
+ )
+
+ # Encode!
+ encoded = [f for f in frame_iterator]
+
+ # Encapsulate the encoded *Pixel Data*
+ nr_frames = len(encoded)
+ total = (nr_frames - 1) * 8 + sum([len(f) for f in encoded[:-1]])
+ if encapsulate_ext or total > 2**32 - 1:
+ (
+ ds.PixelData,
+ ds.ExtendedOffsetTable,
+ ds.ExtendedOffsetTableLengths,
+ ) = encapsulate_extended(encoded)
+ else:
+ ds.PixelData = encapsulate(encoded)
+
+ # PS3.5 Annex A.4 - encapsulated pixel data uses undefined length
+ elem = ds["PixelData"]
+ elem.is_undefined_length = True
+ # PS3.5 Section 8.2 and Annex A.4 - encapsulated pixel data uses OB
+ elem.VR = VR.OB
+
+ ds._pixel_array = None if arr is None else arr
+ ds._pixel_id = {} if arr is None else get_image_pixel_ids(ds)
+
+ # Set the correct *Transfer Syntax UID*
+ if not hasattr(ds, "file_meta"):
+ ds.file_meta = FileMetaDataset()
+
+ ds.file_meta.TransferSyntaxUID = uid
+
+ if new_instance_uid:
+ instance_uid = generate_uid()
+ ds.SOPInstanceUID = instance_uid
+ ds.file_meta.MediaStorageSOPInstanceUID = instance_uid
+
+ return ds
+
+
+def decompress(
+ ds: "Dataset",
+ *,
+ as_rgb: bool = True,
+ new_instance_uid: bool = True,
+ decoding_plugin: str = "",
+ **kwargs: Any,
+) -> "Dataset":
+ """Perform an in-place decompression of a dataset with a compressed *Transfer
+ Syntax UID*.
+
+ .. versionadded:: 3.0
+
+ .. warning::
+
+ This function requires `NumPy <https://numpy.org/>`_ and may require
+ the installation of additional packages to perform the actual pixel
+ data decoding. See the :doc:`pixel data decompression documentation
+ </old/image_data_handlers>` for more information.
+
+ * The dataset's *Transfer Syntax UID* will be set to *Explicit
+ VR Little Endian*.
+ * The *Pixel Data* will be decompressed in its entirety and the
+ *Pixel Data* element's value updated with the uncompressed data,
+ padded to an even length.
+ * The *Pixel Data* element's VR will be set to **OB** if *Bits
+ Allocated* <= 8, otherwise it will be set to **OW**.
+ * The :attr:`DataElement.is_undefined_length
+ <pydicom.dataelem.DataElement.is_undefined_length>` attribute for the
+ *Pixel Data* element will be set to ``False``.
+ * Any :dcm:`image pixel<part03/sect_C.7.6.3.html>` module elements may be
+ modified as required to match the uncompressed *Pixel Data*.
+ * If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
+ Instance UID* value will be generated.
+
+ Parameters
+ ----------
+ ds : pydicom.dataset.Dataset
+ A dataset containing compressed *Pixel Data* to be decoded and the
+ corresponding *Image Pixel* module elements, along with a
+ :attr:`~pydicom.dataset.FileDataset.file_meta` attribute containing a
+ suitable (0002,0010) *Transfer Syntax UID*.
+ as_rgb : bool, optional
+ if ``True`` (default) then convert pixel data with a YCbCr
+ :ref:`photometric interpretation<photometric_interpretation>` such as
+ ``"YBR_FULL_422"`` to RGB.
+ new_instance_uid : bool, optional
+ If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
+ value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
+ keep the original value.
+ decoding_plugin : str, optional
+ The name of the decoding plugin to use when decoding compressed
+ pixel data. If no `decoding_plugin` is specified (default) then all
+ available plugins will be tried and the result from the first successful
+ one yielded. For information on the available plugins for each
+ decoder see the :doc:`API documentation</reference/pixels.decoders>`.
+ kwargs : dict[str, Any], optional
+ Optional keyword parameters for the decoding plugin may also be
+ present. See the :doc:`decoding plugins options
+ </guides/decoding/decoder_options>` for more information.
+
+ Returns
+ -------
+ pydicom.dataset.Dataset
+ The dataset `ds` decompressed in-place.
+ """
+ from pydicom.pixels import get_decoder
+
+ if "PixelData" not in ds:
+ raise AttributeError(
+ "Unable to decompress as the dataset has no (7FE0,0010) 'Pixel Data' element"
+ )
+
+ file_meta = ds.get("file_meta", {})
+ tsyntax = file_meta.get("TransferSyntaxUID", "")
+ if not tsyntax:
+ raise AttributeError(
+ "Unable to decompress as there's no (0002,0010) 'Transfer Syntax UID' "
+ f"element in '{type(ds).__name__}.file_meta'"
+ )
+
+ uid = UID(tsyntax)
+ if not uid.is_compressed:
+ raise ValueError("The dataset is already uncompressed")
+
+ decoder = get_decoder(uid)
+ if not decoder.is_available:
+ missing = "\n".join([f" {s}" for s in decoder.missing_dependencies])
+ raise RuntimeError(
+ f"Unable to decompress as the plugins for the '{uid.name}' decoder "
+ f"are all missing dependencies:\n{missing}"
+ )
+
+ # Disallow decompression of individual frames
+ kwargs.pop("index", None)
+ frame_generator = decoder.iter_array(
+ ds,
+ decoding_plugin=decoding_plugin,
+ as_rgb=as_rgb,
+ **kwargs,
+ )
+ frames: list[bytes] = []
+ for arr, image_pixel in frame_generator:
+ frames.append(arr.tobytes())
+
+ # Part 5, Section 8.1.1: 32-bit Value Length field
+ value_length = sum(len(frame) for frame in frames)
+ if value_length >= 2**32 - 1:
+ raise ValueError(
+ "Unable to decompress as the length of the uncompressed pixel data "
+ "will be greater than the maximum allowed by the DICOM Standard"
+ )
+
+ # Pad with 0x00 if odd length
+ nr_frames = len(frames)
+ if value_length % 2:
+ frames.append(b"\x00")
+
+ elem = ds["PixelData"]
+ elem.value = b"".join(frame for frame in frames)
+ elem.is_undefined_length = False
+ elem.VR = VR.OB if ds.BitsAllocated <= 8 else VR.OW
+
+ # Update the transfer syntax
+ ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
+
+ if new_instance_uid:
+ instance_uid = generate_uid()
+ ds.SOPInstanceUID = instance_uid
+ ds.file_meta.MediaStorageSOPInstanceUID = instance_uid
+
+ # Update the image pixel elements
+ ds.PhotometricInterpretation = image_pixel["photometric_interpretation"]
+ if cast(int, image_pixel["samples_per_pixel"]) > 1:
+ ds.PlanarConfiguration = cast(int, image_pixel["planar_configuration"])
+
+ if "NumberOfFrames" in ds or nr_frames > 1:
+ ds.NumberOfFrames = nr_frames
+
+ ds._pixel_array = None
+ ds._pixel_id = {}
+
+ return ds
+
+
def expand_ybr422(src: ByteString, bits_allocated: int) -> bytes:
"""Return ``YBR_FULL_422`` data expanded to ``YBR_FULL``.
@@ -580,6 +946,8 @@ def iter_pixels(
) -> Iterator["np.ndarray"]:
"""Yield decoded pixel data frames from `src` as :class:`~numpy.ndarray`.
+ .. versionadded:: 3.0
+
.. warning::
This function requires `NumPy <https://numpy.org/>`_
@@ -850,6 +1218,8 @@ def pixel_array(
) -> "np.ndarray":
"""Return decoded pixel data from `src` as :class:`~numpy.ndarray`.
+ .. versionadded:: 3.0
+
.. warning::
This function requires `NumPy <https://numpy.org/>`_
| diff --git a/tests/pixels/test_encoder_pyjpegls.py b/tests/pixels/test_encoder_pyjpegls.py
index 4f1a262a79..98b9f9b675 100644
--- a/tests/pixels/test_encoder_pyjpegls.py
+++ b/tests/pixels/test_encoder_pyjpegls.py
@@ -1325,13 +1325,3 @@ def test_buffer_i2_spp1(self):
assert not np.array_equal(out, ref)
assert np.allclose(out, ref, atol=1)
-
- def test_dataset_compress(self):
- """Test that the jls_error kwarg is passed OK."""
- ds = examples.ct
- ds.compress(JPEGLSNearLossless, jls_error=3, encoding_plugin="pyjpegls")
-
- assert ds.file_meta.TransferSyntaxUID == JPEGLSNearLossless
- frame = get_frame(ds.PixelData, 0)
- info = _get_jpg_parameters(frame)
- assert info["lossy_error"] == 3
diff --git a/tests/pixels/test_encoder_pylibjpeg.py b/tests/pixels/test_encoder_pylibjpeg.py
index 089d0b5d48..e8381c30e6 100644
--- a/tests/pixels/test_encoder_pylibjpeg.py
+++ b/tests/pixels/test_encoder_pylibjpeg.py
@@ -1707,34 +1707,6 @@ def test_bits_stored_25_raises(self):
with pytest.raises(RuntimeError, match=msg):
JPEG2000Encoder.encode(arr, encoding_plugin="pylibjpeg", **opts)
- def test_dataset_compress(self):
- """Test that the j2k_cr and j2k_psnr kwargs are passed OK."""
- ds = examples.ct
- ref = ds.pixel_array
- ds.compress(JPEG2000, j2k_cr=[2], encoding_plugin="pylibjpeg")
- assert ds.file_meta.TransferSyntaxUID == JPEG2000
- opts = as_pixel_options(ds)
- out, _ = JPEG2000Decoder.as_array(
- ds.PixelData,
- decoding_plugin="pylibjpeg",
- **opts,
- )
- assert not np.array_equal(out, ref)
- assert np.allclose(out, ref, atol=2)
-
- ds = examples.ct
- ref = ds.pixel_array
- ds.compress(JPEG2000, j2k_psnr=[100], encoding_plugin="pylibjpeg")
- assert ds.file_meta.TransferSyntaxUID == JPEG2000
- opts = as_pixel_options(ds)
- out, _ = JPEG2000Decoder.as_array(
- ds.PixelData,
- decoding_plugin="pylibjpeg",
- **opts,
- )
- assert not np.array_equal(out, ref)
- assert np.allclose(out, ref, atol=3)
-
def test_is_available_unknown_uid():
"""Test is_available() with an unsupported UID."""
diff --git a/tests/pixels/test_utils.py b/tests/pixels/test_utils.py
index acc12032f8..3274936f7f 100644
--- a/tests/pixels/test_utils.py
+++ b/tests/pixels/test_utils.py
@@ -22,6 +22,8 @@
from pydicom.dataset import Dataset, FileMetaDataset
from pydicom.encaps import get_frame
from pydicom.pixels import pixel_array, iter_pixels, convert_color_space
+from pydicom.pixels.decoders.base import _PIXEL_DATA_DECODERS
+from pydicom.pixels.encoders import RLELosslessEncoder
from pydicom.pixels.utils import (
as_pixel_options,
_passes_version_check,
@@ -34,27 +36,43 @@
pack_bits,
unpack_bits,
expand_ybr422,
+ compress,
+ decompress,
)
from pydicom.uid import (
EnhancedMRImageStorage,
ExplicitVRLittleEndian,
ExplicitVRBigEndian,
UncompressedTransferSyntaxes,
+ RLELossless,
+ JPEG2000Lossless,
+ JPEG2000,
+ JPEG2000MC,
+ JPEGLSNearLossless,
+ JPEGLSLossless,
+ UID,
)
from .pixels_reference import (
PIXEL_REFERENCE,
+ RLE_8_3_1F,
+ RLE_16_1_1F,
RLE_16_1_10F,
+ RLE_32_3_2F,
EXPL_16_1_10F,
+ EXPL_16_16_1F,
+ EXPL_8_3_1F_ODD,
EXPL_8_3_1F_YBR422,
IMPL_16_1_1F,
JPGB_08_08_3_0_1F_RGB_NO_APP14,
JPGB_08_08_3_0_1F_RGB_APP14,
JPGB_08_08_3_0_1F_RGB,
+ JPGB_08_08_3_1F_YBR_FULL,
JLSL_08_08_3_0_1F_ILV0,
JLSL_08_08_3_0_1F_ILV1,
JLSL_08_08_3_0_1F_ILV2,
JLSN_08_01_1_0_1F,
+ J2KR_08_08_3_0_1F_YBR_RCT,
EXPL_1_1_3F,
)
from ..test_helpers import assert_no_warning
@@ -62,8 +80,14 @@
HAVE_PYLJ = bool(importlib.util.find_spec("pylibjpeg"))
HAVE_RLE = bool(importlib.util.find_spec("rle"))
+HAVE_JLS = bool(importlib.util.find_spec("jpeg_ls"))
+HAVE_LJ = bool(importlib.util.find_spec("libjpeg"))
+HAVE_OJ = bool(importlib.util.find_spec("openjpeg"))
SKIP_RLE = not (HAVE_NP and HAVE_PYLJ and HAVE_RLE)
+SKIP_JPG = not (HAVE_NP and HAVE_PYLJ and HAVE_LJ)
+SKIP_JLS = not (HAVE_NP and HAVE_JLS)
+SKIP_J2K = not (HAVE_NP and HAVE_PYLJ and HAVE_OJ)
@pytest.mark.skipif(not HAVE_NP, reason="NumPy is not available")
@@ -1349,3 +1373,452 @@ def test_16bit(self):
arr = arr.reshape(100, 100, 3)
assert (19532, 21845, 65535) == tuple(arr[5, 50, :])
assert (42662, 27242, 49601) == tuple(arr[15, 50, :])
+
+
+class TestCompressRLE:
+ """Tests for compress() with RLE Lossless"""
+
+ def test_compress(self):
+ """Test compressing a dataset."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ assert not ds["PixelData"].is_undefined_length
+ assert ds["PixelData"].VR == "OW"
+ compress(ds, RLELossless, encoding_plugin="pydicom")
+
+ assert ds.SamplesPerPixel == 1
+ assert ds.file_meta.TransferSyntaxUID == RLELossless
+ assert len(ds.PixelData) == 21370
+ assert "PlanarConfiguration" not in ds
+ assert ds["PixelData"].is_undefined_length
+ assert ds["PixelData"].VR == "OB"
+
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ def test_no_file_meta(self):
+ """Test compressing a dataset."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ assert ds["PixelData"].VR == "OW"
+ del ds.file_meta
+ compress(ds, RLELossless, encoding_plugin="pydicom")
+
+ assert ds.SamplesPerPixel == 1
+ assert ds.file_meta.TransferSyntaxUID == RLELossless
+ assert len(ds.PixelData) == 21370
+ assert "PlanarConfiguration" not in ds
+ assert ds["PixelData"].is_undefined_length
+ assert ds["PixelData"].VR == "OB"
+
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ @pytest.mark.skipif(not HAVE_NP, reason="Numpy not available")
+ def test_compress_arr(self):
+ """Test compressing using pixel data from an arr."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ assert hasattr(ds, "file_meta")
+ arr = ds.pixel_array
+ del ds.PixelData
+ del ds.file_meta
+
+ compress(ds, RLELossless, arr, encoding_plugin="pydicom")
+ assert ds.file_meta.TransferSyntaxUID == RLELossless
+ assert len(ds.PixelData) == 21370
+
+ assert ds._pixel_array is arr
+ assert ds._pixel_id != {}
+
+ @pytest.mark.skipif(HAVE_NP, reason="Numpy is available")
+ def test_encoder_unavailable(self, monkeypatch):
+ """Test the required encoder being unavailable."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ monkeypatch.delitem(RLELosslessEncoder._available, "pydicom")
+ msg = (
+ r"The pixel data encoder for 'RLE Lossless' is unavailable because "
+ r"all of its plugins are missing dependencies:\n"
+ r" gdcm - requires gdcm>=3.0.10\n"
+ r" pylibjpeg - requires numpy, pylibjpeg>=2.0 and pylibjpeg-rle>=2.0"
+ )
+ with pytest.raises(RuntimeError, match=msg):
+ compress(ds, RLELossless)
+
+ def test_uid_not_supported(self):
+ """Test the UID not having any encoders."""
+ ds = dcmread(EXPL_16_16_1F.path)
+
+ msg = (
+ r"No pixel data encoders have been implemented for "
+ r"'JPEG 2000 Part 2 Multi-component Image Compression'"
+ )
+ with pytest.raises(NotImplementedError, match=msg):
+ compress(ds, JPEG2000MC, encoding_plugin="pydicom")
+
+ def test_encapsulate_extended(self):
+ """Test forcing extended encapsulation."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ assert "ExtendedOffsetTable" not in ds
+ assert "ExtendedOffsetTableLengths" not in ds
+
+ compress(ds, RLELossless, encapsulate_ext=True, encoding_plugin="pydicom")
+ assert ds.file_meta.TransferSyntaxUID == RLELossless
+ assert len(ds.PixelData) == 21366
+ assert ds.ExtendedOffsetTable == b"\x00" * 8
+ assert ds.ExtendedOffsetTableLengths == b"\x66\x53" + b"\x00" * 6
+
+ @pytest.mark.skipif(not HAVE_NP, reason="Numpy not available")
+ def test_round_trip(self):
+ """Test an encoding round-trip"""
+ ds = dcmread(RLE_16_1_1F.path)
+ arr = ds.pixel_array
+ # Setting PixelData to None frees the memory which may
+ # sometimes be reused, causes the _pixel_id check to fail
+ ds.PixelData = None
+ ds._pixel_array = None
+ compress(ds, RLELossless, arr, encoding_plugin="pydicom")
+ assert ds.PixelData is not None
+ assert np.array_equal(arr, ds.pixel_array)
+
+ @pytest.mark.skipif(not HAVE_NP, reason="Numpy not available")
+ def test_cant_override_kwargs(self):
+ """Test we can't override using kwargs."""
+ ds = dcmread(EXPL_8_3_1F_ODD.path)
+ ref = ds.pixel_array
+ assert ds.SamplesPerPixel == 3
+ compress(
+ ds,
+ RLELossless,
+ encoding_plugin="pydicom",
+ samples_per_pixel=1,
+ )
+
+ assert np.array_equal(ref, ds.pixel_array)
+
+ @pytest.mark.skipif(not HAVE_NP, reason="Numpy not available")
+ def test_instance_uid(self):
+ """Test generating new SOP Instance UID."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ original = ds.SOPInstanceUID
+
+ compress(ds, RLELossless, encoding_plugin="pydicom", new_instance_uid=True)
+ assert ds.SOPInstanceUID != original
+ assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
+
+ ds = dcmread(EXPL_16_16_1F.path)
+ compress(ds, RLELossless, encoding_plugin="pydicom", new_instance_uid=False)
+ assert ds.SOPInstanceUID == original
+ assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
+
+
+@pytest.mark.skipif(SKIP_JLS, reason="JPEG-LS plugins unavailable")
+class TestCompressJLS:
+ """Tests for compress() with JPEG-LS"""
+
+ def test_lossless(self):
+ """Test JPEG-LS Lossless."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ ref = ds.pixel_array
+ compress(ds, JPEGLSLossless, encoding_plugin="pyjpegls")
+
+ assert ds.file_meta.TransferSyntaxUID == JPEGLSLossless
+ frame = get_frame(ds.PixelData, 0)
+ info = _get_jpg_parameters(frame)
+ assert info["lossy_error"] == 0
+
+ assert np.array_equal(ds.pixel_array, ref)
+
+ def test_lossy(self):
+ """Test JPEG-LS Near Lossless and the jls_error kwarg."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ ref = ds.pixel_array
+ compress(ds, JPEGLSNearLossless, jls_error=3, encoding_plugin="pyjpegls")
+
+ assert ds.file_meta.TransferSyntaxUID == JPEGLSNearLossless
+ frame = get_frame(ds.PixelData, 0)
+ info = _get_jpg_parameters(frame)
+ assert info["lossy_error"] == 3
+
+ assert np.allclose(ds.pixel_array, ref, atol=3)
+
+
+@pytest.mark.skipif(SKIP_J2K, reason="JPEG 2000 plugins unavailable")
+class TestCompressJ2K:
+ """Tests for compress() with JPEG 2000"""
+
+ def test_lossless(self):
+ """Test JPEG 2000 Lossless."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ ref = ds.pixel_array
+ compress(ds, JPEG2000Lossless, encoding_plugin="pylibjpeg")
+ assert ds.file_meta.TransferSyntaxUID == JPEG2000Lossless
+ assert np.array_equal(ds.pixel_array, ref)
+
+ def test_lossy(self):
+ """Test JPEG 2000 and the j2k_cr and j2k_psnr kwargs."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ ref = ds.pixel_array
+ compress(ds, JPEG2000, j2k_cr=[2], encoding_plugin="pylibjpeg")
+ assert ds.file_meta.TransferSyntaxUID == JPEG2000
+ out = ds.pixel_array
+ assert not np.array_equal(out, ref)
+ assert np.allclose(out, ref, atol=2)
+
+ ds = dcmread(EXPL_16_16_1F.path)
+ ref = ds.pixel_array
+ compress(ds, JPEG2000, j2k_psnr=[100], encoding_plugin="pylibjpeg")
+ assert ds.file_meta.TransferSyntaxUID == JPEG2000
+ out = ds.pixel_array
+ assert not np.array_equal(out, ref)
+ assert np.allclose(out, ref, atol=3)
+
+
+@pytest.fixture()
+def add_dummy_decoder():
+ """Add a dummy decoder to the pixel data decoders"""
+
+ class DummyDecoder:
+ is_available = True
+
+ def iter_array(self, ds, **kwargs):
+ # Yield a total of 2**32 bytes
+ arr = np.frombuffer(b"\x00" * 2**20, dtype="u1")
+ for _ in range(2**12):
+ yield arr, {}
+
+ _PIXEL_DATA_DECODERS["1.2.3.4"] = [DummyDecoder()]
+ yield
+ del _PIXEL_DATA_DECODERS["1.2.3.4"]
+
+
+class TestDecompress:
+ """Tests for decompress()"""
+
+ def test_no_file_meta_raises(self):
+ """Test exception raised if no file meta or transfer syntax."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ del ds.file_meta.TransferSyntaxUID
+
+ msg = (
+ r"Unable to decompress as there's no \(0002,0010\) 'Transfer Syntax UID' "
+ "element in 'FileDataset.file_meta'"
+ )
+ with pytest.raises(AttributeError, match=msg):
+ decompress(ds)
+
+ del ds.file_meta
+ with pytest.raises(AttributeError, match=msg):
+ decompress(ds)
+
+ def test_no_pixel_data_raises(self):
+ """Test exception raised if no pixel data."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ del ds.PixelData
+
+ msg = (
+ r"Unable to decompress as the dataset has no \(7FE0,0010\) 'Pixel "
+ "Data' element"
+ )
+ with pytest.raises(AttributeError, match=msg):
+ decompress(ds)
+
+ def test_uncompressed_raises(self):
+ """Test exception raised if already uncompressed."""
+ ds = dcmread(EXPL_16_16_1F.path)
+ msg = "The dataset is already uncompressed"
+ with pytest.raises(ValueError, match=msg):
+ decompress(ds)
+
+ @pytest.mark.skipif(not HAVE_NP, reason="Numpy is unavailable")
+ def test_too_long_raises(self, add_dummy_decoder):
+ """Test too much uncompressed data raises"""
+ ds = dcmread(RLE_8_3_1F.path)
+ uid = UID("1.2.3.4")
+ uid.set_private_encoding(False, True)
+ ds.file_meta.TransferSyntaxUID = uid
+
+ msg = (
+ "Unable to decompress as the length of the uncompressed pixel data "
+ "will be greater than the maximum allowed by the DICOM Standard"
+ )
+ with pytest.raises(ValueError, match=msg):
+ decompress(ds)
+
+ @pytest.mark.skipif(SKIP_RLE, reason="RLE plugins unavailable")
+ def test_rle_8_1f_3s(self):
+ """Test decoding RLE Lossless - 1 frame, 3 sample (RGB)"""
+ ds = dcmread(RLE_8_3_1F.path)
+ ref = ds.pixel_array
+ assert ds.BitsAllocated == 8
+ assert ds.PhotometricInterpretation == "RGB"
+ decompress(ds, decoding_plugin="pydicom")
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ elem = ds["PixelData"]
+ assert len(elem.value) == ds.Rows * ds.Columns * (ds.BitsAllocated // 8) * 3
+ assert elem.is_undefined_length is False
+ assert elem.VR == "OB"
+ assert "NumberOfFrames" not in ds
+ assert ds.PlanarConfiguration == 0
+ assert ds.PhotometricInterpretation == "RGB"
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ assert np.array_equal(ds.pixel_array, ref)
+
+ @pytest.mark.skipif(SKIP_RLE, reason="RLE plugins unavailable")
+ def test_rle_16_1f_1s(self):
+ """Test decoding RLE Lossless - 1 frame, 1 sample"""
+ ds = dcmread(RLE_16_1_1F.path)
+ ref = ds.pixel_array
+ assert ds.BitsAllocated == 16
+ decompress(ds, decoding_plugin="pydicom")
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ elem = ds["PixelData"]
+ assert len(elem.value) == ds.Rows * ds.Columns * (ds.BitsAllocated // 8)
+ assert elem.is_undefined_length is False
+ assert elem.VR == "OW"
+ assert "NumberOfFrames" not in ds
+ assert "PlanarConfiguration" not in ds
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ assert np.array_equal(ds.pixel_array, ref)
+
+ @pytest.mark.skipif(SKIP_RLE, reason="RLE plugins unavailable")
+ def test_rle_16_10f_1s(self):
+ """Test decoding RLE Lossless - 10 frame, 1 sample"""
+ ds = dcmread(RLE_16_1_10F.path)
+ ref = ds.pixel_array
+ assert ds.BitsAllocated == 16
+ assert ds.NumberOfFrames == 10
+ # `index` should be ignored
+ decompress(ds, decoding_plugin="pydicom", index=1)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ elem = ds["PixelData"]
+ assert len(elem.value) == (
+ ds.Rows * ds.Columns * (ds.BitsAllocated // 8) * ds.NumberOfFrames
+ )
+ assert elem.is_undefined_length is False
+ assert elem.VR == "OW"
+ assert "PlanarConfiguration" not in ds
+ assert ds.NumberOfFrames == 10
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ assert np.array_equal(ds.pixel_array, ref)
+
+ @pytest.mark.skipif(SKIP_RLE, reason="RLE plugins unavailable")
+ def test_rle_32_2f_3s(self):
+ """Test decoding RLE Lossless - 2 frame, 3 sample (RGB)"""
+ ds = dcmread(RLE_32_3_2F.path)
+ ref = ds.pixel_array
+ assert ds.BitsAllocated == 32
+ assert ds.NumberOfFrames == 2
+ assert ds.PhotometricInterpretation == "RGB"
+ decompress(ds, decoding_plugin="pydicom")
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ elem = ds["PixelData"]
+ assert len(elem.value) == (
+ ds.Rows * ds.Columns * (ds.BitsAllocated // 8) * ds.NumberOfFrames * 3
+ )
+ assert elem.is_undefined_length is False
+ assert elem.VR == "OW"
+ assert ds.PlanarConfiguration == 0
+ assert ds.PhotometricInterpretation == "RGB"
+ assert ds.NumberOfFrames == 2
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ assert np.array_equal(ds.pixel_array, ref)
+
+ @pytest.mark.skipif(SKIP_RLE, reason="RLE plugins unavailable")
+ def test_odd_length_padded(self):
+ """Test odd length Pixel Data gets padded to even length."""
+ ds = dcmread(EXPL_8_3_1F_ODD.path)
+ assert ds.Rows * ds.Columns * ds.SamplesPerPixel % 2 == 1
+ compress(ds, RLELossless, encoding_plugin="pydicom")
+ assert ds.file_meta.TransferSyntaxUID == RLELossless
+ decompress(ds, decoding_plugin="pydicom")
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ assert len(ds.PixelData) % 2 == 0
+
+ @pytest.mark.skipif(not SKIP_J2K, reason="J2K plugin available")
+ def test_no_decoders_raises(self):
+ """Test exception raised if no decoders are available."""
+ ds = dcmread(J2KR_08_08_3_0_1F_YBR_RCT.path)
+ msg = (
+ "Unable to decompress as the plugins for the 'JPEG 2000 Image "
+ r"Compression \(Lossless Only\)' decoder are all missing dependencies:"
+ )
+ with pytest.raises(RuntimeError, match=msg):
+ decompress(ds, decoding_plugin="pylibjpeg")
+
+ @pytest.mark.skipif(SKIP_J2K, reason="J2K plugins unavailable")
+ def test_j2k_ybr_rct(self):
+ """Test decoding J2K YBR_RCT -> RGB"""
+ ds = dcmread(J2KR_08_08_3_0_1F_YBR_RCT.path)
+ ref = ds.pixel_array
+ assert ds.BitsAllocated == 8
+ assert ds.PhotometricInterpretation == "YBR_RCT"
+ # as_rgb will be ignored if YBR_RCT or YBR_ICT
+ decompress(ds, decoding_plugin="pylibjpeg", as_rgb=False)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ elem = ds["PixelData"]
+ assert len(elem.value) == ds.Rows * ds.Columns * (ds.BitsAllocated // 8) * 3
+ assert elem.is_undefined_length is False
+ assert elem.VR == "OB"
+ assert "NumberOfFrames" not in ds
+ assert ds.PlanarConfiguration == 0
+ assert ds.PhotometricInterpretation == "RGB"
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+
+ assert np.array_equal(ds.pixel_array, ref)
+
+ @pytest.mark.skipif(SKIP_JPG, reason="JPEG plugins unavailable")
+ def test_as_rgb(self):
+ """Test decoding J2K - 1 frame, 3 sample (YBR_RCT)"""
+ ds = dcmread(JPGB_08_08_3_1F_YBR_FULL.path)
+ ds.convert_pixel_data("pylibjpeg")
+ ref = ds.pixel_array
+
+ assert ds.BitsAllocated == 8
+ assert ds.PhotometricInterpretation == "YBR_FULL"
+ decompress(ds, decoding_plugin="pylibjpeg", as_rgb=True)
+
+ assert ds.file_meta.TransferSyntaxUID == ExplicitVRLittleEndian
+ elem = ds["PixelData"]
+ assert len(elem.value) == ds.Rows * ds.Columns * (ds.BitsAllocated // 8) * 3
+ assert elem.is_undefined_length is False
+ assert elem.VR == "OB"
+ assert "NumberOfFrames" not in ds
+ assert ds.PlanarConfiguration == 0
+ assert ds.PhotometricInterpretation == "RGB"
+ assert ds._pixel_array is None
+ assert ds._pixel_id == {}
+ assert np.array_equal(
+ ds.pixel_array, convert_color_space(ref, "YBR_FULL", "RGB")
+ )
+
+ ds = dcmread(JPGB_08_08_3_1F_YBR_FULL.path)
+ decompress(ds, decoding_plugin="pylibjpeg", as_rgb=False)
+ assert ds.PhotometricInterpretation == "YBR_FULL"
+ assert np.array_equal(ds.pixel_array, ref)
+
+ @pytest.mark.skipif(SKIP_RLE, reason="RLE plugins unavailable")
+ def test_instance_uid(self):
+ """Test generating new SOP Instance UID."""
+ ds = dcmread(RLE_8_3_1F.path)
+ original = ds.SOPInstanceUID
+
+ decompress(ds, decoding_plugin="pydicom", new_instance_uid=True)
+ assert ds.SOPInstanceUID != original
+ assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
+
+ ds = dcmread(RLE_8_3_1F.path)
+ decompress(ds, decoding_plugin="pydicom", new_instance_uid=False)
+ assert ds.SOPInstanceUID == original
+ assert ds.SOPInstanceUID == ds.file_meta.MediaStorageSOPInstanceUID
| diff --git a/doc/guides/decoding/decoder_options.rst b/doc/guides/decoding/decoder_options.rst
index 0caa0b58e6..7dbd9badc6 100644
--- a/doc/guides/decoding/decoder_options.rst
+++ b/doc/guides/decoding/decoder_options.rst
@@ -7,14 +7,15 @@ Pixel Data Decoder Options
.. currentmodule:: pydicom.pixels.decoders.base
The following applies to the functions and class methods that use the
-:doc:`pixels</reference/pixels>` backend for decoding pixel data. This includes functions
-such as :func:`~pydicom.pixels.pixel_array` and :func:`~pydicom.pixels.iter_pixels`
-as well as the following methods of the :class:`~Decoder` class:
+:doc:`pixels</reference/pixels>` backend for decoding pixel data:
-* :meth:`Decoder.as_array`
-* :meth:`Decoder.as_buffer`
-* :meth:`Decoder.iter_array`
-* :meth:`Decoder.iter_buffer`
+* :func:`~pydicom.pixels.pixel_array`
+* :func:`~pydicom.pixels.iter_pixels`
+* :func:`~pydicom.pixels.decompress`
+* :meth:`Decoder.as_array()<pydicom.pixels.Decoder.as_array>`
+* :meth:`Decoder.as_buffer()<pydicom.pixels.Decoder.as_buffer>`
+* :meth:`Decoder.iter_array()<pydicom.pixels.Decoder.iter_array>`
+* :meth:`Decoder.iter_buffer()<pydicom.pixels.Decoder.iter_array>`
*Image Pixel* Options
=====================
@@ -67,9 +68,13 @@ Image Processing Options
========================
The following options may be used with any transfer syntax for controlling the
-processing applied after decoding to a NumPy :class:`~numpy.ndarray` using
-:func:`~pydicom.pixels.pixel_array`, :func:`~pydicom.pixels.iter_pixels`,
-:meth:`Decoder.as_array` or :meth:`Decoder.iter_array`.
+processing applied after decoding using:
+
+* :func:`~pydicom.pixels.pixel_array`
+* :func:`~pydicom.pixels.iter_pixels`
+* :func:`~pydicom.pixels.decompress`
+* :meth:`Decoder.as_array()<pydicom.pixels.Decoder.as_array>`
+* :meth:`Decoder.iter_array()<pydicom.pixels.Decoder.iter_array>`
* `as_rgb`: :class:`bool` - if ``True`` (default) then convert pixel data with a
YCbCr :ref:`photometric interpretation<photometric_interpretation>`
diff --git a/doc/reference/pixels.rst b/doc/reference/pixels.rst
index 41e1474446..38282e6187 100644
--- a/doc/reference/pixels.rst
+++ b/doc/reference/pixels.rst
@@ -26,6 +26,8 @@ Utility functions
:toctree: generated/
as_pixel_options
+ compress
+ decompress
get_decoder
get_encoder
iter_pixels
diff --git a/doc/reference/pixels.utils.rst b/doc/reference/pixels.utils.rst
index 38024f45e6..31b2b40ee2 100644
--- a/doc/reference/pixels.utils.rst
+++ b/doc/reference/pixels.utils.rst
@@ -12,6 +12,8 @@ Pixel data related utility functions.
:toctree: generated/
as_pixel_options
+ compress
+ decompress
expand_ybr422
get_expected_length
get_image_pixel_ids
diff --git a/doc/release_notes/v3.0.0.rst b/doc/release_notes/v3.0.0.rst
index f8a79bd311..f5a5b5f06d 100644
--- a/doc/release_notes/v3.0.0.rst
+++ b/doc/release_notes/v3.0.0.rst
@@ -182,13 +182,15 @@ Enhancements
* Added two functions for returning pixel data as a NumPy :class:`~numpy.ndarray`
from a path to a dataset while minimizing memory-usage: :func:`~pydicom.pixels.pixel_array`
and :func:`~pydicom.pixels.iter_pixels`.
+* Added two functions for compressing and decompressing datasets using the new
+ decoding backend: :func:`~pydicom.pixels.compress` and :func:`~pydicom.pixels.decompress`.
* Added support for the following transfer syntaxes to :meth:`Dataset.compress()
<pydicom.dataset.Dataset.compress>` (:issue:`1997`):
- * *JPEG-LS Lossless* with :attr:`~pydicom.pixels.encoders.base.JPEGLSLosslessEncoder`
- * *JPEG-LS Near Lossless* with :attr:`~pydicom.pixels.encoders.base.JPEGLSNearLosslessEncoder`
- * *JPEG 2000 Lossless* with :attr:`~pydicom.pixels.encoders.base.JPEG2000LosslessEncoder`
- * *JPEG 2000* with :attr:`~pydicom.pixels.encoders.base.JPEG2000Encoder`
+ * *JPEG-LS Lossless* with :attr:`~pydicom.pixels.encoders.JPEGLSLosslessEncoder`
+ * *JPEG-LS Near Lossless* with :attr:`~pydicom.pixels.encoders.JPEGLSNearLosslessEncoder`
+ * *JPEG 2000 Lossless* with :attr:`~pydicom.pixels.encoders.JPEG2000LosslessEncoder`
+ * *JPEG 2000* with :attr:`~pydicom.pixels.encoders.JPEG2000Encoder`
See the :doc:`JPEG-LS</guides/encoding/jpeg_ls>` and :doc:`JPEG 2000
</guides/encoding/jpeg_2k>` encoding guides for more information.
@@ -285,7 +287,7 @@ Deprecations
* :func:`~pydicom.pixels.utils.reshape_pixel_array`
* :func:`~pydicom.pixels.utils.unpack_bits`
- * :func:`~pydicom.pixel_data_handlers.util.dtype_corrected_for_endianness` will be
+ * :func:`pydicom.pixel_data_handlers.util.dtype_corrected_for_endianness` will be
removed in v4.0.
| [
{
"components": [
{
"doc": "Compress uncompressed pixel data and update `ds` in-place with the\nresulting :dcm:`encapsulated<part05/sect_A.4.html>` codestream.\n\n.. versionadded:: 3.0\n\nThe dataset `ds` must already have the following\n:dcm:`Image Pixel<part03/sect_C.7.6.3.html>` module elements... | [
"tests/pixels/test_encoder_pylibjpeg.py::test_is_available_unknown_uid",
"tests/pixels/test_utils.py::TestPixelArray::test_src",
"tests/pixels/test_utils.py::TestPixelArray::test_ds_out",
"tests/pixels/test_utils.py::TestPixelArray::test_specific_tags",
"tests/pixels/test_utils.py::TestPixelArray::test_inde... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
[MRG] Add dataset compress() and decompress() functions
#### Describe the changes
Adds `pixels.utils.compress()` and `pixels.utils.decompress()`
#### Tasks
- [x] Unit tests added that reproduce the issue or prove feature is working
- [x] Fix or feature added
- [x] Code typed and mypy shows no errors
- [x] Documentation updated (if relevant)
- [x] [Preview link](https://output.circle-artifacts.com/output/job/e604ffff-2ccf-48c1-a62d-5b6ce22d8e0e/artifacts/0/doc/_build/html/index.html)
- [x] Unit tests passing and overall coverage the same or better
----------
</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/pydicom/pixels/utils.py]
(definition of compress:)
def compress( ds: "Dataset", transfer_syntax_uid: str, arr: "np.ndarray | None" = None, *, encoding_plugin: str = "", encapsulate_ext: bool = False, new_instance_uid: bool = True, jls_error: int | None = None, j2k_cr: list[float] | None = None, j2k_psnr: list[float] | None = None, **kwargs: Any, ) -> "Dataset":
"""Compress uncompressed pixel data and update `ds` in-place with the
resulting :dcm:`encapsulated<part05/sect_A.4.html>` codestream.
.. versionadded:: 3.0
The dataset `ds` must already have the following
:dcm:`Image Pixel<part03/sect_C.7.6.3.html>` module elements present
with correct values that correspond to the resulting compressed
pixel data:
* (0028,0002) *Samples per Pixel*
* (0028,0004) *Photometric Interpretation*
* (0028,0008) *Number of Frames* (if more than 1 frame will be present)
* (0028,0010) *Rows*
* (0028,0011) *Columns*
* (0028,0100) *Bits Allocated*
* (0028,0101) *Bits Stored*
* (0028,0103) *Pixel Representation*
If *Samples per Pixel* is greater than 1 then the following element
is also required:
* (0028,0006) *Planar Configuration*
This method will add the file meta dataset if none is present and add
or modify the following elements:
* (0002,0010) *Transfer Syntax UID*
* (7FE0,0010) *Pixel Data*
If the compressed pixel data is too large for encapsulation using a
basic offset table then an :dcm:`extended offset table
<part03/sect_C.7.6.3.html>` will also be used, in which case the
following elements will also be added:
* (7FE0,0001) *Extended Offset Table*
* (7FE0,0002) *Extended Offset Table Lengths*
If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
Instance UID* value will be generated.
**Supported Transfer Syntax UIDs**
+-----------------------------------------------+-----------+----------------------------------+
| UID | Plugins | Encoding Guide |
+------------------------+----------------------+ | |
| Name | Value | | |
+========================+======================+===========+==================================+
| *JPEG-LS Lossless* |1.2.840.10008.1.2.4.80| pyjpegls | :doc:`JPEG-LS |
+------------------------+----------------------+ | </guides/encoding/jpeg_ls>` |
| *JPEG-LS Near Lossless*|1.2.840.10008.1.2.4.81| | |
+------------------------+----------------------+-----------+----------------------------------+
| *JPEG 2000 Lossless* |1.2.840.10008.1.2.4.90| pylibjpeg | :doc:`JPEG 2000 |
+------------------------+----------------------+ | </guides/encoding/jpeg_2k>` |
| *JPEG 2000* |1.2.840.10008.1.2.4.91| | |
+------------------------+----------------------+-----------+----------------------------------+
| *RLE Lossless* | 1.2.840.10008.1.2.5 | pydicom, | :doc:`RLE Lossless |
| | | pylibjpeg,| </guides/encoding/rle_lossless>` |
| | | gdcm | |
+------------------------+----------------------+-----------+----------------------------------+
Examples
--------
Compress the existing uncompressed *Pixel Data* in place:
>>> from pydicom import examples
>>> from pydicom.pixels import compress
>>> from pydicom.uid import RLELossless
>>> ds = examples.ct
>>> compress(ds, RLELossless)
>>> ds.save_as("ct_rle_lossless.dcm")
Parameters
----------
ds : pydicom.dataset.Dataset
The dataset to be compressed.
transfer_syntax_uid : pydicom.uid.UID
The UID of the :dcm:`transfer syntax<part05/chapter_10.html>` to
use when compressing the pixel data.
arr : numpy.ndarray, optional
Compress the uncompressed pixel data in `arr` and use it
to set the *Pixel Data*. If `arr` is not used then the existing
uncompressed *Pixel Data* in the dataset will be compressed instead.
The :attr:`~numpy.ndarray.shape`, :class:`~numpy.dtype` and
contents of the array should match the dataset.
encoding_plugin : str, optional
Use `encoding_plugin` to compress the pixel data. See the
:doc:`user guide </old/image_data_compression>` for a list of
plugins available for each UID and their dependencies. If not
specified then all available plugins will be tried (default).
encapsulate_ext : bool, optional
If ``True`` then force the addition of an extended offset table.
If ``False`` (default) then an extended offset table
will be added if needed for large amounts of compressed *Pixel
Data*, otherwise just the basic offset table will be used.
new_instance_uid : bool, optional
If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
keep the original value.
jls_error : int, optional
**JPEG-LS Near Lossless only**. The allowed absolute compression error
in the pixel values.
j2k_cr : list[float], optional
**JPEG 2000 only**. A list of the compression ratios to use for each
quality layer. There must be at least one quality layer and the
minimum allowable compression ratio is ``1``. When using multiple
quality layers they should be ordered in decreasing value from left
to right. For example, to use 2 quality layers with 20x and 5x
compression ratios then `j2k_cr` should be ``[20, 5]``. Cannot be
used with `j2k_psnr`.
j2k_psnr : list[float], optional
**JPEG 2000 only**. A list of the peak signal-to-noise ratios (in dB)
to use for each quality layer. There must be at least one quality
layer and when using multiple quality layers they should be ordered
in increasing value from left to right. For example, to use 2
quality layers with PSNR of 80 and 300 then `j2k_psnr` should be
``[80, 300]``. Cannot be used with `j2k_cr`.
**kwargs
Optional keyword parameters for the encoding plugin may also be
present. See the :doc:`encoding plugins options
</guides/encoding/encoder_plugin_options>` for more information."""
(definition of decompress:)
def decompress( ds: "Dataset", *, as_rgb: bool = True, new_instance_uid: bool = True, decoding_plugin: str = "", **kwargs: Any, ) -> "Dataset":
"""Perform an in-place decompression of a dataset with a compressed *Transfer
Syntax UID*.
.. versionadded:: 3.0
.. warning::
This function requires `NumPy <https://numpy.org/>`_ and may require
the installation of additional packages to perform the actual pixel
data decoding. See the :doc:`pixel data decompression documentation
</old/image_data_handlers>` for more information.
* The dataset's *Transfer Syntax UID* will be set to *Explicit
VR Little Endian*.
* The *Pixel Data* will be decompressed in its entirety and the
*Pixel Data* element's value updated with the uncompressed data,
padded to an even length.
* The *Pixel Data* element's VR will be set to **OB** if *Bits
Allocated* <= 8, otherwise it will be set to **OW**.
* The :attr:`DataElement.is_undefined_length
<pydicom.dataelem.DataElement.is_undefined_length>` attribute for the
*Pixel Data* element will be set to ``False``.
* Any :dcm:`image pixel<part03/sect_C.7.6.3.html>` module elements may be
modified as required to match the uncompressed *Pixel Data*.
* If `new_instance_uid` is ``True`` (default) then a new (0008,0018) *SOP
Instance UID* value will be generated.
Parameters
----------
ds : pydicom.dataset.Dataset
A dataset containing compressed *Pixel Data* to be decoded and the
corresponding *Image Pixel* module elements, along with a
:attr:`~pydicom.dataset.FileDataset.file_meta` attribute containing a
suitable (0002,0010) *Transfer Syntax UID*.
as_rgb : bool, optional
if ``True`` (default) then convert pixel data with a YCbCr
:ref:`photometric interpretation<photometric_interpretation>` such as
``"YBR_FULL_422"`` to RGB.
new_instance_uid : bool, optional
If ``True`` (default) then generate a new (0008,0018) *SOP Instance UID*
value for the dataset using :func:`~pydicom.uid.generate_uid`, otherwise
keep the original value.
decoding_plugin : str, optional
The name of the decoding plugin to use when decoding compressed
pixel data. If no `decoding_plugin` is specified (default) then all
available plugins will be tried and the result from the first successful
one yielded. For information on the available plugins for each
decoder see the :doc:`API documentation</reference/pixels.decoders>`.
kwargs : dict[str, Any], optional
Optional keyword parameters for the decoding plugin may also be
present. See the :doc:`decoding plugins options
</guides/decoding/decoder_options>` for more information.
Returns
-------
pydicom.dataset.Dataset
The dataset `ds` decompressed in-place."""
[end of new definitions in src/pydicom/pixels/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>> | f57c7aceaeda48b60ef3d66fdb875db61e5b49a8 | |
tobymao__sqlglot-3465 | 3,465 | tobymao/sqlglot | null | 58d5f2bece42acdda5f8c08d30e6f61a5e538d4c | 2024-05-13T08:10:34Z | diff --git a/sqlglot/dialects/clickhouse.py b/sqlglot/dialects/clickhouse.py
index 362ccde351..de385dd82b 100644
--- a/sqlglot/dialects/clickhouse.py
+++ b/sqlglot/dialects/clickhouse.py
@@ -611,6 +611,19 @@ def _parse_alter_table_replace(self) -> t.Optional[exp.Expression]:
exp.ReplacePartition, expression=partition, source=self._parse_table_parts()
)
+ def _parse_projection_def(self) -> t.Optional[exp.ProjectionDef]:
+ if not self._match_text_seq("PROJECTION"):
+ return None
+
+ return self.expression(
+ exp.ProjectionDef,
+ this=self._parse_id_var(),
+ expression=self._parse_wrapped(self._parse_statement),
+ )
+
+ def _parse_constraint(self) -> t.Optional[exp.Expression]:
+ return super()._parse_constraint() or self._parse_projection_def()
+
class Generator(generator.Generator):
QUERY_HINTS = False
STRUCT_DELIMITER = ("(", ")")
@@ -878,3 +891,6 @@ def replacepartition_sql(self, expression: exp.ReplacePartition) -> str:
return (
f"REPLACE {self.sql(expression.expression)} FROM {self.sql(expression, 'source')}"
)
+
+ def projectiondef_sql(self, expression: exp.ProjectionDef) -> str:
+ return f"PROJECTION {self.sql(expression.this)} {self.wrap(expression.expression)}"
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 8c02919196..657c22333b 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -1520,6 +1520,10 @@ class CTE(DerivedTable):
}
+class ProjectionDef(Expression):
+ arg_types = {"this": True, "expression": True}
+
+
class TableAlias(Expression):
arg_types = {"this": False, "columns": False}
| diff --git a/tests/dialects/test_clickhouse.py b/tests/dialects/test_clickhouse.py
index 1bce7f5cd5..15adda8a87 100644
--- a/tests/dialects/test_clickhouse.py
+++ b/tests/dialects/test_clickhouse.py
@@ -844,6 +844,9 @@ def test_ddl(self):
self.validate_identity(
"CREATE TABLE t1 (a String EPHEMERAL, b String EPHEMERAL func(), c String MATERIALIZED func(), d String ALIAS func()) ENGINE=TinyLog()"
)
+ self.validate_identity(
+ "CREATE TABLE t (a String, b String, c UInt64, PROJECTION p1 (SELECT a, sum(c) GROUP BY a, b), PROJECTION p2 (SELECT b, sum(c) GROUP BY b)) ENGINE=MergeTree()"
+ )
def test_agg_functions(self):
def extract_agg_func(query):
| [] | [
"tests/dialects/test_clickhouse.py::TestClickhouse::test_ddl"
] | [
"tests/dialects/test_clickhouse.py::TestClickhouse::test_agg_functions",
"tests/dialects/test_clickhouse.py::TestClickhouse::test_clickhouse",
"tests/dialects/test_clickhouse.py::TestClickhouse::test_cte",
"tests/dialects/test_clickhouse.py::TestClickhouse::test_drop_on_cluster",
"tests/dialects/test_clickh... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(clickhouse): add support for PROJECTION in CREATE TABLE statement
Added support for defining `PROJECTION` in `CREATE TABLE` statement for ClickHouse dialect
Documentation reference:
https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#add-projection
----------
</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>
</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 | ||
Textualize__textual-4508 | 4,508 | Textualize/textual | null | 9fdb3792075347851921add7befc31a0ee4f6814 | 2024-05-12T16:27:27Z | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68cd1546ea..170a8189e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Fixed auto width not working for option lists https://github.com/Textualize/textual/pull/4507
+### Added
+
+- Added `DOMNode.query_children` https://github.com/Textualize/textual/pull/4508
+
## [0.59.0] - 2024-05-11
### Fixed
diff --git a/src/textual/css/query.py b/src/textual/css/query.py
index d3cf48b512..649738d3a1 100644
--- a/src/textual/css/query.py
+++ b/src/textual/css/query.py
@@ -55,12 +55,7 @@ class WrongType(QueryError):
@rich.repr.auto(angular=True)
class DOMQuery(Generic[QueryType]):
- __slots__ = [
- "_node",
- "_nodes",
- "_filters",
- "_excludes",
- ]
+ __slots__ = ["_node", "_nodes", "_filters", "_excludes", "_deep"]
def __init__(
self,
@@ -68,6 +63,7 @@ def __init__(
*,
filter: str | None = None,
exclude: str | None = None,
+ deep: bool = True,
parent: DOMQuery | None = None,
) -> None:
"""Initialize a query object.
@@ -80,6 +76,7 @@ def __init__(
node: A DOM node.
filter: Query to filter children in the node.
exclude: Query to exclude children in the node.
+ deep: Query should be deep, i.e. recursive.
parent: The parent query, if this is the result of filtering another query.
Raises:
@@ -94,6 +91,7 @@ def __init__(
self._excludes: list[tuple[SelectorSet, ...]] = (
parent._excludes.copy() if parent else []
)
+ self._deep = deep
if filter is not None:
try:
self._filters.append(parse_selectors(filter))
@@ -118,9 +116,12 @@ def nodes(self) -> list[QueryType]:
from ..widget import Widget
if self._nodes is None:
+ initial_nodes = list(
+ self._node.walk_children(Widget) if self._deep else self._node._nodes
+ )
nodes = [
node
- for node in self._node.walk_children(Widget)
+ for node in initial_nodes
if all(match(selector_set, node) for selector_set in self._filters)
]
nodes = [
@@ -156,14 +157,20 @@ def __getitem__(self, index: int | slice) -> QueryType | list[QueryType]:
def __rich_repr__(self) -> rich.repr.Result:
try:
if self._filters:
- yield "query", " AND ".join(
- ",".join(selector.css for selector in selectors)
- for selectors in self._filters
+ yield (
+ "query",
+ " AND ".join(
+ ",".join(selector.css for selector in selectors)
+ for selectors in self._filters
+ ),
)
if self._excludes:
- yield "exclude", " OR ".join(
- ",".join(selector.css for selector in selectors)
- for selectors in self._excludes
+ yield (
+ "exclude",
+ " OR ".join(
+ ",".join(selector.css for selector in selectors)
+ for selectors in self._excludes
+ ),
)
except AttributeError:
pass
@@ -178,7 +185,12 @@ def filter(self, selector: str) -> DOMQuery[QueryType]:
New DOM Query.
"""
- return DOMQuery(self.node, filter=selector, parent=self)
+ return DOMQuery(
+ self.node,
+ filter=selector,
+ deep=self._deep,
+ parent=self,
+ )
def exclude(self, selector: str) -> DOMQuery[QueryType]:
"""Exclude nodes that match a given selector.
@@ -189,7 +201,12 @@ def exclude(self, selector: str) -> DOMQuery[QueryType]:
Returns:
New DOM query.
"""
- return DOMQuery(self.node, exclude=selector, parent=self)
+ return DOMQuery(
+ self.node,
+ exclude=selector,
+ deep=self._deep,
+ parent=self,
+ )
@overload
def first(self) -> QueryType: ...
diff --git a/src/textual/dom.py b/src/textual/dom.py
index 1a6d969cf3..3dedcce317 100644
--- a/src/textual/dom.py
+++ b/src/textual/dom.py
@@ -1234,7 +1234,7 @@ def walk_children(
return cast("list[DOMNode]", nodes)
@overload
- def query(self, selector: str | None) -> DOMQuery[Widget]: ...
+ def query(self, selector: str | None = None) -> DOMQuery[Widget]: ...
@overload
def query(self, selector: type[QueryType]) -> DOMQuery[QueryType]: ...
@@ -1258,6 +1258,35 @@ def query(
else:
return DOMQuery[QueryType](self, filter=selector.__name__)
+ @overload
+ def query_children(self, selector: str | None = None) -> DOMQuery[Widget]: ...
+
+ @overload
+ def query_children(self, selector: type[QueryType]) -> DOMQuery[QueryType]: ...
+
+ def query_children(
+ self, selector: str | type[QueryType] | None = None
+ ) -> DOMQuery[Widget] | DOMQuery[QueryType]:
+ """Query the DOM for the immediate children that match a selector or widget type.
+
+ Note that this will not return child widgets more than a single level deep.
+ If you want to a query to potentially match all children in the widget tree,
+ see [query][textual.dom.DOMNode.query].
+
+ Args:
+ selector: A CSS selector, widget type, or `None` for all nodes.
+
+ Returns:
+ A query object.
+ """
+ from .css.query import DOMQuery, QueryType
+ from .widget import Widget
+
+ if isinstance(selector, str) or selector is None:
+ return DOMQuery[Widget](self, deep=False, filter=selector)
+ else:
+ return DOMQuery[QueryType](self, deep=False, filter=selector.__name__)
+
@overload
def query_one(self, selector: str) -> Widget: ...
diff --git a/src/textual/widget.py b/src/textual/widget.py
index 0f1fa9c6c4..bacdec9a42 100644
--- a/src/textual/widget.py
+++ b/src/textual/widget.py
@@ -55,6 +55,7 @@
from ._styles_cache import StylesCache
from ._types import AnimationLevel
from .actions import SkipAction
+from .await_complete import AwaitComplete
from .await_remove import AwaitRemove
from .box_model import BoxModel
from .cache import FIFOCache
@@ -626,20 +627,15 @@ def set_loading(self, loading: bool) -> Awaitable:
An optional awaitable.
"""
LOADING_INDICATOR_CLASS = "-textual-loading-indicator"
+ LOADING_INDICATOR_QUERY = f".{LOADING_INDICATOR_CLASS}"
+ remove_indicator = self.query_children(LOADING_INDICATOR_QUERY).remove()
if loading:
loading_indicator = self.get_loading_widget()
loading_indicator.add_class(LOADING_INDICATOR_CLASS)
await_mount = self.mount(loading_indicator)
- return await_mount
+ return AwaitComplete(remove_indicator, await_mount)
else:
- for child in self.children:
- if child.has_class(LOADING_INDICATOR_CLASS):
- return child.remove()
-
- async def dummy() -> None:
- """Do nothing if there is no indicator."""
-
- return dummy()
+ return remove_indicator
async def _watch_loading(self, loading: bool) -> None:
"""Called when the 'loading' reactive is changed."""
| diff --git a/tests/test_query.py b/tests/test_query.py
index 19aac12dbe..07f608824a 100644
--- a/tests/test_query.py
+++ b/tests/test_query.py
@@ -56,6 +56,11 @@ class App(Widget):
# repeat tests to account for caching
for repeat in range(3):
+ assert list(app.query_children()) == [main_view, help_view]
+ assert list(app.query_children("*")) == [main_view, help_view]
+ assert list(app.query_children("#help")) == [help_view]
+ assert list(main_view.query_children(".float")) == [sidebar]
+
assert list(app.query("Frob")) == []
assert list(app.query(".frob")) == []
assert list(app.query("#frob")) == []
| diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68cd1546ea..170a8189e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Fixed auto width not working for option lists https://github.com/Textualize/textual/pull/4507
+### Added
+
+- Added `DOMNode.query_children` https://github.com/Textualize/textual/pull/4508
+
## [0.59.0] - 2024-05-11
### Fixed
| [
{
"components": [
{
"doc": "Query the DOM for the immediate children that match a selector or widget type.\n\nNote that this will not return child widgets more than a single level deep.\nIf you want to a query to potentially match all children in the widget tree,\nsee [query][textual.dom.DOMNode.q... | [
"tests/test_query.py::test_query"
] | [
"tests/test_query.py::test_query_classes",
"tests/test_query.py::test_invalid_query"
] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
query children
Adds a `query_children` method. Which is virtually the same as `query`, but only finds immediate children.
----------
</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/dom.py]
(definition of DOMNode.query_children:)
def query_children( self, selector: str | type[QueryType] | None = None ) -> DOMQuery[Widget] | DOMQuery[QueryType]:
"""Query the DOM for the immediate children that match a selector or widget type.
Note that this will not return child widgets more than a single level deep.
If you want to a query to potentially match all children in the widget tree,
see [query][textual.dom.DOMNode.query].
Args:
selector: A CSS selector, widget type, or `None` for all nodes.
Returns:
A query object."""
[end of new definitions in src/textual/dom.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-3463 | 3,463 | tobymao/sqlglot | null | 58d5f2bece42acdda5f8c08d30e6f61a5e538d4c | 2024-05-12T05:01:57Z | diff --git a/sqlglot/dialects/bigquery.py b/sqlglot/dialects/bigquery.py
index 0d2cfc1a6b..d38452551f 100644
--- a/sqlglot/dialects/bigquery.py
+++ b/sqlglot/dialects/bigquery.py
@@ -156,7 +156,7 @@ def _build_date(args: t.List) -> exp.Date | exp.DateFromParts:
def _build_to_hex(args: t.List) -> exp.Hex | exp.MD5:
# TO_HEX(MD5(..)) is common in BigQuery, so it's parsed into MD5 to simplify its transpilation
arg = seq_get(args, 0)
- return exp.MD5(this=arg.this) if isinstance(arg, exp.MD5Digest) else exp.Hex(this=arg)
+ return exp.MD5(this=arg.this) if isinstance(arg, exp.MD5Digest) else exp.LowerHex(this=arg)
def _array_contains_sql(self: BigQuery.Generator, expression: exp.ArrayContains) -> str:
@@ -245,6 +245,8 @@ class BigQuery(Dialect):
# https://cloud.google.com/bigquery/docs/querying-partitioned-tables#query_an_ingestion-time_partitioned_table
PSEUDOCOLUMNS = {"_PARTITIONTIME", "_PARTITIONDATE"}
+ HEX_LOWERCASE = True
+
def normalize_identifier(self, expression: E) -> E:
if isinstance(expression, exp.Identifier):
parent = expression.parent
@@ -603,7 +605,8 @@ class Generator(generator.Generator):
),
exp.GenerateSeries: rename_func("GENERATE_ARRAY"),
exp.GroupConcat: rename_func("STRING_AGG"),
- exp.Hex: rename_func("TO_HEX"),
+ exp.Hex: lambda self, e: self.func("UPPER", self.func("TO_HEX", self.sql(e, "this"))),
+ exp.LowerHex: rename_func("TO_HEX"),
exp.If: if_sql(false_value="NULL"),
exp.ILike: no_ilike_sql,
exp.IntDiv: rename_func("DIV"),
diff --git a/sqlglot/dialects/dialect.py b/sqlglot/dialects/dialect.py
index cc1d62087a..b55f3fd68d 100644
--- a/sqlglot/dialects/dialect.py
+++ b/sqlglot/dialects/dialect.py
@@ -290,6 +290,22 @@ class Dialect(metaclass=_Dialect):
) SELECT c FROM y;
"""
+ HEX_LOWERCASE = False
+ """
+ Different dialect, `HEX` function will producing a different string, some are in
+ lowercase, other are in uppercase. HEX_LOWERCASE property can determine the case
+ of the string which current dialect use. `HEX` can be wrapped by an additional
+ lower or upper function to convert the output to exact dialect.
+ For example,
+ `SELECT TO_HEX(x)`;
+ in Bigquery will be rewritten as the following one in Presto and Trino
+ `SELECT LOWER(TO_HEX(x))`;
+ In another example,
+ `SELECT TO_HEX(x)`;
+ in Presto will be rewritten as the following one in Bigquery
+ `SELECT UPPER(TO_HEX(x))`;
+ """
+
# --- Autofilled ---
tokenizer_class = Tokenizer
diff --git a/sqlglot/dialects/presto.py b/sqlglot/dialects/presto.py
index b6e44cb9b9..63f6c03469 100644
--- a/sqlglot/dialects/presto.py
+++ b/sqlglot/dialects/presto.py
@@ -385,6 +385,9 @@ class Generator(generator.Generator):
"ARRAY_JOIN", self.func("ARRAY_AGG", e.this), e.args.get("separator")
),
exp.Hex: rename_func("TO_HEX"),
+ exp.LowerHex: lambda self, e: self.func(
+ "LOWER", self.func("TO_HEX", self.sql(e, "this"))
+ ),
exp.If: if_sql(),
exp.ILike: no_ilike_sql,
exp.Initcap: _initcap_sql,
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index 8c02919196..eedb70008e 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -5193,6 +5193,10 @@ class Hex(Func):
pass
+class LowerHex(Hex):
+ pass
+
+
class Xor(Connector, Func):
arg_types = {"this": False, "expression": False, "expressions": False}
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
index bdfeef38b7..146637adf5 100644
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -1301,6 +1301,19 @@ def identifier_sql(self, expression: exp.Identifier) -> str:
text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
return text
+ def hex_sql(self, expression: exp.Hex) -> str:
+ text = self.func("HEX", self.sql(expression, "this"))
+ if self.dialect.HEX_LOWERCASE:
+ text = self.func("LOWER", text)
+
+ return text
+
+ def lowerhex_sql(self, expression: exp.LowerHex) -> str:
+ text = self.func("HEX", self.sql(expression, "this"))
+ if not self.dialect.HEX_LOWERCASE:
+ text = self.func("LOWER", text)
+ return text
+
def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
input_format = self.sql(expression, "input_format")
input_format = f"INPUTFORMAT {input_format}" if input_format else ""
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index a039258e68..e621f97f96 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -61,6 +61,23 @@ def build_logarithm(args: t.List, dialect: Dialect) -> exp.Func:
return (exp.Ln if dialect.parser_class.LOG_DEFAULTS_TO_LN else exp.Log)(this=this)
+def build_hex(args: t.List, dialect: Dialect) -> exp.Hex | exp.LowerHex:
+ arg = seq_get(args, 0)
+ return exp.LowerHex(this=arg) if dialect.HEX_LOWERCASE else exp.Hex(this=arg)
+
+
+def build_lower(args: t.List) -> exp.Lower | exp.Hex:
+ # LOWER(HEX(..)) can be simplified to LowerHex to simplify its transpilation
+ arg = seq_get(args, 0)
+ return exp.LowerHex(this=arg.this) if isinstance(arg, exp.Hex) else exp.Lower(this=arg)
+
+
+def build_upper(args: t.List) -> exp.Upper | exp.Hex:
+ # UPPER(HEX(..)) can be simplified to Hex to simplify its transpilation
+ arg = seq_get(args, 0)
+ return exp.Hex(this=arg.this) if isinstance(arg, exp.Hex) else exp.Upper(this=arg)
+
+
def build_extract_json_with_path(expr_type: t.Type[E]) -> t.Callable[[t.List, Dialect], E]:
def _builder(args: t.List, dialect: Dialect) -> E:
expression = expr_type(
@@ -148,6 +165,9 @@ class Parser(metaclass=_Parser):
length=exp.Literal.number(10),
),
"VAR_MAP": build_var_map,
+ "LOWER": build_lower,
+ "UPPER": build_upper,
+ "HEX": build_hex,
}
NO_PAREN_FUNCTIONS = {
| diff --git a/tests/dialects/test_bigquery.py b/tests/dialects/test_bigquery.py
index 9df897c18b..c5a7bad3f6 100644
--- a/tests/dialects/test_bigquery.py
+++ b/tests/dialects/test_bigquery.py
@@ -631,6 +631,58 @@ def test_bigquery(self):
"mysql": "SELECT DATE_SUB(TIMESTAMP('2008-12-25 15:30:00+00'), INTERVAL 10 MINUTE)",
},
)
+ self.validate_all(
+ "LOWER(TO_HEX(x))",
+ write={
+ "": "LOWER(HEX(x))",
+ "bigquery": "TO_HEX(x)",
+ "presto": "LOWER(TO_HEX(x))",
+ "trino": "LOWER(TO_HEX(x))",
+ "clickhouse": "LOWER(HEX(x))",
+ "hive": "LOWER(HEX(x))",
+ "spark": "LOWER(HEX(x))",
+ },
+ )
+ self.validate_all(
+ "TO_HEX(x)",
+ read={
+ "": "LOWER(HEX(x))",
+ "presto": "LOWER(TO_HEX(x))",
+ "trino": "LOWER(TO_HEX(x))",
+ "clickhouse": "LOWER(HEX(x))",
+ "hive": "LOWER(HEX(x))",
+ "spark": "LOWER(HEX(x))",
+ },
+ write={
+ "": "LOWER(HEX(x))",
+ "bigquery": "TO_HEX(x)",
+ "presto": "LOWER(TO_HEX(x))",
+ "trino": "LOWER(TO_HEX(x))",
+ "clickhouse": "LOWER(HEX(x))",
+ "hive": "LOWER(HEX(x))",
+ "spark": "LOWER(HEX(x))",
+ },
+ )
+ self.validate_all(
+ "UPPER(TO_HEX(x))",
+ read={
+ "": "HEX(x)",
+ "presto": "TO_HEX(x)",
+ "trino": "TO_HEX(x)",
+ "clickhouse": "HEX(x)",
+ "hive": "HEX(x)",
+ "spark": "HEX(x)",
+ },
+ write={
+ "": "HEX(x)",
+ "bigquery": "UPPER(TO_HEX(x))",
+ "presto": "TO_HEX(x)",
+ "trino": "TO_HEX(x)",
+ "clickhouse": "HEX(x)",
+ "hive": "HEX(x)",
+ "spark": "HEX(x)",
+ },
+ )
self.validate_all(
"MD5(x)",
read={
@@ -653,6 +705,9 @@ def test_bigquery(self):
read={
"duckdb": "SELECT MD5(some_string)",
"spark": "SELECT MD5(some_string)",
+ "clickhouse": "SELECT LOWER(HEX(MD5(some_string)))",
+ "presto": "SELECT LOWER(TO_HEX(MD5(some_string)))",
+ "trino": "SELECT LOWER(TO_HEX(MD5(some_string)))",
},
write={
"": "SELECT MD5(some_string)",
diff --git a/tests/test_expressions.py b/tests/test_expressions.py
index 550f1fc2ef..1395b24ea9 100644
--- a/tests/test_expressions.py
+++ b/tests/test_expressions.py
@@ -674,7 +674,9 @@ def test_functions(self):
self.assertIsInstance(parse_one("STANDARD_HASH('hello', 'sha256')"), exp.StandardHash)
self.assertIsInstance(parse_one("DATE(foo)"), exp.Date)
self.assertIsInstance(parse_one("HEX(foo)"), exp.Hex)
- self.assertIsInstance(parse_one("TO_HEX(foo)", read="bigquery"), exp.Hex)
+ self.assertIsInstance(parse_one("LOWER(HEX(foo))"), exp.LowerHex)
+ self.assertIsInstance(parse_one("TO_HEX(foo)", read="bigquery"), exp.LowerHex)
+ self.assertIsInstance(parse_one("UPPER(TO_HEX(foo))", read="bigquery"), exp.Hex)
self.assertIsInstance(parse_one("TO_HEX(MD5(foo))", read="bigquery"), exp.MD5)
self.assertIsInstance(parse_one("TRANSFORM(a, b)", read="spark"), exp.Transform)
self.assertIsInstance(parse_one("ADD_MONTHS(a, b)"), exp.AddMonths)
| [] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_bigquery",
"tests/test_expressions.py::TestExpressions::test_functions"
] | [
"tests/dialects/test_bigquery.py::TestBigQuery::test_errors",
"tests/dialects/test_bigquery.py::TestBigQuery::test_group_concat",
"tests/dialects/test_bigquery.py::TestBigQuery::test_json_object",
"tests/dialects/test_bigquery.py::TestBigQuery::test_merge",
"tests/dialects/test_bigquery.py::TestBigQuery::te... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat(transpiler): handle different hex behavior for dialects
Fixes https://github.com/tobymao/sqlglot/issues/3460
- Default hex function of all dialects, including `SQLGlot` dialect, to uppercase.
- Set HEX_LOWERCASE to True in the dialect if it produces lowercase output.
- Simplify LOWER and UPPER expression depending on HEX_LOWERCASE configuration.
----------
</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>
</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 | ||
pvlib__pvlib-python-2048 | 2,048 | pvlib/pvlib-python | 0.10 | 1eecaa38e8cf07a013a6bf00ea7378c9b23ba65e | 2024-05-12T00:16:30Z | diff --git a/docs/examples/agrivoltaics/README.rst b/docs/examples/agrivoltaics/README.rst
new file mode 100644
index 0000000000..9c3c2ad045
--- /dev/null
+++ b/docs/examples/agrivoltaics/README.rst
@@ -0,0 +1,2 @@
+Agrivoltaic Systems Modelling
+-----------------------------
diff --git a/docs/examples/agrivoltaics/plot_diffuse_PAR_Spitters_relationship.py b/docs/examples/agrivoltaics/plot_diffuse_PAR_Spitters_relationship.py
new file mode 100644
index 0000000000..97ebe860a6
--- /dev/null
+++ b/docs/examples/agrivoltaics/plot_diffuse_PAR_Spitters_relationship.py
@@ -0,0 +1,161 @@
+"""
+Calculating daily diffuse PAR using Spitter's relationship
+==========================================================
+
+This example demonstrates how to calculate the diffuse photosynthetically
+active radiation (PAR) from diffuse fraction of broadband insolation.
+"""
+
+# %%
+# The photosynthetically active radiation (PAR) is a key metric in quantifying
+# the photosynthesis process of plants. As with broadband irradiance, PAR can
+# be divided into direct and diffuse components. The diffuse fraction of PAR
+# with respect to the total PAR is important in agrivoltaic systems, where
+# crops are grown under solar panels. The diffuse fraction of PAR can be
+# calculated using the Spitter's relationship [1]_ implemented in
+# :py:func:`~pvlib.irradiance.diffuse_par_spitters`.
+# This model requires the average daily solar zenith angle and the
+# daily fraction of the broadband insolation that is diffuse as inputs.
+#
+# .. note::
+# Understanding the distinction between the broadband insolation and the PAR
+# is a key concept. Broadband insolation is the total amount of solar
+# energy that gets to a surface, often used in PV applications, while PAR
+# is a measurement of a narrower spectrum of wavelengths that are involved
+# in photosynthesis. See section on *Photosynthetically Active insolation*
+# in pp. 222-223 of [1]_.
+#
+# References
+# ----------
+# .. [1] C. J. T. Spitters, H. A. J. M. Toussaint, and J. Goudriaan,
+# 'Separating the diffuse and direct component of global radiation and its
+# implications for modeling canopy photosynthesis Part I. Components of
+# incoming radiation', Agricultural and Forest Meteorology, vol. 38,
+# no. 1, pp. 217-229, Oct. 1986, :doi:`10.1016/0168-1923(86)90060-2`.
+#
+# Read some example data
+# ^^^^^^^^^^^^^^^^^^^^^^
+# Let's read some weather data from a TMY3 file and calculate the solar
+# position.
+
+import pvlib
+import pandas as pd
+import matplotlib.pyplot as plt
+from matplotlib.dates import AutoDateLocator, ConciseDateFormatter
+from pathlib import Path
+
+# Datafile found in the pvlib distribution
+DATA_FILE = Path(pvlib.__path__[0]).joinpath("data", "723170TYA.CSV")
+
+tmy, metadata = pvlib.iotools.read_tmy3(
+ DATA_FILE, coerce_year=2002, map_variables=True
+)
+tmy = tmy.filter(
+ ["ghi", "dhi", "dni", "pressure", "temp_air"]
+) # remaining columns are not needed
+tmy = tmy["2002-09-06":"2002-09-21"] # select some days
+
+solar_position = pvlib.solarposition.get_solarposition(
+ # TMY timestamp is at end of hour, so shift to center of interval
+ tmy.index.shift(freq="-30T"),
+ latitude=metadata["latitude"],
+ longitude=metadata["longitude"],
+ altitude=metadata["altitude"],
+ pressure=tmy["pressure"] * 100, # convert from millibar to Pa
+ temperature=tmy["temp_air"],
+)
+solar_position.index = tmy.index # reset index to end of the hour
+
+# %%
+# Calculate daily values
+# ^^^^^^^^^^^^^^^^^^^^^^
+# The daily average solar zenith angle and the daily diffuse fraction of
+# broadband insolation are calculated as follows:
+
+daily_solar_zenith = solar_position["zenith"].resample("D").mean()
+# integration over the day with a time step of 1 hour
+daily_tmy = tmy[["ghi", "dhi"]].resample("D").sum() * 1
+daily_tmy["diffuse_fraction"] = daily_tmy["dhi"] / daily_tmy["ghi"]
+
+# %%
+# Calculate Photosynthetically Active Radiation
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+# The total PAR can be approximated as 0.50 times the broadband horizontal
+# insolation (integral of GHI) for an average solar elevation higher that 10°.
+# See section on *Photosynthetically Active Radiation* in pp. 222-223 of [1]_.
+
+par = pd.DataFrame({"total": 0.50 * daily_tmy["ghi"]}, index=daily_tmy.index)
+if daily_solar_zenith.min() < 10:
+ raise ValueError(
+ "The total PAR can't be assumed to be half the broadband insolation "
+ + "for average zenith angles lower than 10°."
+ )
+
+# Calculate broadband insolation diffuse fraction, input of the Spitter's model
+daily_tmy["diffuse_fraction"] = daily_tmy["dhi"] / daily_tmy["ghi"]
+
+# Calculate diffuse PAR fraction using Spitter's relationship
+par["diffuse_fraction"] = pvlib.irradiance.diffuse_par_spitters(
+ solar_position["zenith"], daily_tmy["diffuse_fraction"]
+)
+
+# Finally, calculate the diffuse PAR
+par["diffuse"] = par["total"] * par["diffuse_fraction"]
+
+# %%
+# Plot the results
+# ^^^^^^^^^^^^^^^^
+# Insolation on left axis, diffuse fraction on right axis
+
+fig, ax_l = plt.subplots(figsize=(12, 6))
+ax_l.set(
+ xlabel="Time",
+ ylabel="Daily insolation $[Wh/m^2/day]$",
+ title="Diffuse PAR using Spitter's relationship",
+)
+ax_l.xaxis.set_major_formatter(
+ ConciseDateFormatter(AutoDateLocator(), tz=daily_tmy.index.tz)
+)
+ax_l.plot(
+ daily_tmy.index,
+ daily_tmy["ghi"],
+ label="Broadband: total",
+ color="deepskyblue",
+)
+ax_l.plot(
+ daily_tmy.index,
+ daily_tmy["dhi"],
+ label="Broadband: diffuse",
+ color="skyblue",
+ linestyle="-.",
+)
+ax_l.plot(daily_tmy.index, par["total"], label="PAR: total", color="orangered")
+ax_l.plot(
+ daily_tmy.index,
+ par["diffuse"],
+ label="PAR: diffuse",
+ color="coral",
+ linestyle="-.",
+)
+ax_l.grid()
+ax_l.legend(loc="upper left")
+
+ax_r = ax_l.twinx()
+ax_r.set(ylabel="Diffuse fraction")
+ax_r.plot(
+ daily_tmy.index,
+ daily_tmy["diffuse_fraction"],
+ label="Broadband diffuse fraction",
+ color="plum",
+ linestyle=":",
+)
+ax_r.plot(
+ daily_tmy.index,
+ par["diffuse_fraction"],
+ label="PAR diffuse fraction",
+ color="chocolate",
+ linestyle=":",
+)
+ax_r.legend(loc="upper right")
+
+plt.show()
diff --git a/docs/sphinx/source/reference/irradiance/components.rst b/docs/sphinx/source/reference/irradiance/components.rst
index 70e94ab38d..ce75d9d083 100644
--- a/docs/sphinx/source/reference/irradiance/components.rst
+++ b/docs/sphinx/source/reference/irradiance/components.rst
@@ -14,3 +14,4 @@ Decomposing and combining irradiance
irradiance.get_ground_diffuse
irradiance.dni
irradiance.complete_irradiance
+ irradiance.diffuse_par_spitters
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 2fdcd1c444..dacfe4ca49 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -50,6 +50,10 @@ Enhancements
* Added extraterrestrial and direct spectra of the ASTM G173-03 standard with
the new function :py:func:`pvlib.spectrum.get_reference_spectra`.
(:issue:`1963`, :pull:`2039`)
+* Add function :py:func:`pvlib.irradiance.diffuse_par_spitters` to calculate the
+ diffuse fraction of Photosynthetically Active Radiation (PAR) from the
+ global diffuse fraction and the solar zenith.
+ (:issue:`2047`, :pull:`2048`)
Bug fixes
~~~~~~~~~
diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py
index 73448b6d6d..1f16bdf854 100644
--- a/pvlib/irradiance.py
+++ b/pvlib/irradiance.py
@@ -3761,3 +3761,76 @@ def louche(ghi, solar_zenith, datetime_or_doy, max_zenith=90):
data = pd.DataFrame(data, index=datetime_or_doy)
return data
+
+
+def diffuse_par_spitters(daily_solar_zenith, global_diffuse_fraction):
+ r"""
+ Derive daily diffuse fraction of Photosynthetically Active Radiation (PAR)
+ from daily average solar zenith and diffuse fraction of daily insolation.
+
+ The relationship is based on the work of Spitters et al. (1986) [1]_. The
+ resulting value is the fraction of daily PAR that is diffuse.
+
+ .. note::
+ The diffuse fraction is defined as the ratio of
+ diffuse to global daily insolation, in J m⁻² day⁻¹ or equivalent.
+
+ Parameters
+ ----------
+ daily_solar_zenith : numeric
+ Average daily solar zenith angle. In degrees [°].
+
+ global_diffuse_fraction : numeric
+ Fraction of daily global broadband insolation that is diffuse.
+ Unitless [0, 1].
+
+ Returns
+ -------
+ par_diffuse_fraction : numeric
+ Fraction of daily photosynthetically active radiation (PAR) that is
+ diffuse. Unitless [0, 1].
+
+ Notes
+ -----
+ The relationship is given by equations (9) & (10) in [1]_ and (1) in [2]_:
+
+ .. math::
+
+ k_{diffuse\_PAR}^{model} = \frac{PAR_{diffuse}}{PAR_{total}} =
+ \frac{\left[1 + 0.3 \left(1 - \left(k_d\right) ^2\right)\right]
+ k_d}
+ {1 + \left(1 - \left(k_d\right)^2\right) \cos ^2 (90 - \beta)
+ \cos ^3 \beta}
+
+ where :math:`k_d` is the diffuse fraction of the global insolation, and
+ :math:`\beta` is the daily average of the solar elevation angle in degrees.
+
+ A comparison using different models for the diffuse fraction of
+ the global insolation can be found in [2]_ in the context of Sweden.
+
+ References
+ ----------
+ .. [1] C. J. T. Spitters, H. A. J. M. Toussaint, and J. Goudriaan,
+ 'Separating the diffuse and direct component of global radiation and its
+ implications for modeling canopy photosynthesis Part I. Components of
+ incoming radiation', Agricultural and Forest Meteorology, vol. 38,
+ no. 1, pp. 217-229, Oct. 1986, :doi:`10.1016/0168-1923(86)90060-2`.
+ .. [2] S. Ma Lu et al., 'Photosynthetically active radiation decomposition
+ models for agrivoltaic systems applications', Solar Energy, vol. 244,
+ pp. 536-549, Sep. 2022, :doi:`10.1016/j.solener.2022.05.046`.
+ """
+ # notation change:
+ # cosd(90-x) = sind(x) and 90-solar_elevation = solar_zenith
+ cosd_solar_zenith = tools.cosd(daily_solar_zenith)
+ cosd_solar_elevation = tools.sind(daily_solar_zenith)
+ par_diffuse_fraction = (
+ (1 + 0.3 * (1 - global_diffuse_fraction**2))
+ * global_diffuse_fraction
+ / (
+ 1
+ + (1 - global_diffuse_fraction**2)
+ * cosd_solar_zenith**2
+ * cosd_solar_elevation**3
+ )
+ )
+ return par_diffuse_fraction
| diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py
index 19ce0790ee..8e9f99f11f 100644
--- a/pvlib/tests/test_irradiance.py
+++ b/pvlib/tests/test_irradiance.py
@@ -1419,3 +1419,23 @@ def test_SURFACE_ALBEDOS_deprecated():
@pytest.mark.filterwarnings("ignore:SURFACE_ALBEDOS")
def test_SURFACE_ALBEDO_equals():
assert irradiance.SURFACE_ALBEDOS == albedo.SURFACE_ALBEDOS
+
+
+def test_diffuse_par_spitters():
+ solar_zenith, global_diffuse_fraction = np.meshgrid(
+ [90, 85, 75, 60, 40, 30, 10, 0], [0.01, 0.1, 0.3, 0.6, 0.8, 0.99]
+ )
+ solar_zenith = solar_zenith.ravel()
+ global_diffuse_fraction = global_diffuse_fraction.ravel()
+ result = irradiance.diffuse_par_spitters(
+ solar_zenith, global_diffuse_fraction
+ )
+ expected = np.array([
+ 0.01300, 0.01290, 0.01226, 0.01118, 0.01125, 0.01189, 0.01293, 0.01300,
+ 0.12970, 0.12874, 0.12239, 0.11174, 0.11236, 0.11868, 0.12905, 0.12970,
+ 0.38190, 0.37931, 0.36201, 0.33273, 0.33446, 0.35188, 0.38014, 0.38190,
+ 0.71520, 0.71178, 0.68859, 0.64787, 0.65033, 0.67472, 0.71288, 0.71520,
+ 0.88640, 0.88401, 0.86755, 0.83745, 0.83931, 0.85746, 0.88478, 0.88640,
+ 0.99591, 0.99576, 0.99472, 0.99270, 0.99283, 0.99406, 0.99581, 0.99591,
+ ]) # fmt: skip
+ assert_allclose(result, expected, atol=1e-5)
| diff --git a/docs/examples/agrivoltaics/README.rst b/docs/examples/agrivoltaics/README.rst
new file mode 100644
index 0000000000..9c3c2ad045
--- /dev/null
+++ b/docs/examples/agrivoltaics/README.rst
@@ -0,0 +1,2 @@
+Agrivoltaic Systems Modelling
+-----------------------------
diff --git a/docs/sphinx/source/reference/irradiance/components.rst b/docs/sphinx/source/reference/irradiance/components.rst
index 70e94ab38d..ce75d9d083 100644
--- a/docs/sphinx/source/reference/irradiance/components.rst
+++ b/docs/sphinx/source/reference/irradiance/components.rst
@@ -14,3 +14,4 @@ Decomposing and combining irradiance
irradiance.get_ground_diffuse
irradiance.dni
irradiance.complete_irradiance
+ irradiance.diffuse_par_spitters
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index 2fdcd1c444..dacfe4ca49 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -50,6 +50,10 @@ Enhancements
* Added extraterrestrial and direct spectra of the ASTM G173-03 standard with
the new function :py:func:`pvlib.spectrum.get_reference_spectra`.
(:issue:`1963`, :pull:`2039`)
+* Add function :py:func:`pvlib.irradiance.diffuse_par_spitters` to calculate the
+ diffuse fraction of Photosynthetically Active Radiation (PAR) from the
+ global diffuse fraction and the solar zenith.
+ (:issue:`2047`, :pull:`2048`)
Bug fixes
~~~~~~~~~
| [
{
"components": [
{
"doc": "Derive daily diffuse fraction of Photosynthetically Active Radiation (PAR)\nfrom daily average solar zenith and diffuse fraction of daily insolation.\n\nThe relationship is based on the work of Spitters et al. (1986) [1]_. The\nresulting value is the fraction of daily P... | [
"pvlib/tests/test_irradiance.py::test_diffuse_par_spitters"
] | [
"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... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Agrivoltaics - PAR diffuse fraction model
- [x] Closes #2047
- [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.
Adds the model described in #2047.
### Current implementation
I'm a bit hesitant about the tests here. I haven't found any straightforward way to make the tests from the papers. They check the mathematical integrity of the implementation, if that's a thing.
### Docs links
* Model: https://pvlib-python--2048.org.readthedocs.build/en/2048/reference/generated/pvlib.irradiance.diffuse_par_spitters.html
* Example: https://pvlib-python--2048.org.readthedocs.build/en/2048/gallery/agrivoltaics/plot_diffuse_PAR_Spitters_relationship.html
----------
</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 diffuse_par_spitters:)
def diffuse_par_spitters(daily_solar_zenith, global_diffuse_fraction):
"""Derive daily diffuse fraction of Photosynthetically Active Radiation (PAR)
from daily average solar zenith and diffuse fraction of daily insolation.
The relationship is based on the work of Spitters et al. (1986) [1]_. The
resulting value is the fraction of daily PAR that is diffuse.
.. note::
The diffuse fraction is defined as the ratio of
diffuse to global daily insolation, in J m⁻² day⁻¹ or equivalent.
Parameters
----------
daily_solar_zenith : numeric
Average daily solar zenith angle. In degrees [°].
global_diffuse_fraction : numeric
Fraction of daily global broadband insolation that is diffuse.
Unitless [0, 1].
Returns
-------
par_diffuse_fraction : numeric
Fraction of daily photosynthetically active radiation (PAR) that is
diffuse. Unitless [0, 1].
Notes
-----
The relationship is given by equations (9) & (10) in [1]_ and (1) in [2]_:
.. math::
k_{diffuse\_PAR}^{model} = \frac{PAR_{diffuse}}{PAR_{total}} =
\frac{\left[1 + 0.3 \left(1 - \left(k_d\right) ^2\right)\right]
k_d}
{1 + \left(1 - \left(k_d\right)^2\right) \cos ^2 (90 - \beta)
\cos ^3 \beta}
where :math:`k_d` is the diffuse fraction of the global insolation, and
:math:`\beta` is the daily average of the solar elevation angle in degrees.
A comparison using different models for the diffuse fraction of
the global insolation can be found in [2]_ in the context of Sweden.
References
----------
.. [1] C. J. T. Spitters, H. A. J. M. Toussaint, and J. Goudriaan,
'Separating the diffuse and direct component of global radiation and its
implications for modeling canopy photosynthesis Part I. Components of
incoming radiation', Agricultural and Forest Meteorology, vol. 38,
no. 1, pp. 217-229, Oct. 1986, :doi:`10.1016/0168-1923(86)90060-2`.
.. [2] S. Ma Lu et al., 'Photosynthetically active radiation decomposition
models for agrivoltaic systems applications', Solar Energy, vol. 244,
pp. 536-549, Sep. 2022, :doi:`10.1016/j.solener.2022.05.046`."""
[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>> | Here is the discussion in the issues of the pull request.
<issues>
Photosynthetically active radiation decomposition model
Following my GSoC proposal, there are two models I plan to contribute regarding Photosynthetically Active Radiation, PAR. This is of great importance in the design of AgriVoltaic systems, since PAR is one of the metrics used for the simulation of crops productivity.
I pretend this is the first one due to simplicity. The model takes an input of the global irradiance diffuse fraction and the solar elevation, and outputs the fraction of diffuse PAR. See Eq. (1) in [2]. It is a derivation of equations (9) & (10) in [1]. This is known as the Spitters relationship in [2].
- [1] C. J. T. Spitters, H. A. J. M. Toussaint, and J. Goudriaan,
'Separating the diffuse and direct component of global radiation and its
implications for modeling canopy photosynthesis Part I. Components of
incoming radiation', Agricultural and Forest Meteorology, vol. 38,
no. 1, pp. 217-229, Oct. 1986, [:doi:`10.1016/0168-1923(86)90060-2`.](https://doi.org/10.1016/0168-1923(86)90060-2)
- [2] S. Ma Lu et al., 'Photosynthetically active radiation decomposition
models for agrivoltaic systems applications', Solar Energy, vol. 244,
pp. 536-549, Sep. 2022, [:doi:`10.1016/j.solener.2022.05.046`.](https://doi.org/10.1016/j.solener.2022.05.046)
**Describe the solution you'd like**
A function in a new module, presumably `pvlib.par`, that has the function `spitters_relationship` with the described inputs and output.
**Describe alternatives you've considered**
Other names for the module `pvlib.agrivoltaic[s]` or trying to fit it into current structure until new things can be included and then arranged in the future. Take into account moving things requires deprecations.
Other names for the function, may be `par_diffuse_fraction_from_global` or so. However, I think an author-named model is better in this case. There may be more models about that, like the modified by Gu et al., Eq. (3) in [2].
As always, I'm open to other alternatives.
**Additional context**
I will open a PR in short as an initial proposal.
Ask, discuss and suggest freely.
----------
--------------------
</issues> | 6af80da35a7c96059c534ee38be9123bcfc7f50f |
tobymao__sqlglot-3462 | 3,462 | tobymao/sqlglot | null | 2c29bf3b7a163b88754c4593996bbba9b3c791b6 | 2024-05-11T15:53:48Z | diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py
index baed638e2b..7bfefccab5 100644
--- a/sqlglot/dialects/tsql.py
+++ b/sqlglot/dialects/tsql.py
@@ -3,6 +3,7 @@
import datetime
import re
import typing as t
+from functools import partial
from sqlglot import exp, generator, parser, tokens, transforms
from sqlglot.dialects.dialect import (
@@ -211,7 +212,8 @@ def _string_agg_sql(self: TSQL.Generator, expression: exp.GroupConcat) -> str:
if isinstance(expression.this, exp.Order):
if expression.this.this:
this = expression.this.this.pop()
- order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})" # Order has a leading space
+ # Order has a leading space
+ order = f" WITHIN GROUP ({self.sql(expression.this)[1:]})"
separator = expression.args.get("separator") or exp.Literal.string(",")
return f"STRING_AGG({self.format_args(this, separator)}){order}"
@@ -451,7 +453,7 @@ class Tokenizer(tokens.Tokenizer):
**tokens.Tokenizer.KEYWORDS,
"DATETIME2": TokenType.DATETIME,
"DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
- "DECLARE": TokenType.COMMAND,
+ "DECLARE": TokenType.DECLARE,
"EXEC": TokenType.COMMAND,
"IMAGE": TokenType.IMAGE,
"MONEY": TokenType.MONEY,
@@ -526,6 +528,11 @@ class Parser(parser.Parser):
*parser.Parser.TYPE_TOKENS,
}
+ STATEMENT_PARSERS = {
+ **parser.Parser.STATEMENT_PARSERS,
+ TokenType.DECLARE: lambda self: self._parse_declare(),
+ }
+
def _parse_options(self) -> t.Optional[t.List[exp.Expression]]:
if not self._match(TokenType.OPTION):
return None
@@ -708,6 +715,30 @@ def parse_range():
return partition
+ def _parse_declare(self) -> exp.Declare | exp.Command:
+ index = self._index
+ expressions = self._try_parse(partial(self._parse_csv, self._parse_declareitem))
+ if not expressions or self._curr:
+ self._retreat(index)
+ return self._parse_as_command(self._prev)
+ return self.expression(exp.Declare, expressions=expressions)
+
+ def _parse_declareitem(self) -> t.Optional[exp.DeclareItem]:
+ var = self._parse_id_var()
+ if not var:
+ return None
+ value = None
+ self._match(TokenType.ALIAS)
+ if self._match(TokenType.TABLE):
+ table = self.expression(exp.Table, this=var)
+ data_type = self._parse_schema(this=table)
+ else:
+ data_type = self._parse_types()
+ if self._match(TokenType.EQ):
+ value = self._parse_bitwise()
+
+ return self.expression(exp.DeclareItem, this=var, kind=data_type, default=value)
+
class Generator(generator.Generator):
LIMIT_IS_TOP = True
QUERY_HINTS = False
@@ -1067,3 +1098,16 @@ def drop_sql(self, expression: exp.Drop) -> str:
if expression.args["kind"] == "VIEW":
expression.this.set("catalog", None)
return super().drop_sql(expression)
+
+ def declare_sql(self, expression: exp.Declare) -> str:
+ return f"DECLARE {self.expressions(expression, flat=True)}"
+
+ def declareitem_sql(self, expression: exp.DeclareItem) -> str:
+ variable = self.sql(expression, "this")
+ type = self.sql(expression, "kind")
+ # generating sql from a table looks like "TableName (Schema)",
+ # but since we already have the table name (as variable), replace the "name" with the type "TABLE"
+ type = type.replace(variable, "TABLE")
+ default = self.sql(expression, "default")
+ default = f" = {default}" if default else ""
+ return f"{variable} AS {type}{default}"
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
index b3cd4cebef..7ad6bad1d4 100644
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -1445,6 +1445,14 @@ class Pragma(Expression):
pass
+class Declare(Expression):
+ arg_types = {"expressions": True}
+
+
+class DeclareItem(Expression):
+ arg_types = {"this": True, "kind": True, "default": False}
+
+
class Set(Expression):
arg_types = {"expressions": False, "unset": False, "tag": False}
diff --git a/sqlglot/tokens.py b/sqlglot/tokens.py
index adb181365e..25a069b036 100644
--- a/sqlglot/tokens.py
+++ b/sqlglot/tokens.py
@@ -234,6 +234,7 @@ class TokenType(AutoName):
CURRENT_TIME = auto()
CURRENT_TIMESTAMP = auto()
CURRENT_USER = auto()
+ DECLARE = auto()
DEFAULT = auto()
DELETE = auto()
DESC = auto()
| diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py
index 4cd4d0b37f..4d6f1bf34e 100644
--- a/tests/dialects/test_tsql.py
+++ b/tests/dialects/test_tsql.py
@@ -1,5 +1,4 @@
from sqlglot import exp, parse, parse_one
-from sqlglot.parser import logger as parser_logger
from tests.dialects.test_dialect import Validator
from sqlglot.errors import ParseError
@@ -261,7 +260,7 @@ def test_tsql(self):
self.validate_identity("SELECT * FROM ##foo")
self.validate_identity("SELECT a = 1", "SELECT 1 AS a")
self.validate_identity(
- "DECLARE @TestVariable AS VARCHAR(100)='Save Our Planet'", check_command_warning=True
+ "DECLARE @TestVariable AS VARCHAR(100) = 'Save Our Planet'",
)
self.validate_identity(
"SELECT a = 1 UNION ALL SELECT a = b", "SELECT 1 AS a UNION ALL SELECT b AS a"
@@ -902,8 +901,7 @@ def test_rollback(self):
def test_udf(self):
self.validate_identity(
- "DECLARE @DWH_DateCreated DATETIME = CONVERT(DATETIME, getdate(), 104)",
- check_command_warning=True,
+ "DECLARE @DWH_DateCreated AS DATETIME2 = CONVERT(DATETIME2, GETDATE(), 104)",
)
self.validate_identity(
"CREATE PROCEDURE foo @a INTEGER, @b INTEGER AS SELECT @a = SUM(bla) FROM baz AS bar"
@@ -975,9 +973,9 @@ def test_fullproc(self):
BEGIN
SET XACT_ABORT ON;
- DECLARE @DWH_DateCreated DATETIME = CONVERT(DATETIME, getdate(), 104);
- DECLARE @DWH_DateModified DATETIME = CONVERT(DATETIME, getdate(), 104);
- DECLARE @DWH_IdUserCreated INTEGER = SUSER_ID (SYSTEM_USER);
+ DECLARE @DWH_DateCreated AS DATETIME = CONVERT(DATETIME, getdate(), 104);
+ DECLARE @DWH_DateModified DATETIME2 = CONVERT(DATETIME2, GETDATE(), 104);
+ DECLARE @DWH_IdUserCreated INTEGER = SUSER_ID (CURRENT_USER());
DECLARE @DWH_IdUserModified INTEGER = SUSER_ID (SYSTEM_USER);
DECLARE @SalesAmountBefore float;
@@ -987,18 +985,17 @@ def test_fullproc(self):
expected_sqls = [
"CREATE PROCEDURE [TRANSF].[SP_Merge_Sales_Real] @Loadid INTEGER, @NumberOfRows INTEGER AS BEGIN SET XACT_ABORT ON",
- "DECLARE @DWH_DateCreated DATETIME = CONVERT(DATETIME, getdate(), 104)",
- "DECLARE @DWH_DateModified DATETIME = CONVERT(DATETIME, getdate(), 104)",
- "DECLARE @DWH_IdUserCreated INTEGER = SUSER_ID (SYSTEM_USER)",
- "DECLARE @DWH_IdUserModified INTEGER = SUSER_ID (SYSTEM_USER)",
- "DECLARE @SalesAmountBefore float",
+ "DECLARE @DWH_DateCreated AS DATETIME2 = CONVERT(DATETIME2, GETDATE(), 104)",
+ "DECLARE @DWH_DateModified AS DATETIME2 = CONVERT(DATETIME2, GETDATE(), 104)",
+ "DECLARE @DWH_IdUserCreated AS INTEGER = SUSER_ID(CURRENT_USER())",
+ "DECLARE @DWH_IdUserModified AS INTEGER = SUSER_ID(CURRENT_USER())",
+ "DECLARE @SalesAmountBefore AS FLOAT",
"SELECT @SalesAmountBefore = SUM(SalesAmount) FROM TRANSF.[Pre_Merge_Sales_Real] AS S",
"END",
]
- with self.assertLogs(parser_logger):
- for expr, expected_sql in zip(parse(sql, read="tsql"), expected_sqls):
- self.assertEqual(expr.sql(dialect="tsql"), expected_sql)
+ for expr, expected_sql in zip(parse(sql, read="tsql"), expected_sqls):
+ self.assertEqual(expr.sql(dialect="tsql"), expected_sql)
sql = """
CREATE PROC [dbo].[transform_proc] AS
@@ -1012,14 +1009,13 @@ def test_fullproc(self):
"""
expected_sqls = [
- "CREATE PROC [dbo].[transform_proc] AS DECLARE @CurrentDate VARCHAR(20)",
+ "CREATE PROC [dbo].[transform_proc] AS DECLARE @CurrentDate AS VARCHAR(20)",
"SET @CurrentDate = CONVERT(VARCHAR(20), GETDATE(), 120)",
"CREATE TABLE [target_schema].[target_table] (a INTEGER) WITH (DISTRIBUTION=REPLICATE, HEAP)",
]
- with self.assertLogs(parser_logger):
- for expr, expected_sql in zip(parse(sql, read="tsql"), expected_sqls):
- self.assertEqual(expr.sql(dialect="tsql"), expected_sql)
+ for expr, expected_sql in zip(parse(sql, read="tsql"), expected_sqls):
+ self.assertEqual(expr.sql(dialect="tsql"), expected_sql)
def test_charindex(self):
self.validate_identity(
@@ -1825,3 +1821,35 @@ def test_qualify_derived_table_outputs(self):
"duckdb": "WITH t1(c) AS (SELECT 1), t2 AS (SELECT CAST(c AS INTEGER) FROM t1) SELECT * FROM t2",
},
)
+
+ def test_declare(self):
+ # supported cases
+ self.validate_identity("DECLARE @X INT", "DECLARE @X AS INTEGER")
+ self.validate_identity("DECLARE @X INT = 1", "DECLARE @X AS INTEGER = 1")
+ self.validate_identity(
+ "DECLARE @X INT, @Y VARCHAR(10)", "DECLARE @X AS INTEGER, @Y AS VARCHAR(10)"
+ )
+ self.validate_identity(
+ "declare @X int = (select col from table where id = 1)",
+ "DECLARE @X AS INTEGER = (SELECT col FROM table WHERE id = 1)",
+ )
+ self.validate_identity(
+ "declare @X TABLE (Id INT NOT NULL, Name VARCHAR(100) NOT NULL)",
+ "DECLARE @X AS TABLE (Id INTEGER NOT NULL, Name VARCHAR(100) NOT NULL)",
+ )
+ self.validate_identity(
+ "declare @X TABLE (Id INT NOT NULL, constraint PK_Id primary key (Id))",
+ "DECLARE @X AS TABLE (Id INTEGER NOT NULL, CONSTRAINT PK_Id PRIMARY KEY (Id))",
+ )
+ self.validate_identity(
+ "declare @X UserDefinedTableType",
+ "DECLARE @X AS UserDefinedTableType",
+ )
+ self.validate_identity(
+ "DECLARE @MyTableVar TABLE (EmpID INT NOT NULL, PRIMARY KEY CLUSTERED (EmpID), UNIQUE NONCLUSTERED (EmpID), INDEX CustomNonClusteredIndex NONCLUSTERED (EmpID))",
+ check_command_warning=True,
+ )
+ self.validate_identity(
+ "DECLARE vendor_cursor CURSOR FOR SELECT VendorID, Name FROM Purchasing.Vendor WHERE PreferredVendorStatus = 1 ORDER BY VendorID",
+ check_command_warning=True,
+ )
| [] | [
"tests/dialects/test_tsql.py::TestTSQL::test_declare",
"tests/dialects/test_tsql.py::TestTSQL::test_fullproc"
] | [
"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... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: Add T-SQL DECLARE statement parsing
This PR adds DECLARE statement parsing to the TSQL dialect of SQLGlot. I haven't implemented any sql generation functionality for the new Declare and DeclareItem expression types, so running expression.sql will not work (let me know if this should be implemented before this PR could be merged)
This feature can parse scalar DECLAREs:
"DECLARE @var INT",
"DECLARE @var INT = 1",
"DECLARE @var1 INT, @var2 varchar(2)",
"DECLARE @string varchar(2) = 'AB'",
"DECLARE @var INT = (SELECT num FROM table WHERE condition)"
And, it can parse variable table DECLAREs:
"
DECLARE @myTable TABLE (
ID INT NOT NULL,
CONSTRAINT PK_ID PRIMARY KEY CLUSTERED (ID)
)
"
I didn't add any tests for this code to the existing test suite because the existing architecture seems to rely on parsing raw SQL into an AST, then converting the AST back into SQL to compare for accuracy, and this code can't convert the AST back into SQL yet.
Thank you all so much for all the work you've done on this library!
----------
</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>
</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-3457 | 3,457 | tobymao/sqlglot | null | b76dfda7b4122a59c52bcbb445cffc6617e68b8c | 2024-05-10T23:24:28Z | diff --git a/sqlglot/dialects/duckdb.py b/sqlglot/dialects/duckdb.py
index c11315f594..17de6768e4 100644
--- a/sqlglot/dialects/duckdb.py
+++ b/sqlglot/dialects/duckdb.py
@@ -304,6 +304,17 @@ class Parser(parser.Parser):
),
}
+ def _parse_table_sample(self, as_modifier: bool = False) -> t.Optional[exp.TableSample]:
+ # https://duckdb.org/docs/sql/samples.html
+ sample = super()._parse_table_sample(as_modifier=as_modifier)
+ if sample and not sample.args.get("method"):
+ if sample.args.get("size"):
+ sample.set("method", exp.var("RESERVOIR"))
+ else:
+ sample.set("method", exp.var("SYSTEM"))
+
+ return sample
+
def _parse_bracket(
self, this: t.Optional[exp.Expression] = None
) -> t.Optional[exp.Expression]:
@@ -550,6 +561,15 @@ def tablesample_sql(
# This sample clause only applies to a single source, not the entire resulting relation
tablesample_keyword = "TABLESAMPLE"
+ if expression.args.get("size"):
+ method = expression.args.get("method")
+ if method and method.name.upper() != "RESERVOIR":
+ self.unsupported(
+ f"Sampling method {method} is not supported with a discrete sample count, "
+ "defaulting to reservoir sampling"
+ )
+ expression.set("method", exp.var("RESERVOIR"))
+
return super().tablesample_sql(
expression, sep=sep, tablesample_keyword=tablesample_keyword
)
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py
index bdc4218607..68b5be6ca1 100644
--- a/sqlglot/dialects/postgres.py
+++ b/sqlglot/dialects/postgres.py
@@ -233,6 +233,7 @@ class Postgres(Dialect):
CONCAT_COALESCE = True
NULL_ORDERING = "nulls_are_large"
TIME_FORMAT = "'YYYY-MM-DD HH24:MI:SS'"
+ TABLESAMPLE_SIZE_IS_PERCENT = True
TIME_MAPPING = {
"AM": "%p",
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py
index 1ae854ef15..ea3832db09 100644
--- a/sqlglot/dialects/snowflake.py
+++ b/sqlglot/dialects/snowflake.py
@@ -334,6 +334,7 @@ def quote_identifier(self, expression: E, identify: bool = True) -> E:
class Parser(parser.Parser):
IDENTIFY_PIVOT_STRINGS = True
+ DEFAULT_SAMPLING_METHOD = "BERNOULLI"
ID_VAR_TOKENS = {
*parser.Parser.ID_VAR_TOKENS,
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
index e7ee89a6b8..14fbf00b99 100644
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -1102,6 +1102,9 @@ class Parser(metaclass=_Parser):
# Whether the table sample clause expects CSV syntax
TABLESAMPLE_CSV = False
+ # The default method used for table sampling
+ DEFAULT_SAMPLING_METHOD: t.Optional[str] = None
+
# Whether the SET command needs a delimiter (e.g. "=") for assignments
SET_REQUIRES_ASSIGNMENT_DELIMITER = True
@@ -3388,6 +3391,9 @@ def _parse_table_sample(self, as_modifier: bool = False) -> t.Optional[exp.Table
elif self._match_texts(("SEED", "REPEATABLE")):
seed = self._parse_wrapped(self._parse_number)
+ if not method and self.DEFAULT_SAMPLING_METHOD:
+ method = exp.var(self.DEFAULT_SAMPLING_METHOD)
+
return self.expression(
exp.TableSample,
expressions=expressions,
| diff --git a/tests/dialects/test_duckdb.py b/tests/dialects/test_duckdb.py
index f736264c4b..29a2308e91 100644
--- a/tests/dialects/test_duckdb.py
+++ b/tests/dialects/test_duckdb.py
@@ -892,11 +892,11 @@ def test_time(self):
def test_sample(self):
self.validate_identity(
"SELECT * FROM tbl USING SAMPLE 5",
- "SELECT * FROM tbl USING SAMPLE (5 ROWS)",
+ "SELECT * FROM tbl USING SAMPLE RESERVOIR (5 ROWS)",
)
self.validate_identity(
"SELECT * FROM tbl USING SAMPLE 10%",
- "SELECT * FROM tbl USING SAMPLE (10 PERCENT)",
+ "SELECT * FROM tbl USING SAMPLE SYSTEM (10 PERCENT)",
)
self.validate_identity(
"SELECT * FROM tbl USING SAMPLE 10 PERCENT (bernoulli)",
@@ -920,14 +920,13 @@ def test_sample(self):
)
self.validate_all(
- "SELECT * FROM example TABLESAMPLE (3 ROWS) REPEATABLE (82)",
+ "SELECT * FROM example TABLESAMPLE RESERVOIR (3 ROWS) REPEATABLE (82)",
read={
"duckdb": "SELECT * FROM example TABLESAMPLE (3) REPEATABLE (82)",
"snowflake": "SELECT * FROM example SAMPLE (3 ROWS) SEED (82)",
},
write={
- "duckdb": "SELECT * FROM example TABLESAMPLE (3 ROWS) REPEATABLE (82)",
- "snowflake": "SELECT * FROM example TABLESAMPLE (3 ROWS) SEED (82)",
+ "duckdb": "SELECT * FROM example TABLESAMPLE RESERVOIR (3 ROWS) REPEATABLE (82)",
},
)
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py
index e8f827a9b9..6e532beced 100644
--- a/tests/dialects/test_snowflake.py
+++ b/tests/dialects/test_snowflake.py
@@ -99,9 +99,6 @@ def test_snowflake(self):
self.validate_identity(
'DESCRIBE TABLE "SNOWFLAKE_SAMPLE_DATA"."TPCDS_SF100TCL"."WEB_SITE" type=stage'
)
- self.validate_identity(
- "SELECT a FROM test PIVOT(SUM(x) FOR y IN ('z', 'q')) AS x TABLESAMPLE (0.1)"
- )
self.validate_identity(
"SELECT * FROM DATA AS DATA_L ASOF JOIN DATA AS DATA_R MATCH_CONDITION (DATA_L.VAL > DATA_R.VAL) ON DATA_L.ID = DATA_R.ID"
)
@@ -146,10 +143,6 @@ def test_snowflake(self):
"SELECT TIMESTAMPFROMPARTS(d, t)",
"SELECT TIMESTAMP_FROM_PARTS(d, t)",
)
- self.validate_identity(
- "SELECT user_id, value FROM table_name SAMPLE ($s) SEED (0)",
- "SELECT user_id, value FROM table_name TABLESAMPLE ($s) SEED (0)",
- )
self.validate_identity(
"SELECT v:attr[0].name FROM vartab",
"SELECT GET_PATH(v, 'attr[0].name') FROM vartab",
@@ -250,18 +243,6 @@ def test_snowflake(self):
"snowflake": "OBJECT_CONSTRUCT_KEEP_NULL('key_1', 'one', 'key_2', NULL)",
},
)
- self.validate_all(
- "SELECT * FROM example TABLESAMPLE (3) SEED (82)",
- read={
- "databricks": "SELECT * FROM example TABLESAMPLE (3 PERCENT) REPEATABLE (82)",
- "duckdb": "SELECT * FROM example TABLESAMPLE (3 PERCENT) REPEATABLE (82)",
- },
- write={
- "databricks": "SELECT * FROM example TABLESAMPLE (3 PERCENT) REPEATABLE (82)",
- "duckdb": "SELECT * FROM example TABLESAMPLE (3 PERCENT) REPEATABLE (82)",
- "snowflake": "SELECT * FROM example TABLESAMPLE (3) SEED (82)",
- },
- )
self.validate_all(
"SELECT TIME_FROM_PARTS(12, 34, 56, 987654321)",
write={
@@ -919,18 +900,27 @@ def test_staged_files(self):
def test_sample(self):
self.validate_identity("SELECT * FROM testtable TABLESAMPLE BERNOULLI (20.3)")
- self.validate_identity("SELECT * FROM testtable TABLESAMPLE (100)")
self.validate_identity("SELECT * FROM testtable TABLESAMPLE SYSTEM (3) SEED (82)")
- self.validate_identity("SELECT * FROM testtable TABLESAMPLE (10 ROWS)")
self.validate_identity(
- "SELECT i, j FROM table1 AS t1 INNER JOIN table2 AS t2 TABLESAMPLE (50) WHERE t2.j = t1.i"
+ "SELECT a FROM test PIVOT(SUM(x) FOR y IN ('z', 'q')) AS x TABLESAMPLE BERNOULLI (0.1)"
+ )
+ self.validate_identity(
+ "SELECT i, j FROM table1 AS t1 INNER JOIN table2 AS t2 TABLESAMPLE BERNOULLI (50) WHERE t2.j = t1.i"
+ )
+ self.validate_identity(
+ "SELECT * FROM (SELECT * FROM t1 JOIN t2 ON t1.a = t2.c) TABLESAMPLE BERNOULLI (1)"
)
self.validate_identity(
- "SELECT * FROM (SELECT * FROM t1 JOIN t2 ON t1.a = t2.c) TABLESAMPLE (1)"
+ "SELECT * FROM testtable TABLESAMPLE (10 ROWS)",
+ "SELECT * FROM testtable TABLESAMPLE BERNOULLI (10 ROWS)",
+ )
+ self.validate_identity(
+ "SELECT * FROM testtable TABLESAMPLE (100)",
+ "SELECT * FROM testtable TABLESAMPLE BERNOULLI (100)",
)
self.validate_identity(
"SELECT * FROM testtable SAMPLE (10)",
- "SELECT * FROM testtable TABLESAMPLE (10)",
+ "SELECT * FROM testtable TABLESAMPLE BERNOULLI (10)",
)
self.validate_identity(
"SELECT * FROM testtable SAMPLE ROW (0)",
@@ -940,7 +930,29 @@ def test_sample(self):
"SELECT a FROM test SAMPLE BLOCK (0.5) SEED (42)",
"SELECT a FROM test TABLESAMPLE BLOCK (0.5) SEED (42)",
)
+ self.validate_identity(
+ "SELECT user_id, value FROM table_name SAMPLE BERNOULLI ($s) SEED (0)",
+ "SELECT user_id, value FROM table_name TABLESAMPLE BERNOULLI ($s) SEED (0)",
+ )
+ self.validate_all(
+ "SELECT * FROM example TABLESAMPLE BERNOULLI (3) SEED (82)",
+ read={
+ "duckdb": "SELECT * FROM example TABLESAMPLE BERNOULLI (3 PERCENT) REPEATABLE (82)",
+ },
+ write={
+ "databricks": "SELECT * FROM example TABLESAMPLE (3 PERCENT) REPEATABLE (82)",
+ "duckdb": "SELECT * FROM example TABLESAMPLE BERNOULLI (3 PERCENT) REPEATABLE (82)",
+ "snowflake": "SELECT * FROM example TABLESAMPLE BERNOULLI (3) SEED (82)",
+ },
+ )
+ self.validate_all(
+ "SELECT * FROM test AS _tmp TABLESAMPLE (5)",
+ write={
+ "postgres": "SELECT * FROM test AS _tmp TABLESAMPLE BERNOULLI (5)",
+ "snowflake": "SELECT * FROM test AS _tmp TABLESAMPLE BERNOULLI (5)",
+ },
+ )
self.validate_all(
"""
SELECT i, j
@@ -950,7 +962,7 @@ def test_sample(self):
table2 AS t2 SAMPLE (50) -- 50% of rows in table2
WHERE t2.j = t1.i""",
write={
- "snowflake": "SELECT i, j FROM table1 AS t1 TABLESAMPLE (25) /* 25% of rows in table1 */ INNER JOIN table2 AS t2 TABLESAMPLE (50) /* 50% of rows in table2 */ WHERE t2.j = t1.i",
+ "snowflake": "SELECT i, j FROM table1 AS t1 TABLESAMPLE BERNOULLI (25) /* 25% of rows in table1 */ INNER JOIN table2 AS t2 TABLESAMPLE BERNOULLI (50) /* 50% of rows in table2 */ WHERE t2.j = t1.i",
},
)
self.validate_all(
@@ -962,7 +974,7 @@ def test_sample(self):
self.validate_all(
"SELECT * FROM (SELECT * FROM t1 join t2 on t1.a = t2.c) SAMPLE (1)",
write={
- "snowflake": "SELECT * FROM (SELECT * FROM t1 JOIN t2 ON t1.a = t2.c) TABLESAMPLE (1)",
+ "snowflake": "SELECT * FROM (SELECT * FROM t1 JOIN t2 ON t1.a = t2.c) TABLESAMPLE BERNOULLI (1)",
"spark": "SELECT * FROM (SELECT * FROM t1 JOIN t2 ON t1.a = t2.c) TABLESAMPLE (1 PERCENT)",
},
)
| [] | [
"tests/dialects/test_duckdb.py::TestDuckDB::test_sample",
"tests/dialects/test_snowflake.py::TestSnowflake::test_sample"
] | [
"tests/dialects/test_duckdb.py::TestDuckDB::test_array",
"tests/dialects/test_duckdb.py::TestDuckDB::test_array_index",
"tests/dialects/test_duckdb.py::TestDuckDB::test_bool_or",
"tests/dialects/test_duckdb.py::TestDuckDB::test_cast",
"tests/dialects/test_duckdb.py::TestDuckDB::test_duckdb",
"tests/dialec... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Feat!: improve transpilation of TABLESAMPLE clause
Fixes #3456
References:
- https://duckdb.org/docs/sql/samples.html
- https://docs.snowflake.com/en/sql-reference/constructs/sample
- https://www.postgresql.org/docs/current/sql-select.html
----------
</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>
</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>
Rendering of `TABLESAMPLE` yields invalid `PERCENT` keyword for Postgres dialect
Hi folks,
big kudos for the quick turnaround on some of the issues I've recently filed, really appreciated! 🙌 🚀
Looks like we've just hit have another small one - related to rendering of `TABLESAMPLE` percentages for Postgres as target.
Given the following code:
```
query = "SELECT * FROM test AS _tmp TABLESAMPLE (5)"
result = parse_one(query, read="snowflake").sql(dialect="postgres")
print(result)
```
... `sqlglot` generates:
```
SELECT * FROM test AS _tmp TABLESAMPLE (5 PERCENT)
```
... however, this is not valid Postgres syntax, as Postgres:
* (1) requires the `SYSTEM` keyword to be present as default, and
* (2) does not recognize the `PERCENT` keyword.
So, the correct syntax in Postgres would be:
```
SELECT * FROM test AS _tmp TABLESAMPLE SYSTEM (5)
```
For point (2), we've been able to use the following workaround in our code base:
```
Postgres.TABLESAMPLE_SIZE_IS_PERCENT = True
```
We also have a workaround for point (1) in place, so not a blocker, but would be great if it could be fixed for the Postgres dialect as well. 🙌
----------
--------------------
</issues> | ceb42fabad60312699e4b15936aeebac00e22e4d | |
pvlib__pvlib-python-2046 | 2,046 | pvlib/pvlib-python | 0.10 | 55e0a36fac1e3931b92f5f11508f6c09d903e0cc | 2024-05-10T21:14:40Z | diff --git a/docs/examples/bifacial/plot_irradiance_nonuniformity_loss.py b/docs/examples/bifacial/plot_irradiance_nonuniformity_loss.py
new file mode 100644
index 0000000000..8b19ebeb79
--- /dev/null
+++ b/docs/examples/bifacial/plot_irradiance_nonuniformity_loss.py
@@ -0,0 +1,129 @@
+"""
+Plot Irradiance Non-uniformity Loss
+===================================
+
+Calculate the DC power lost to irradiance non-uniformity in a bifacial PV
+array.
+"""
+
+# %%
+# The incident irradiance on the backside of a bifacial PV module is
+# not uniform due to neighboring rows, the ground albedo, and site conditions.
+# When each cell works at different irradiance levels, the power produced by
+# the module is less than the sum of the power produced by each cell since the
+# maximum power point (MPP) of each cell is different, but cells connected in
+# series will operate at the same current.
+# This is known as irradiance non-uniformity loss.
+#
+# Calculating the IV curve of each cell and then matching the working point of
+# the whole module is computationally expensive, so a simple model to account
+# for this loss is of interest. Deline et al. [1]_ proposed a model based on
+# the Relative Mean Absolute Difference (RMAD) of the irradiance of each cell.
+# They considered the standard deviation of the cells' irradiances, but they
+# found that the RMAD was a better predictor of the mismatch loss.
+#
+# This example demonstrates how to model the irradiance non-uniformity loss
+# from the irradiance levels of each cell in a PV module.
+#
+# The function
+# :py:func:`pvlib.bifacial.power_mismatch_deline` is
+# used to transform the Relative Mean Absolute Difference (RMAD) of the
+# irradiance into a power loss mismatch. Down below you will find a
+# numpy-based implementation of the RMAD function.
+#
+# References
+# ----------
+# .. [1] C. Deline, S. Ayala Pelaez, S. MacAlpine, and C. Olalla, 'Estimating
+# and parameterizing mismatch power loss in bifacial photovoltaic
+# systems', Progress in Photovoltaics: Research and Applications, vol. 28,
+# no. 7, pp. 691-703, 2020, :doi:`10.1002/pip.3259`.
+#
+# .. sectionauthor:: Echedey Luis <echelual (at) gmail.com>
+
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib.cm import ScalarMappable
+from matplotlib.colors import Normalize
+
+from pvlib.bifacial import power_mismatch_deline
+
+# %%
+# Problem description
+# -------------------
+# Let's set a fixed irradiance to each cell row of the PV array with the values
+# described in Figure 1 (A), [1]_. We will cover this case for educational
+# purposes, although it can be achieved with the packages
+# :ref:`solarfactors <https://github.com/pvlib/solarfactors/>` and
+# :ref:`bifacial_radiance <https://github.com/NREL/bifacial_radiance>`.
+#
+# Here we set and plot the global irradiance level of each cell.
+
+x = np.arange(12, 0, -1)
+y = np.arange(6, 0, -1)
+cells_irrad = np.repeat([1059, 976, 967, 986, 1034, 1128], len(x)).reshape(
+ len(y), len(x)
+)
+
+color_map = "gray"
+color_norm = Normalize(930, 1150)
+
+fig, ax = plt.subplots()
+fig.suptitle("Global Irradiance Levels of Each Cell")
+fig.colorbar(
+ ScalarMappable(cmap=color_map, norm=color_norm),
+ ax=ax,
+ orientation="vertical",
+ label="$[W/m^2]$",
+)
+ax.set_aspect("equal")
+ax.pcolormesh(
+ x,
+ y,
+ cells_irrad,
+ shading="nearest",
+ edgecolors="black",
+ cmap=color_map,
+ norm=color_norm,
+)
+
+# %%
+# Relative Mean Absolute Difference
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+# Calculate the Relative Mean Absolute Difference (RMAD) of the cells'
+# irradiances with the following function, Eq. (4) of [1]_:
+#
+# .. math::
+#
+# \Delta \left[ unitless \right] = \frac{1}{n^2 \bar{G}_{total}}
+# \sum_{i=1}^{n} \sum_{j=1}^{n} \lvert G_{total,i} - G_{total,j} \rvert
+#
+
+
+def rmad(data, axis=None):
+ """
+ Relative Mean Absolute Difference. Output is [Unitless].
+ https://stackoverflow.com/a/19472336/19371110
+ """
+ mean = np.mean(data, axis)
+ mad = np.mean(np.absolute(data - mean), axis)
+ return mad / mean
+
+
+rmad_cells = rmad(cells_irrad)
+
+# this is the same as a column's RMAD!
+print(rmad_cells == rmad(cells_irrad[:, 0]))
+
+# %%
+# Mismatch Loss
+# ^^^^^^^^^^^^^
+# Calculate the power loss ratio due to the irradiance non-uniformity
+# with :py:func:`pvlib.bifacial.power_mismatch_deline`.
+
+mismatch_loss = power_mismatch_deline(rmad_cells)
+
+print(f"RMAD of the cells' irradiance: {rmad_cells:.3} [unitless]")
+print(
+ "Power loss due to the irradiance non-uniformity: "
+ + f"{mismatch_loss:.3} [unitless]"
+)
diff --git a/docs/sphinx/source/reference/bifacial.rst b/docs/sphinx/source/reference/bifacial.rst
index 6405fe4afc..a107062fd2 100644
--- a/docs/sphinx/source/reference/bifacial.rst
+++ b/docs/sphinx/source/reference/bifacial.rst
@@ -12,6 +12,13 @@ Functions for calculating front and back surface irradiance
bifacial.infinite_sheds.get_irradiance
bifacial.infinite_sheds.get_irradiance_poa
+Loss models that are specific to bifacial PV systems
+
+.. autosummary::
+ :toctree: generated/
+
+ bifacial.power_mismatch_deline
+
Utility functions for bifacial modeling
.. autosummary::
diff --git a/docs/sphinx/source/whatsnew/v0.11.1.rst b/docs/sphinx/source/whatsnew/v0.11.1.rst
index aa2205bb43..1e839c596c 100644
--- a/docs/sphinx/source/whatsnew/v0.11.1.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.1.rst
@@ -10,6 +10,9 @@ Deprecations
Enhancements
~~~~~~~~~~~~
+* Add new losses function that accounts for non-uniform irradiance on bifacial
+ modules, :py:func:`pvlib.bifacial.power_mismatch_deline`.
+ (:issue:`2045`, :pull:`2046`)
Bug fixes
@@ -30,4 +33,4 @@ Requirements
Contributors
~~~~~~~~~~~~
-
+* Echedey Luis (:ghuser:`echedey-ls`)
diff --git a/pvlib/bifacial/__init__.py b/pvlib/bifacial/__init__.py
index 0a6b98d4f5..e166c55108 100644
--- a/pvlib/bifacial/__init__.py
+++ b/pvlib/bifacial/__init__.py
@@ -1,10 +1,10 @@
"""
-The ``bifacial`` module contains functions to model irradiance for bifacial
-modules.
-
+The ``bifacial`` submodule contains functions to model bifacial modules.
"""
+
from pvlib._deprecation import deprecated
-from pvlib.bifacial import pvfactors, infinite_sheds, utils # noqa: F401
+from pvlib.bifacial import pvfactors, infinite_sheds, utils # noqa: F401
+from .loss_models import power_mismatch_deline # noqa: F401
pvfactors_timeseries = deprecated(
since='0.9.1',
diff --git a/pvlib/bifacial/loss_models.py b/pvlib/bifacial/loss_models.py
new file mode 100644
index 0000000000..cbcb2ba4d1
--- /dev/null
+++ b/pvlib/bifacial/loss_models.py
@@ -0,0 +1,155 @@
+import numpy as np
+import pandas as pd
+
+
+def power_mismatch_deline(
+ rmad,
+ coefficients=(0, 0.142, 0.032 * 100),
+ fill_factor: float = None,
+ fill_factor_reference: float = 0.79,
+):
+ r"""
+ Estimate DC power loss due to irradiance non-uniformity.
+
+ This model is described for bifacial modules in [1]_, where the backside
+ irradiance is less uniform due to mounting and site conditions.
+
+ The power loss is estimated by a polynomial model of the Relative Mean
+ Absolute Difference (RMAD) of the cell-by-cell total irradiance.
+
+ Use ``fill_factor`` to account for different fill factors between the
+ data used to fit the model and the module of interest. Specify the model's fill factor with
+ ``fill_factor_reference``.
+
+ .. versionadded:: 0.11.1
+
+ Parameters
+ ----------
+ rmad : numeric
+ The Relative Mean Absolute Difference of the cell-by-cell total
+ irradiance. [Unitless]
+
+ See the *Notes* section for the equation to calculate ``rmad`` from the
+ bifaciality and the front and back irradiances.
+
+ coefficients : float collection or numpy.polynomial.polynomial.Polynomial, default ``(0, 0.142, 0.032 * 100)``
+ The polynomial coefficients to use.
+
+ If a :external:class:`numpy.polynomial.polynomial.Polynomial`,
+ it is evaluated as is. If not a ``Polynomial``, it must be the
+ coefficients of a polynomial in ``rmad``, where the first element is
+ the constant term and the last element is the highest order term. A
+ :external:class:`~numpy.polynomial.polynomial.Polynomial`
+ will be created internally.
+
+ fill_factor : float, optional
+ Fill factor at standard test condition (STC) of the module.
+ Accounts for different fill factors between the trained model and the
+ module under non-uniform irradiance.
+ If not provided, the default ``fill_factor_reference`` of 0.79 is used.
+
+ fill_factor_reference : float, default 0.79
+ Fill factor at STC of the module used to train the model.
+
+ Returns
+ -------
+ loss : numeric
+ The fractional power loss. [Unitless]
+
+ Output will be a ``pandas.Series`` if ``rmad`` is a ``pandas.Series``.
+
+ Notes
+ -----
+ The default model implemented is equation (11) [1]_:
+
+ .. math::
+
+ M[\%] &= 0.142 \Delta[\%] + 0.032 \Delta^2[\%] \qquad \text{(11)}
+
+ M[-] &= 0.142 \Delta[-] + 0.032 \times 100 \Delta^2[-]
+
+ where the upper equation is in percentage (same as paper) and the lower
+ one is unitless. The implementation uses the unitless version, where
+ :math:`M[-]` is the mismatch power loss [unitless] and
+ :math:`\Delta[-]` is the Relative Mean Absolute Difference [unitless]
+ of the global irradiance, Eq. (4) of [1]_ and [2]_.
+ Note that the n-th power coefficient is multiplied by :math:`100^{n-1}`
+ to convert the percentage to unitless.
+
+ The losses definition is Eq. (1) of [1]_, and it's defined as a loss of the
+ output power:
+
+ .. math::
+
+ M = 1 - \frac{P_{Array}}{\sum P_{Cells}} \qquad \text{(1)}
+
+ To account for a module with a fill factor distinct from the one used to
+ train the model (``0.79`` by default), the output of the model can be
+ modified with Eq. (7):
+
+ .. math::
+
+ M_{FF_1} = M_{FF_0} \frac{FF_1}{FF_0} \qquad \text{(7)}
+
+ where parameter ``fill_factor`` is :math:`FF_1` and
+ ``fill_factor_reference`` is :math:`FF_0`.
+
+ In the section *See Also*, you will find two packages that can be used to
+ calculate the irradiance at different points of the module.
+
+ .. note::
+ The global irradiance RMAD is different from the backside irradiance
+ RMAD.
+
+ In case the RMAD of the backside irradiance is known, the global RMAD can
+ be calculated as follows, assuming the front irradiance RMAD is
+ negligible [2]_:
+
+ .. math::
+
+ RMAD(k \cdot X + c) = RMAD(X) \cdot k \frac{k \bar{X}}{k \bar{X} + c}
+ = RMAD(X) \cdot \frac{k}{1 + \frac{c}{k \bar{X}}}
+
+ by similarity with equation (2) of [1]_:
+
+ .. math::
+
+ G_{total\,i} = G_{front\,i} + \phi_{Bifi} G_{rear\,i} \qquad \text{(2)}
+
+ which yields:
+
+ .. math::
+
+ RMAD_{total} = RMAD_{rear} \frac{\phi_{Bifi}}
+ {1 + \frac{G_{front}}{\phi_{Bifi} \bar{G}_{rear}}}
+
+ See Also
+ --------
+ `solarfactors <https://github.com/pvlib/solarfactors/>`_
+ Calculate the irradiance at different points of the module.
+ `bifacial_radiance <https://github.com/NREL/bifacial_radiance>`_
+ Calculate the irradiance at different points of the module.
+
+ References
+ ----------
+ .. [1] C. Deline, S. Ayala Pelaez, S. MacAlpine, and C. Olalla, 'Estimating
+ and parameterizing mismatch power loss in bifacial photovoltaic
+ systems', Progress in Photovoltaics: Research and Applications, vol. 28,
+ no. 7, pp. 691-703, 2020, :doi:`10.1002/pip.3259`.
+ .. [2] “Mean absolute difference,” Wikipedia, Sep. 05, 2023.
+ https://en.wikipedia.org/wiki/Mean_absolute_difference#Relative_mean_absolute_difference
+ (accessed 2024-04-14).
+ """ # noqa: E501
+ if isinstance(coefficients, np.polynomial.Polynomial):
+ model_polynom = coefficients
+ else: # expect an iterable
+ model_polynom = np.polynomial.Polynomial(coef=coefficients)
+
+ if fill_factor: # Eq. (7), [1]
+ # Scale output of trained model to account for different fill factors
+ model_polynom = model_polynom * fill_factor / fill_factor_reference
+
+ mismatch = model_polynom(rmad)
+ if isinstance(rmad, pd.Series):
+ mismatch = pd.Series(mismatch, index=rmad.index)
+ return mismatch
| diff --git a/pvlib/tests/bifacial/test_losses_models.py b/pvlib/tests/bifacial/test_losses_models.py
new file mode 100644
index 0000000000..72dd050928
--- /dev/null
+++ b/pvlib/tests/bifacial/test_losses_models.py
@@ -0,0 +1,54 @@
+from pvlib import bifacial
+
+import pandas as pd
+import numpy as np
+from numpy.testing import assert_allclose
+
+
+def test_power_mismatch_deline():
+ """tests bifacial.power_mismatch_deline"""
+ premise_rmads = np.array([0.0, 0.05, 0.1, 0.15, 0.2, 0.25])
+ # test default model is for fixed tilt
+ expected_ft_mms = np.array([0.0, 0.0151, 0.0462, 0.0933, 0.1564, 0.2355])
+ result_def_mms = bifacial.power_mismatch_deline(premise_rmads)
+ assert_allclose(result_def_mms, expected_ft_mms, atol=1e-5)
+ assert np.all(np.diff(result_def_mms) > 0) # higher RMADs => higher losses
+
+ # test custom coefficients, set model to 1+1*RMAD
+ # as Polynomial class
+ polynomial = np.polynomial.Polynomial([1, 1, 0])
+ result_custom_mms = bifacial.power_mismatch_deline(
+ premise_rmads, coefficients=polynomial
+ )
+ assert_allclose(result_custom_mms, 1 + premise_rmads)
+ # as list
+ result_custom_mms = bifacial.power_mismatch_deline(
+ premise_rmads, coefficients=[1, 1, 0]
+ )
+ assert_allclose(result_custom_mms, 1 + premise_rmads)
+
+ # test datatypes IO with Series
+ result_mms = bifacial.power_mismatch_deline(pd.Series(premise_rmads))
+ assert isinstance(result_mms, pd.Series)
+
+ # test fill_factor, fill_factor_reference
+ # default model + default fill_factor_reference
+ ff_ref_default = 0.79
+ ff_of_interest = 0.65
+ result_mms = bifacial.power_mismatch_deline(
+ premise_rmads, fill_factor=ff_of_interest
+ )
+ assert_allclose(
+ result_mms,
+ expected_ft_mms * ff_of_interest / ff_ref_default,
+ atol=1e-5,
+ )
+ # default model + custom fill_factor_reference
+ ff_of_interest = 0.65
+ ff_ref = 0.75
+ result_mms = bifacial.power_mismatch_deline(
+ premise_rmads, fill_factor=ff_of_interest, fill_factor_reference=ff_ref
+ )
+ assert_allclose(
+ result_mms, expected_ft_mms * ff_of_interest / ff_ref, atol=1e-5
+ )
| diff --git a/docs/sphinx/source/reference/bifacial.rst b/docs/sphinx/source/reference/bifacial.rst
index 6405fe4afc..a107062fd2 100644
--- a/docs/sphinx/source/reference/bifacial.rst
+++ b/docs/sphinx/source/reference/bifacial.rst
@@ -12,6 +12,13 @@ Functions for calculating front and back surface irradiance
bifacial.infinite_sheds.get_irradiance
bifacial.infinite_sheds.get_irradiance_poa
+Loss models that are specific to bifacial PV systems
+
+.. autosummary::
+ :toctree: generated/
+
+ bifacial.power_mismatch_deline
+
Utility functions for bifacial modeling
.. autosummary::
diff --git a/docs/sphinx/source/whatsnew/v0.11.1.rst b/docs/sphinx/source/whatsnew/v0.11.1.rst
index aa2205bb43..1e839c596c 100644
--- a/docs/sphinx/source/whatsnew/v0.11.1.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.1.rst
@@ -10,6 +10,9 @@ Deprecations
Enhancements
~~~~~~~~~~~~
+* Add new losses function that accounts for non-uniform irradiance on bifacial
+ modules, :py:func:`pvlib.bifacial.power_mismatch_deline`.
+ (:issue:`2045`, :pull:`2046`)
Bug fixes
@@ -30,4 +33,4 @@ Requirements
Contributors
~~~~~~~~~~~~
-
+* Echedey Luis (:ghuser:`echedey-ls`)
| [
{
"components": [
{
"doc": "Relative Mean Absolute Difference. Output is [Unitless].\nhttps://stackoverflow.com/a/19472336/19371110",
"lines": [
102,
109
],
"name": "rmad",
"signature": "def rmad(data, axis=None):",
"type": "function"
... | [
"pvlib/tests/bifacial/test_losses_models.py::test_power_mismatch_deline"
] | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
NREL non-uniform irradiance mismatch loss for bifacial modules
- [x] Closes #1541
- [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.
Adds the model described in #1541, also in #2045, [NREL source](https://research-hub.nrel.gov/en/publications/bifacial-pv-system-mismatch-loss-estimation-and-parameterization-).
### Doc links
* https://pvlib-python--2046.org.readthedocs.build/en/2046/reference/generated/pvlib.bifacial.power_mismatch_deline.html
* https://pvlib-python--2046.org.readthedocs.build/en/2046/gallery/bifacial/plot_irradiance_nonuniformity_loss.html
* https://pvlib-python--2046.org.readthedocs.build/en/2046/reference/bifacial.html
----------
</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 docs/examples/bifacial/plot_irradiance_nonuniformity_loss.py]
(definition of rmad:)
def rmad(data, axis=None):
"""Relative Mean Absolute Difference. Output is [Unitless].
https://stackoverflow.com/a/19472336/19371110"""
[end of new definitions in docs/examples/bifacial/plot_irradiance_nonuniformity_loss.py]
[start of new definitions in pvlib/bifacial/loss_models.py]
(definition of power_mismatch_deline:)
def power_mismatch_deline( rmad, coefficients=(0, 0.142, 0.032 * 100), fill_factor: float = None, fill_factor_reference: float = 0.79, ):
"""Estimate DC power loss due to irradiance non-uniformity.
This model is described for bifacial modules in [1]_, where the backside
irradiance is less uniform due to mounting and site conditions.
The power loss is estimated by a polynomial model of the Relative Mean
Absolute Difference (RMAD) of the cell-by-cell total irradiance.
Use ``fill_factor`` to account for different fill factors between the
data used to fit the model and the module of interest. Specify the model's fill factor with
``fill_factor_reference``.
.. versionadded:: 0.11.1
Parameters
----------
rmad : numeric
The Relative Mean Absolute Difference of the cell-by-cell total
irradiance. [Unitless]
See the *Notes* section for the equation to calculate ``rmad`` from the
bifaciality and the front and back irradiances.
coefficients : float collection or numpy.polynomial.polynomial.Polynomial, default ``(0, 0.142, 0.032 * 100)``
The polynomial coefficients to use.
If a :external:class:`numpy.polynomial.polynomial.Polynomial`,
it is evaluated as is. If not a ``Polynomial``, it must be the
coefficients of a polynomial in ``rmad``, where the first element is
the constant term and the last element is the highest order term. A
:external:class:`~numpy.polynomial.polynomial.Polynomial`
will be created internally.
fill_factor : float, optional
Fill factor at standard test condition (STC) of the module.
Accounts for different fill factors between the trained model and the
module under non-uniform irradiance.
If not provided, the default ``fill_factor_reference`` of 0.79 is used.
fill_factor_reference : float, default 0.79
Fill factor at STC of the module used to train the model.
Returns
-------
loss : numeric
The fractional power loss. [Unitless]
Output will be a ``pandas.Series`` if ``rmad`` is a ``pandas.Series``.
Notes
-----
The default model implemented is equation (11) [1]_:
.. math::
M[\%] &= 0.142 \Delta[\%] + 0.032 \Delta^2[\%] \qquad \text{(11)}
M[-] &= 0.142 \Delta[-] + 0.032 \times 100 \Delta^2[-]
where the upper equation is in percentage (same as paper) and the lower
one is unitless. The implementation uses the unitless version, where
:math:`M[-]` is the mismatch power loss [unitless] and
:math:`\Delta[-]` is the Relative Mean Absolute Difference [unitless]
of the global irradiance, Eq. (4) of [1]_ and [2]_.
Note that the n-th power coefficient is multiplied by :math:`100^{n-1}`
to convert the percentage to unitless.
The losses definition is Eq. (1) of [1]_, and it's defined as a loss of the
output power:
.. math::
M = 1 - \frac{P_{Array}}{\sum P_{Cells}} \qquad \text{(1)}
To account for a module with a fill factor distinct from the one used to
train the model (``0.79`` by default), the output of the model can be
modified with Eq. (7):
.. math::
M_{FF_1} = M_{FF_0} \frac{FF_1}{FF_0} \qquad \text{(7)}
where parameter ``fill_factor`` is :math:`FF_1` and
``fill_factor_reference`` is :math:`FF_0`.
In the section *See Also*, you will find two packages that can be used to
calculate the irradiance at different points of the module.
.. note::
The global irradiance RMAD is different from the backside irradiance
RMAD.
In case the RMAD of the backside irradiance is known, the global RMAD can
be calculated as follows, assuming the front irradiance RMAD is
negligible [2]_:
.. math::
RMAD(k \cdot X + c) = RMAD(X) \cdot k \frac{k \bar{X}}{k \bar{X} + c}
= RMAD(X) \cdot \frac{k}{1 + \frac{c}{k \bar{X}}}
by similarity with equation (2) of [1]_:
.. math::
G_{total\,i} = G_{front\,i} + \phi_{Bifi} G_{rear\,i} \qquad \text{(2)}
which yields:
.. math::
RMAD_{total} = RMAD_{rear} \frac{\phi_{Bifi}}
{1 + \frac{G_{front}}{\phi_{Bifi} \bar{G}_{rear}}}
See Also
--------
`solarfactors <https://github.com/pvlib/solarfactors/>`_
Calculate the irradiance at different points of the module.
`bifacial_radiance <https://github.com/NREL/bifacial_radiance>`_
Calculate the irradiance at different points of the module.
References
----------
.. [1] C. Deline, S. Ayala Pelaez, S. MacAlpine, and C. Olalla, 'Estimating
and parameterizing mismatch power loss in bifacial photovoltaic
systems', Progress in Photovoltaics: Research and Applications, vol. 28,
no. 7, pp. 691-703, 2020, :doi:`10.1002/pip.3259`.
.. [2] “Mean absolute difference,” Wikipedia, Sep. 05, 2023.
https://en.wikipedia.org/wiki/Mean_absolute_difference#Relative_mean_absolute_difference
(accessed 2024-04-14)."""
[end of new definitions in pvlib/bifacial/loss_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>> | Here is the discussion in the issues of the pull request.
<issues>
Reduced order electrical mismatch model
**Is your feature request related to a problem? Please describe.**
Electrical mismatch loss due to cell-to-cell irradiance nonuniformity is relevant for bifacial system performance, but pvlib does not offer any tools to model this. PVMismatch can, but maybe I don't want to learn a new tool, maybe I don't have 2-diode model parameters, maybe I don't want another dependency, maybe I just want a quick mismatch estimate without the computational burden of a full I-V circuit solver...
**Describe the solution you'd like**
One of the many feature requests suggested at PVPMC (thanks @shirubana!) is an implementation of the reduced order electrical mismatch model described in [Deline, Pelaez et al 2020, "Estimating and parameterizing mismatch power loss in bifacial photovoltaic systems"](https://doi.org/10.1002/pip.3259).
The model itself is straightforward: given irradiance at several locations across a module, summarize the irradiance variation using mean absolute difference and feed that into a polynomial with known coefficients. What might be more difficult is deciding what the structure of the inputs should be, as we don't currently have a data structure convention for representing multiple irradiance values for a single module. It must be at least 2D (time, location in module), but maybe 3D would be better to allow vectorization across modules.
**Describe alternatives you've considered**
Of course a full I-V curve circuit simulator is still desirable in the long run, but this model is a lot simpler both to implement and to use. No reason not to have both IMHO.
**Additional context**
- `pvfactors` will give you localized/partitioned irradiance going up the row height if you ask it nicely; perhaps we should add a gallery example demonstrating how to do that. I don't think the infinite sheds code can return irradiance for small parts of the module, can it?
- `bifacial_radiance` already has a BSD-3 implementation we could use as a starting point:
https://github.com/NREL/bifacial_radiance/blob/5f9de36861ec9bcffe169c9a4371806860c0e224/bifacial_radiance/mismatch.py#L166-L220
----------
There's also a pytest for half of it.
[https://github.com/NREL/bifacial_radiance/blob/main/tests/test_mismatch.py#L51-L63
](https://github.com/NREL/bifacial_radiance/blob/main/tests/test_mismatch.py#L51-L63
)
Which module do you envision this function to live?
pvsystem.py for this simple model, I think. Code for detailed mismatch calculations would go into singlediode or ivtools.
--------------------
</issues> | 6af80da35a7c96059c534ee38be9123bcfc7f50f |
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/c... | [
"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/t... | 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 | ||
deepset-ai__haystack-7663 | 7,663 | deepset-ai/haystack | null | 6d27de0b406a586a2376031246f9f10eaa452888 | 2024-05-07T16:38:08Z | diff --git a/haystack/components/builders/chat_prompt_builder.py b/haystack/components/builders/chat_prompt_builder.py
new file mode 100644
index 0000000000..b49509d9c9
--- /dev/null
+++ b/haystack/components/builders/chat_prompt_builder.py
@@ -0,0 +1,223 @@
+# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
+#
+# SPDX-License-Identifier: Apache-2.0
+
+from typing import Any, Dict, List, Optional, Set
+
+from jinja2 import Template, meta
+
+from haystack import component, logging
+from haystack.dataclasses.chat_message import ChatMessage, ChatRole
+
+logger = logging.getLogger(__name__)
+
+
+@component
+class ChatPromptBuilder:
+ """
+ ChatPromptBuilder is a component that renders a chat prompt from a template string using Jinja2 templates.
+
+ It is designed to construct prompts for the pipeline using static or dynamic templates: Users can change
+ the prompt template at runtime by providing a new template for each pipeline run invocation if needed.
+
+ The template variables found in the init template string are used as input types for the component and are all optional,
+ unless explicitly specified. If an optional template variable is not provided as an input, it will be replaced with
+ an empty string in the rendered prompt. Use `variable` and `required_variables` to specify the input types and
+ required variables.
+
+ Usage example with static prompt template:
+ ```python
+ template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")]
+ builder = ChatPromptBuilder(template=template)
+ builder.run(target_language="spanish", snippet="I can't speak spanish.")
+ ```
+
+ Usage example of overriding the static template at runtime:
+ ```python
+ template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")]
+ builder = ChatPromptBuilder(template=template)
+ builder.run(target_language="spanish", snippet="I can't speak spanish.")
+
+ summary_template = [ChatMessage.from_user("Translate to {{ target_language }} and summarize. Context: {{ snippet }}; Summary:")]
+ builder.run(target_language="spanish", snippet="I can't speak spanish.", template=summary_template)
+ ```
+
+ Usage example with dynamic prompt template:
+ ```python
+ from haystack.components.builders import ChatPromptBuilder
+ from haystack.components.generators.chat import OpenAIChatGenerator
+ from haystack.dataclasses import ChatMessage
+ from haystack import Pipeline
+ from haystack.utils import Secret
+
+ # no parameter init, we don't use any runtime template variables
+ prompt_builder = ChatPromptBuilder()
+ llm = OpenAIChatGenerator(api_key=Secret.from_token("<your-api-key>"), model="gpt-3.5-turbo")
+
+ pipe = Pipeline()
+ pipe.add_component("prompt_builder", prompt_builder)
+ pipe.add_component("llm", llm)
+ pipe.connect("prompt_builder.prompt", "llm.messages")
+
+ location = "Berlin"
+ language = "English"
+ system_message = ChatMessage.from_system("You are an assistant giving information to tourists in {{language}}")
+ messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")]
+
+ res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "language": language},
+ "template": messages}})
+ print(res)
+
+ >> {'llm': {'replies': [ChatMessage(content="Berlin is the capital city of Germany and one of the most vibrant
+ and diverse cities in Europe. Here are some key things to know...Enjoy your time exploring the vibrant and dynamic
+ capital of Germany!", role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'gpt-3.5-turbo-0613',
+ 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 27, 'completion_tokens': 681, 'total_tokens':
+ 708}})]}}
+
+
+ messages = [system_message, ChatMessage.from_user("What's the weather forecast for {{location}} in the next
+ {{day_count}} days?")]
+
+ res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "day_count": "5"},
+ "template": messages}})
+
+ print(res)
+ >> {'llm': {'replies': [ChatMessage(content="Here is the weather forecast for Berlin in the next 5
+ days:\n\nDay 1: Mostly cloudy with a high of 22°C (72°F) and...so it's always a good idea to check for updates
+ closer to your visit.", role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'gpt-3.5-turbo-0613',
+ 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 37, 'completion_tokens': 201,
+ 'total_tokens': 238}})]}}
+ ```
+
+ Note how in the example above, we can dynamically change the prompt template by providing a new template to the
+ run method of the pipeline.
+
+ """
+
+ def __init__(
+ self,
+ template: Optional[List[ChatMessage]] = None,
+ required_variables: Optional[List[str]] = None,
+ variables: Optional[List[str]] = None,
+ ):
+ """
+ Constructs a ChatPromptBuilder component.
+
+ :param template:
+ A list of `ChatMessage` instances. All user and system messages are treated as potentially having jinja2
+ templates and are rendered with the provided template variables. If not provided, the template
+ must be provided at runtime using the `template` parameter of the `run` method.
+ :param required_variables: An optional list of input variables that must be provided at all times.
+ If not provided, an exception will be raised.
+ :param variables:
+ A list of template variable names you can use in prompt construction. For example,
+ if `variables` contains the string `documents`, the component will create an input called
+ `documents` of type `Any`. These variable names are used to resolve variables and their values during
+ pipeline execution. The values associated with variables from the pipeline runtime are then injected into
+ template placeholders of a prompt text template that is provided to the `run` method.
+ If not provided, variables are inferred from `template`.
+ """
+ self._variables = variables
+ self._required_variables = required_variables
+ self.required_variables = required_variables or []
+ self.template = template
+ variables = variables or []
+ if template and not variables:
+ for message in template:
+ if message.is_from(ChatRole.USER) or message.is_from(ChatRole.SYSTEM):
+ # infere variables from template
+ msg_template = Template(message.content)
+ ast = msg_template.environment.parse(message.content)
+ template_variables = meta.find_undeclared_variables(ast)
+ variables += list(template_variables)
+
+ # setup inputs
+ static_input_slots = {"template": Optional[str], "template_variables": Optional[Dict[str, Any]]}
+ component.set_input_types(self, **static_input_slots)
+ for var in variables:
+ if var in self.required_variables:
+ component.set_input_type(self, var, Any)
+ else:
+ component.set_input_type(self, var, Any, "")
+
+ @component.output_types(prompt=List[ChatMessage])
+ def run(
+ self,
+ template: Optional[List[ChatMessage]] = None,
+ template_variables: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """
+ Executes the prompt building process.
+
+ It applies the template variables to render the final prompt. You can provide variables either via pipeline
+ (set through `variables` or inferred from `template` at initialization) or via additional template variables
+ set directly to this method. On collision, the variables provided directly to this method take precedence.
+
+ :param template:
+ An optional list of ChatMessages to overwrite ChatPromptBuilder's default template. If None, the default template
+ provided at initialization is used.
+ :param template_variables:
+ An optional dictionary of template variables. These are additional variables users can provide directly
+ to this method in contrast to pipeline variables.
+ :param kwargs:
+ Pipeline variables (typically resolved from a pipeline) which are merged with the provided template variables.
+
+ :returns: A dictionary with the following keys:
+ - `prompt`: The updated list of `ChatMessage` instances after rendering the found templates.
+ :raises ValueError:
+ If `chat_messages` is empty or contains elements that are not instances of `ChatMessage`.
+ """
+ kwargs = kwargs or {}
+ template_variables = template_variables or {}
+ template_variables_combined = {**kwargs, **template_variables}
+
+ if template is None:
+ template = self.template
+
+ if not template:
+ raise ValueError(
+ f"The {self.__class__.__name__} requires a non-empty list of ChatMessage instances. "
+ f"Please provide a valid list of ChatMessage instances to render the prompt."
+ )
+
+ if not all(isinstance(message, ChatMessage) for message in template):
+ raise ValueError(
+ f"The {self.__class__.__name__} expects a list containing only ChatMessage instances. "
+ f"The provided list contains other types. Please ensure that all elements in the list "
+ f"are ChatMessage instances."
+ )
+
+ processed_messages = []
+ for message in template:
+ if message.is_from(ChatRole.USER) or message.is_from(ChatRole.SYSTEM):
+ self._validate_variables(set(template_variables_combined.keys()))
+ compiled_template = Template(message.content)
+ rendered_content = compiled_template.render(template_variables_combined)
+ rendered_message = (
+ ChatMessage.from_user(rendered_content)
+ if message.is_from(ChatRole.USER)
+ else ChatMessage.from_system(rendered_content)
+ )
+ processed_messages.append(rendered_message)
+ else:
+ processed_messages.append(message)
+
+ return {"prompt": processed_messages}
+
+ def _validate_variables(self, provided_variables: Set[str]):
+ """
+ Checks if all the required template variables are provided.
+
+ :param provided_variables:
+ A set of provided template variables.
+ :raises ValueError:
+ If no template is provided or if all the required template variables are not provided.
+ """
+ missing_variables = [var for var in self.required_variables if var not in provided_variables]
+ if missing_variables:
+ missing_vars_str = ", ".join(missing_variables)
+ raise ValueError(
+ f"Missing required input variables in ChatPromptBuilder: {missing_vars_str}. "
+ f"Required variables: {self.required_variables}. Provided variables: {provided_variables}."
+ )
diff --git a/haystack/components/builders/dynamic_chat_prompt_builder.py b/haystack/components/builders/dynamic_chat_prompt_builder.py
index 719e2d8c72..a6cd2413b5 100644
--- a/haystack/components/builders/dynamic_chat_prompt_builder.py
+++ b/haystack/components/builders/dynamic_chat_prompt_builder.py
@@ -2,6 +2,7 @@
#
# SPDX-License-Identifier: Apache-2.0
+import warnings
from typing import Any, Dict, List, Optional, Set
from jinja2 import Template, meta
@@ -84,6 +85,11 @@ def __init__(self, runtime_variables: Optional[List[str]] = None):
pipeline execution. The values associated with variables from the pipeline runtime are then injected into
template placeholders of a ChatMessage that is provided to the `run` method.
"""
+ warnings.warn(
+ "`DynamicChatPromptBuilder` is deprecated and will be removed in Haystack 2.3.0."
+ "Use `ChatPromptBuilder` instead.",
+ DeprecationWarning,
+ )
runtime_variables = runtime_variables or []
# setup inputs
diff --git a/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml b/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml
new file mode 100644
index 0000000000..8d80cb47d1
--- /dev/null
+++ b/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml
@@ -0,0 +1,7 @@
+---
+enhancements:
+ - |
+ `ChatPromptBuilder` now supports changing its template at runtime. This allows you to define a default template and then change it based on your needs at runtime.
+deprecations:
+ - |
+ `DynamicChatPromptBuilder` has been deprecated as `ChatPromptBuilder` fully covers its functionality. Use `ChatPromptBuilder` instead.
| diff --git a/test/components/builders/test_chat_prompt_builder.py b/test/components/builders/test_chat_prompt_builder.py
new file mode 100644
index 0000000000..406e40b739
--- /dev/null
+++ b/test/components/builders/test_chat_prompt_builder.py
@@ -0,0 +1,496 @@
+from typing import Any, Dict, List, Optional
+from jinja2 import TemplateSyntaxError
+import pytest
+
+from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder
+from haystack import component
+from haystack.core.pipeline.pipeline import Pipeline
+from haystack.dataclasses.chat_message import ChatMessage
+from haystack.dataclasses.document import Document
+
+
+class TestChatPromptBuilder:
+ def test_init(self):
+ builder = ChatPromptBuilder(
+ template=[
+ ChatMessage.from_user(content="This is a {{ variable }}"),
+ ChatMessage.from_system(content="This is a {{ variable2 }}"),
+ ]
+ )
+ assert builder.required_variables == []
+ assert builder.template[0].content == "This is a {{ variable }}"
+ assert builder.template[1].content == "This is a {{ variable2 }}"
+ assert builder._variables is None
+ assert builder._required_variables is None
+
+ # we have inputs that contain: template, template_variables + inferred variables
+ inputs = builder.__haystack_input__._sockets_dict
+ assert set(inputs.keys()) == {"template", "template_variables", "variable", "variable2"}
+ assert inputs["template"].type == Optional[List[ChatMessage]]
+ assert inputs["template_variables"].type == Optional[Dict[str, Any]]
+ assert inputs["variable"].type == Any
+ assert inputs["variable2"].type == Any
+
+ # response is always prompt
+ outputs = builder.__haystack_output__._sockets_dict
+ assert set(outputs.keys()) == {"prompt"}
+ assert outputs["prompt"].type == List[ChatMessage]
+
+ def test_init_without_template(self):
+ variables = ["var1", "var2"]
+ builder = ChatPromptBuilder(variables=variables)
+ assert builder.template is None
+ assert builder.required_variables == []
+ assert builder._variables == variables
+ assert builder._required_variables is None
+
+ # we have inputs that contain: template, template_variables + variables
+ inputs = builder.__haystack_input__._sockets_dict
+ assert set(inputs.keys()) == {"template", "template_variables", "var1", "var2"}
+ assert inputs["template"].type == Optional[List[ChatMessage]]
+ assert inputs["template_variables"].type == Optional[Dict[str, Any]]
+ assert inputs["var1"].type == Any
+ assert inputs["var2"].type == Any
+
+ # response is always prompt
+ outputs = builder.__haystack_output__._sockets_dict
+ assert set(outputs.keys()) == {"prompt"}
+ assert outputs["prompt"].type == List[ChatMessage]
+
+ def test_init_with_required_variables(self):
+ builder = ChatPromptBuilder(
+ template=[ChatMessage.from_user("This is a {{ variable }}")], required_variables=["variable"]
+ )
+ assert builder.required_variables == ["variable"]
+ assert builder.template[0].content == "This is a {{ variable }}"
+ assert builder._variables is None
+ assert builder._required_variables == ["variable"]
+
+ # we have inputs that contain: template, template_variables + inferred variables
+ inputs = builder.__haystack_input__._sockets_dict
+ assert set(inputs.keys()) == {"template", "template_variables", "variable"}
+ assert inputs["template"].type == Optional[List[ChatMessage]]
+ assert inputs["template_variables"].type == Optional[Dict[str, Any]]
+ assert inputs["variable"].type == Any
+
+ # response is always prompt
+ outputs = builder.__haystack_output__._sockets_dict
+ assert set(outputs.keys()) == {"prompt"}
+ assert outputs["prompt"].type == List[ChatMessage]
+
+ def test_init_with_custom_variables(self):
+ variables = ["var1", "var2", "var3"]
+ template = [ChatMessage.from_user("Hello, {{ var1 }}, {{ var2 }}!")]
+ builder = ChatPromptBuilder(template=template, variables=variables)
+ assert builder.required_variables == []
+ assert builder._variables == variables
+ assert builder.template[0].content == "Hello, {{ var1 }}, {{ var2 }}!"
+ assert builder._required_variables is None
+
+ # we have inputs that contain: template, template_variables + variables
+ inputs = builder.__haystack_input__._sockets_dict
+ assert set(inputs.keys()) == {"template", "template_variables", "var1", "var2", "var3"}
+ assert inputs["template"].type == Optional[List[ChatMessage]]
+ assert inputs["template_variables"].type == Optional[Dict[str, Any]]
+ assert inputs["var1"].type == Any
+ assert inputs["var2"].type == Any
+ assert inputs["var3"].type == Any
+
+ # response is always prompt
+ outputs = builder.__haystack_output__._sockets_dict
+ assert set(outputs.keys()) == {"prompt"}
+ assert outputs["prompt"].type == List[ChatMessage]
+
+ def test_run(self):
+ builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")])
+ res = builder.run(variable="test")
+ assert res == {"prompt": [ChatMessage.from_user("This is a test")]}
+
+ def test_run_template_variable(self):
+ builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")])
+ res = builder.run(template_variables={"variable": "test"})
+ assert res == {"prompt": [ChatMessage.from_user("This is a test")]}
+
+ def test_run_template_variable_overrides_variable(self):
+ builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")])
+ res = builder.run(template_variables={"variable": "test_from_template_var"}, variable="test")
+ assert res == {"prompt": [ChatMessage.from_user("This is a test_from_template_var")]}
+
+ def test_run_without_input(self):
+ builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a template without input")])
+ res = builder.run()
+ assert res == {"prompt": [ChatMessage.from_user("This is a template without input")]}
+
+ def test_run_with_missing_input(self):
+ builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")])
+ res = builder.run()
+ assert res == {"prompt": [ChatMessage.from_user("This is a ")]}
+
+ def test_run_with_missing_required_input(self):
+ builder = ChatPromptBuilder(
+ template=[ChatMessage.from_user("This is a {{ foo }}, not a {{ bar }}")], required_variables=["foo", "bar"]
+ )
+ with pytest.raises(ValueError, match="foo"):
+ builder.run(bar="bar")
+ with pytest.raises(ValueError, match="bar"):
+ builder.run(foo="foo")
+ with pytest.raises(ValueError, match="foo, bar"):
+ builder.run()
+
+ def test_run_with_variables(self):
+ variables = ["var1", "var2", "var3"]
+ template = [ChatMessage.from_user("Hello, {{ name }}! {{ var1 }}")]
+
+ builder = ChatPromptBuilder(template=template, variables=variables)
+
+ template_variables = {"name": "John"}
+ expected_result = {"prompt": [ChatMessage.from_user("Hello, John! How are you?")]}
+
+ assert builder.run(template_variables=template_variables, var1="How are you?") == expected_result
+
+ def test_run_with_variables_and_runtime_template(self):
+ variables = ["var1", "var2", "var3"]
+
+ builder = ChatPromptBuilder(variables=variables)
+
+ template = [ChatMessage.from_user("Hello, {{ name }}! {{ var1 }}")]
+ template_variables = {"name": "John"}
+ expected_result = {"prompt": [ChatMessage.from_user("Hello, John! How are you?")]}
+
+ assert (
+ builder.run(template=template, template_variables=template_variables, var1="How are you?")
+ == expected_result
+ )
+
+ def test_run_overwriting_default_template(self):
+ default_template = [ChatMessage.from_user("Hello, {{ name }}!")]
+
+ builder = ChatPromptBuilder(template=default_template)
+
+ template = [ChatMessage.from_user("Hello, {{ var1 }}{{ name }}!")]
+ expected_result = {"prompt": [ChatMessage.from_user("Hello, John!")]}
+
+ assert builder.run(template, name="John") == expected_result
+
+ def test_run_overwriting_default_template_with_template_variables(self):
+ default_template = [ChatMessage.from_user("Hello, {{ name }}!")]
+
+ builder = ChatPromptBuilder(template=default_template)
+
+ template = [ChatMessage.from_user("Hello, {{ var1 }} {{ name }}!")]
+ template_variables = {"var1": "Big"}
+ expected_result = {"prompt": [ChatMessage.from_user("Hello, Big John!")]}
+
+ assert builder.run(template, template_variables, name="John") == expected_result
+
+ def test_run_overwriting_default_template_with_variables(self):
+ variables = ["var1", "var2", "name"]
+ default_template = [ChatMessage.from_user("Hello, {{ name }}!")]
+
+ builder = ChatPromptBuilder(template=default_template, variables=variables)
+
+ template = [ChatMessage.from_user("Hello, {{ var1 }} {{ name }}!")]
+ expected_result = {"prompt": [ChatMessage.from_user("Hello, Big John!")]}
+
+ assert builder.run(template, name="John", var1="Big") == expected_result
+
+ def test_run_with_invalid_template(self):
+ builder = ChatPromptBuilder()
+
+ template = [ChatMessage.from_user("Hello, {{ name }!")]
+ template_variables = {"name": "John"}
+ with pytest.raises(TemplateSyntaxError):
+ builder.run(template, template_variables)
+
+ def test_init_with_invalid_template(self):
+ template = [ChatMessage.from_user("Hello, {{ name }!")]
+ with pytest.raises(TemplateSyntaxError):
+ ChatPromptBuilder(template)
+
+ def test_run_without_template(self):
+ prompt_builder = ChatPromptBuilder()
+ with pytest.raises(
+ ValueError, match="The ChatPromptBuilder requires a non-empty list of ChatMessage instances"
+ ):
+ prompt_builder.run()
+
+ def test_run_with_empty_chat_message_list(self):
+ prompt_builder = ChatPromptBuilder(template=[], variables=["documents"])
+ with pytest.raises(
+ ValueError, match="The ChatPromptBuilder requires a non-empty list of ChatMessage instances"
+ ):
+ prompt_builder.run()
+
+ def test_chat_message_list_with_mixed_object_list(self):
+ prompt_builder = ChatPromptBuilder(
+ template=[ChatMessage.from_user("Hello"), "there world"], variables=["documents"]
+ )
+ with pytest.raises(
+ ValueError, match="The ChatPromptBuilder expects a list containing only ChatMessage instances"
+ ):
+ prompt_builder.run()
+
+ def test_provided_template_variables(self):
+ prompt_builder = ChatPromptBuilder(variables=["documents"], required_variables=["city"])
+
+ # both variables are provided
+ prompt_builder._validate_variables({"name", "city"})
+
+ # provided variables are a superset of the required variables
+ prompt_builder._validate_variables({"name", "city", "age"})
+
+ with pytest.raises(ValueError):
+ prompt_builder._validate_variables({"name"})
+
+ def test_example_in_pipeline(self):
+ default_template = [
+ ChatMessage.from_user("Here is the document: {{documents[0].content}} \\n Answer: {{query}}")
+ ]
+ prompt_builder = ChatPromptBuilder(template=default_template, variables=["documents"])
+
+ @component
+ class DocumentProducer:
+ @component.output_types(documents=List[Document])
+ def run(self, doc_input: str):
+ return {"documents": [Document(content=doc_input)]}
+
+ pipe = Pipeline()
+ pipe.add_component("doc_producer", DocumentProducer())
+ pipe.add_component("prompt_builder", prompt_builder)
+ pipe.connect("doc_producer.documents", "prompt_builder.documents")
+
+ template = [ChatMessage.from_user("Here is the document: {{documents[0].content}} \n Query: {{query}}")]
+ result = pipe.run(
+ data={
+ "doc_producer": {"doc_input": "Hello world, I live in Berlin"},
+ "prompt_builder": {
+ "template": template,
+ "template_variables": {"query": "Where does the speaker live?"},
+ },
+ }
+ )
+
+ assert result == {
+ "prompt_builder": {
+ "prompt": [
+ ChatMessage.from_user(
+ "Here is the document: Hello world, I live in Berlin \n Query: Where does the speaker live?"
+ )
+ ]
+ }
+ }
+
+ def test_example_in_pipeline_simple(self):
+ default_template = [ChatMessage.from_user("This is the default prompt:\n Query: {{query}}")]
+ prompt_builder = ChatPromptBuilder(template=default_template)
+
+ pipe = Pipeline()
+ pipe.add_component("prompt_builder", prompt_builder)
+
+ # using the default prompt
+ result = pipe.run(data={"query": "Where does the speaker live?"})
+ expected_default = {
+ "prompt_builder": {
+ "prompt": [ChatMessage.from_user("This is the default prompt:\n Query: Where does the speaker live?")]
+ }
+ }
+ assert result == expected_default
+
+ # using the dynamic prompt
+ result = pipe.run(
+ data={
+ "query": "Where does the speaker live?",
+ "template": [ChatMessage.from_user("This is the dynamic prompt:\n Query: {{query}}")],
+ }
+ )
+ expected_dynamic = {
+ "prompt_builder": {
+ "prompt": [ChatMessage.from_user("This is the dynamic prompt:\n Query: Where does the speaker live?")]
+ }
+ }
+ assert result == expected_dynamic
+
+
+class TestChatPromptBuilderDynamic:
+ def test_multiple_templated_chat_messages(self):
+ prompt_builder = ChatPromptBuilder()
+ language = "French"
+ location = "Berlin"
+ messages = [
+ ChatMessage.from_system("Write your response in this language:{{language}}"),
+ ChatMessage.from_user("Tell me about {{location}}"),
+ ]
+
+ result = prompt_builder.run(template_variables={"language": language, "location": location}, template=messages)
+ assert result["prompt"] == [
+ ChatMessage.from_system("Write your response in this language:French"),
+ ChatMessage.from_user("Tell me about Berlin"),
+ ], "The templated messages should match the expected output."
+
+ def test_multiple_templated_chat_messages_in_place(self):
+ prompt_builder = ChatPromptBuilder()
+ language = "French"
+ location = "Berlin"
+ messages = [
+ ChatMessage.from_system("Write your response ins this language:{{language}}"),
+ ChatMessage.from_user("Tell me about {{location}}"),
+ ]
+
+ res = prompt_builder.run(template_variables={"language": language, "location": location}, template=messages)
+ assert res == {
+ "prompt": [
+ ChatMessage.from_system("Write your response ins this language:French"),
+ ChatMessage.from_user("Tell me about Berlin"),
+ ]
+ }, "The templated messages should match the expected output."
+
+ def test_some_templated_chat_messages(self):
+ prompt_builder = ChatPromptBuilder()
+ language = "English"
+ location = "Paris"
+ messages = [
+ ChatMessage.from_system("Please, respond in the following language: {{language}}."),
+ ChatMessage.from_user("I would like to learn more about {{location}}."),
+ ChatMessage.from_assistant("Yes, I can help you with that {{subject}}"),
+ ChatMessage.from_user("Ok so do so please, be elaborate."),
+ ]
+
+ result = prompt_builder.run(template_variables={"language": language, "location": location}, template=messages)
+
+ expected_messages = [
+ ChatMessage.from_system("Please, respond in the following language: English."),
+ ChatMessage.from_user("I would like to learn more about Paris."),
+ ChatMessage.from_assistant(
+ "Yes, I can help you with that {{subject}}"
+ ), # assistant message should not be templated
+ ChatMessage.from_user("Ok so do so please, be elaborate."),
+ ]
+
+ assert result["prompt"] == expected_messages, "The templated messages should match the expected output."
+
+ def test_example_in_pipeline(self):
+ prompt_builder = ChatPromptBuilder()
+
+ pipe = Pipeline()
+ pipe.add_component("prompt_builder", prompt_builder)
+
+ location = "Berlin"
+ system_message = ChatMessage.from_system(
+ "You are a helpful assistant giving out valuable information to tourists."
+ )
+ messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")]
+
+ res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location}, "template": messages}})
+ assert res == {
+ "prompt_builder": {
+ "prompt": [
+ ChatMessage.from_system("You are a helpful assistant giving out valuable information to tourists."),
+ ChatMessage.from_user("Tell me about Berlin"),
+ ]
+ }
+ }
+
+ messages = [
+ system_message,
+ ChatMessage.from_user("What's the weather forecast for {{location}} in the next {{day_count}} days?"),
+ ]
+
+ res = pipe.run(
+ data={
+ "prompt_builder": {"template_variables": {"location": location, "day_count": "5"}, "template": messages}
+ }
+ )
+ assert res == {
+ "prompt_builder": {
+ "prompt": [
+ ChatMessage.from_system("You are a helpful assistant giving out valuable information to tourists."),
+ ChatMessage.from_user("What's the weather forecast for Berlin in the next 5 days?"),
+ ]
+ }
+ }
+
+ def test_example_in_pipeline_with_multiple_templated_messages(self):
+ # no parameter init, we don't use any runtime template variables
+ prompt_builder = ChatPromptBuilder()
+
+ pipe = Pipeline()
+ pipe.add_component("prompt_builder", prompt_builder)
+
+ location = "Berlin"
+ system_message = ChatMessage.from_system(
+ "You are a helpful assistant giving out valuable information to tourists in {{language}}."
+ )
+ messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")]
+
+ res = pipe.run(
+ data={
+ "prompt_builder": {
+ "template_variables": {"location": location, "language": "German"},
+ "template": messages,
+ }
+ }
+ )
+ assert res == {
+ "prompt_builder": {
+ "prompt": [
+ ChatMessage.from_system(
+ "You are a helpful assistant giving out valuable information to tourists in German."
+ ),
+ ChatMessage.from_user("Tell me about Berlin"),
+ ]
+ }
+ }
+
+ messages = [
+ system_message,
+ ChatMessage.from_user("What's the weather forecast for {{location}} in the next {{day_count}} days?"),
+ ]
+
+ res = pipe.run(
+ data={
+ "prompt_builder": {
+ "template_variables": {"location": location, "day_count": "5", "language": "English"},
+ "template": messages,
+ }
+ }
+ )
+ assert res == {
+ "prompt_builder": {
+ "prompt": [
+ ChatMessage.from_system(
+ "You are a helpful assistant giving out valuable information to tourists in English."
+ ),
+ ChatMessage.from_user("What's the weather forecast for Berlin in the next 5 days?"),
+ ]
+ }
+ }
+
+ def test_pipeline_complex(self):
+ @component
+ class ValueProducer:
+ def __init__(self, value_to_produce: str):
+ self.value_to_produce = value_to_produce
+
+ @component.output_types(value_output=str)
+ def run(self):
+ return {"value_output": self.value_to_produce}
+
+ pipe = Pipeline()
+ pipe.add_component("prompt_builder", ChatPromptBuilder(variables=["value_output"]))
+ pipe.add_component("value_producer", ValueProducer(value_to_produce="Berlin"))
+ pipe.connect("value_producer.value_output", "prompt_builder")
+
+ messages = [
+ ChatMessage.from_system("You give valuable information to tourists."),
+ ChatMessage.from_user("Tell me about {{value_output}}"),
+ ]
+
+ res = pipe.run(data={"template": messages})
+ assert res == {
+ "prompt_builder": {
+ "prompt": [
+ ChatMessage.from_system("You give valuable information to tourists."),
+ ChatMessage.from_user("Tell me about Berlin"),
+ ]
+ }
+ }
| diff --git a/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml b/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml
new file mode 100644
index 0000000000..8d80cb47d1
--- /dev/null
+++ b/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml
@@ -0,0 +1,7 @@
+---
+enhancements:
+ - |
+ `ChatPromptBuilder` now supports changing its template at runtime. This allows you to define a default template and then change it based on your needs at runtime.
+deprecations:
+ - |
+ `DynamicChatPromptBuilder` has been deprecated as `ChatPromptBuilder` fully covers its functionality. Use `ChatPromptBuilder` instead.
| [
{
"components": [
{
"doc": " ChatPromptBuilder is a component that renders a chat prompt from a template string using Jinja2 templates.\n\n It is designed to construct prompts for the pipeline using static or dynamic templates: Users can change\n the prompt template at runtime by providin... | [
"test/components/builders/test_chat_prompt_builder.py::TestChatPromptBuilder::test_init",
"test/components/builders/test_chat_prompt_builder.py::TestChatPromptBuilder::test_init_without_template",
"test/components/builders/test_chat_prompt_builder.py::TestChatPromptBuilder::test_init_with_required_variables",
... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
feat: add ChatPromptBuilder, deprecate DynamicChatPromptBuilder
### Related Issues
- follow up from https://github.com/deepset-ai/haystack/pull/7655 regarding `ChatPromptBuilder`
### Proposed Changes:
This extends ChatPromptBuilder to change prompts at query time.
```python
default_template = [ChatMessage.from_user("This is the default prompt: \\n Query: {{query}}")]
prompt_builder = ChatPromptBuilder(template=default_template)
pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
# using the default prompt
result = pipe.run(
data={
"prompt_builder": {
"query": "Where does the speaker live?",
},
}
)
# "This is the default prompt: \n Query: Where does the speaker live?"
# using the dynamic prompt
result = pipe.run(
data={
"prompt_builder": {
"template": [ChatMessage.from_user("This is the dynamic prompt:\\n Query: {{query}}")],
"query": "Where does the speaker live?",
},
}
)
# "This is the dynamic prompt: \n Query: Where does the speaker live?"
```
### How did you test it?
- added tests
### Notes for the reviewer
- There are no breaking changes
- `DynamicChatPromptBuilder` is being deprecated
### 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/builders/chat_prompt_builder.py]
(definition of ChatPromptBuilder:)
class ChatPromptBuilder:
""" ChatPromptBuilder is a component that renders a chat prompt from a template string using Jinja2 templates.
It is designed to construct prompts for the pipeline using static or dynamic templates: Users can change
the prompt template at runtime by providing a new template for each pipeline run invocation if needed.
The template variables found in the init template string are used as input types for the component and are all optional,
unless explicitly specified. If an optional template variable is not provided as an input, it will be replaced with
an empty string in the rendered prompt. Use `variable` and `required_variables` to specify the input types and
required variables.
Usage example with static prompt template:
```python
template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")]
builder = ChatPromptBuilder(template=template)
builder.run(target_language="spanish", snippet="I can't speak spanish.")
```
Usage example of overriding the static template at runtime:
```python
template = [ChatMessage.from_user("Translate to {{ target_language }}. Context: {{ snippet }}; Translation:")]
builder = ChatPromptBuilder(template=template)
builder.run(target_language="spanish", snippet="I can't speak spanish.")
summary_template = [ChatMessage.from_user("Translate to {{ target_language }} and summarize. Context: {{ snippet }}; Summary:")]
builder.run(target_language="spanish", snippet="I can't speak spanish.", template=summary_template)
```
Usage example with dynamic prompt template:
```python
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack import Pipeline
from haystack.utils import Secret
# no parameter init, we don't use any runtime template variables
prompt_builder = ChatPromptBuilder()
llm = OpenAIChatGenerator(api_key=Secret.from_token("<your-api-key>"), model="gpt-3.5-turbo")
pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("llm", llm)
pipe.connect("prompt_builder.prompt", "llm.messages")
location = "Berlin"
language = "English"
system_message = ChatMessage.from_system("You are an assistant giving information to tourists in {{language}}")
messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")]
res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "language": language},
"template": messages}})
print(res)
>> {'llm': {'replies': [ChatMessage(content="Berlin is the capital city of Germany and one of the most vibrant
and diverse cities in Europe. Here are some key things to know...Enjoy your time exploring the vibrant and dynamic
capital of Germany!", role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'gpt-3.5-turbo-0613',
'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 27, 'completion_tokens': 681, 'total_tokens':
708}})]}}
messages = [system_message, ChatMessage.from_user("What's the weather forecast for {{location}} in the next
{{day_count}} days?")]
res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location, "day_count": "5"},
"template": messages}})
print(res)
>> {'llm': {'replies': [ChatMessage(content="Here is the weather forecast for Berlin in the next 5
days:
Day 1: Mostly cloudy with a high of 22°C (72°F) and...so it's always a good idea to check for updates
closer to your visit.", role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'gpt-3.5-turbo-0613',
'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 37, 'completion_tokens': 201,
'total_tokens': 238}})]}}
```
Note how in the example above, we can dynamically change the prompt template by providing a new template to the
run method of the pipeline.
"""
(definition of ChatPromptBuilder.__init__:)
def __init__( self, template: Optional[List[ChatMessage]] = None, required_variables: Optional[List[str]] = None, variables: Optional[List[str]] = None, ):
"""Constructs a ChatPromptBuilder component.
:param template:
A list of `ChatMessage` instances. All user and system messages are treated as potentially having jinja2
templates and are rendered with the provided template variables. If not provided, the template
must be provided at runtime using the `template` parameter of the `run` method.
:param required_variables: An optional list of input variables that must be provided at all times.
If not provided, an exception will be raised.
:param variables:
A list of template variable names you can use in prompt construction. For example,
if `variables` contains the string `documents`, the component will create an input called
`documents` of type `Any`. These variable names are used to resolve variables and their values during
pipeline execution. The values associated with variables from the pipeline runtime are then injected into
template placeholders of a prompt text template that is provided to the `run` method.
If not provided, variables are inferred from `template`."""
(definition of ChatPromptBuilder.run:)
def run( self, template: Optional[List[ChatMessage]] = None, template_variables: Optional[Dict[str, Any]] = None, **kwargs, ):
"""Executes the prompt building process.
It applies the template variables to render the final prompt. You can provide variables either via pipeline
(set through `variables` or inferred from `template` at initialization) or via additional template variables
set directly to this method. On collision, the variables provided directly to this method take precedence.
:param template:
An optional list of ChatMessages to overwrite ChatPromptBuilder's default template. If None, the default template
provided at initialization is used.
:param template_variables:
An optional dictionary of template variables. These are additional variables users can provide directly
to this method in contrast to pipeline variables.
:param kwargs:
Pipeline variables (typically resolved from a pipeline) which are merged with the provided template variables.
:returns: A dictionary with the following keys:
- `prompt`: The updated list of `ChatMessage` instances after rendering the found templates.
:raises ValueError:
If `chat_messages` is empty or contains elements that are not instances of `ChatMessage`."""
(definition of ChatPromptBuilder._validate_variables:)
def _validate_variables(self, provided_variables: Set[str]):
"""Checks if all the required template variables are provided.
:param provided_variables:
A set of provided template variables.
:raises ValueError:
If no template is provided or if all the required template variables are not provided."""
[end of new definitions in haystack/components/builders/chat_prompt_builder.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 | |
pvlib__pvlib-python-2041 | 2,041 | pvlib/pvlib-python | 0.9 | d53f97e984bfdd268aa92f8bf482ced0edda0110 | 2024-05-06T22:25:16Z | diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index 8041d8f49b..fde3b170a9 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -13,3 +13,5 @@ Spectrum
spectrum.spectral_factor_caballero
spectrum.spectral_factor_firstsolar
spectrum.spectral_factor_sapm
+ spectrum.sr_to_qe
+ spectrum.qe_to_sr
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index b5d543bff1..2f056cd3e4 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -19,6 +19,10 @@ Enhancements
shade perpendicular to ``axis_azimuth``. The function is applicable to both
fixed-tilt and one-axis tracking systems.
(:issue:`1689`, :pull:`1725`, :pull:`1962`)
+* Added conversion functions from spectral response ([A/W]) to quantum
+ efficiency ([unitless]) and vice versa. The conversion functions are
+ :py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
+ respectively. (:issue:`2040`, :pull:`2041`)
Bug fixes
@@ -42,3 +46,4 @@ Contributors
* Cliff Hansen (:ghuser:`cwhanse`)
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
+* Mark Campanelli (:ghuser:`markcampanelli`)
diff --git a/pvlib/spectrum/__init__.py b/pvlib/spectrum/__init__.py
index 6c97df978e..0b9f7b03e9 100644
--- a/pvlib/spectrum/__init__.py
+++ b/pvlib/spectrum/__init__.py
@@ -6,4 +6,6 @@
spectral_factor_caballero,
spectral_factor_firstsolar,
spectral_factor_sapm,
+ sr_to_qe,
+ qe_to_sr,
)
diff --git a/pvlib/spectrum/mismatch.py b/pvlib/spectrum/mismatch.py
index 5e00b2472d..e3f434f99c 100644
--- a/pvlib/spectrum/mismatch.py
+++ b/pvlib/spectrum/mismatch.py
@@ -3,15 +3,25 @@
"""
import pvlib
+from pvlib.tools import normalize_max2one
import numpy as np
import pandas as pd
-from scipy.interpolate import interp1d
+import scipy.constants
from scipy.integrate import trapezoid
+from scipy.interpolate import interp1d
import os
from warnings import warn
+_PLANCK_BY_LIGHT_SPEED_OVER_ELEMENTAL_CHARGE_BY_BILLION = (
+ scipy.constants.speed_of_light
+ * scipy.constants.Planck
+ / scipy.constants.elementary_charge
+ * 1e9
+)
+
+
def get_example_spectral_response(wavelength=None):
'''
Generate a generic smooth spectral response (SR) for tests and experiments.
@@ -154,7 +164,7 @@ def calc_spectral_mismatch_field(sr, e_sun, e_ref=None):
e_sun: pandas.DataFrame or pandas.Series
One or more measured solar irradiance spectra in a pandas.DataFrame
- having wavelength in nm as column index. A single spectrum may be
+ having wavelength in nm as column index. A single spectrum may be
be given as a pandas.Series having wavelength in nm as index.
[(W/m^2)/nm]
@@ -571,3 +581,201 @@ def spectral_factor_caballero(precipitable_water, airmass_absolute, aod500,
)
modifier = f_AM + f_AOD + f_PW # Eq 5
return modifier
+
+
+def sr_to_qe(sr, wavelength=None, normalize=False):
+ """
+ Convert spectral responsivities to quantum efficiencies.
+ If ``wavelength`` is not provided, the spectral responsivity ``sr`` must be
+ a :py:class:`pandas.Series` or :py:class:`pandas.DataFrame`, with the
+ wavelengths in the index.
+
+ Provide wavelengths in nanometers, [nm].
+
+ Conversion is described in [1]_.
+
+ .. versionadded:: 0.11.0
+
+ Parameters
+ ----------
+ sr : numeric, pandas.Series or pandas.DataFrame
+ Spectral response, [A/W].
+ Index must be the wavelength in nanometers, [nm].
+
+ wavelength : numeric, optional
+ Points where spectral response is measured, in nanometers, [nm].
+
+ normalize : bool, default False
+ If True, the quantum efficiency is normalized so that the maximum value
+ is 1.
+ For ``pandas.DataFrame``, normalization is done for each column.
+ For 2D arrays, normalization is done for each sub-array.
+
+ Returns
+ -------
+ quantum_efficiency : numeric, same type as ``sr``
+ Quantum efficiency, in the interval [0, 1].
+
+ Notes
+ -----
+ - If ``sr`` is of type ``pandas.Series`` or ``pandas.DataFrame``,
+ column names will remain unchanged in the returned object.
+ - If ``wavelength`` is provided it will be used independently of the
+ datatype of ``sr``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import pandas as pd
+ >>> from pvlib import spectrum
+ >>> wavelengths = np.array([350, 550, 750])
+ >>> spectral_response = np.array([0.25, 0.40, 0.57])
+ >>> quantum_efficiency = spectrum.sr_to_qe(spectral_response, wavelengths)
+ >>> print(quantum_efficiency)
+ array([0.88560142, 0.90170326, 0.94227991])
+
+ >>> spectral_response_series = pd.Series(spectral_response, index=wavelengths, name="dataset")
+ >>> qe = spectrum.sr_to_qe(spectral_response_series)
+ >>> print(qe)
+ 350 0.885601
+ 550 0.901703
+ 750 0.942280
+ Name: dataset, dtype: float64
+
+ >>> qe = spectrum.sr_to_qe(spectral_response_series, normalize=True)
+ >>> print(qe)
+ 350 0.939850
+ 550 0.956938
+ 750 1.000000
+ Name: dataset, dtype: float64
+
+ References
+ ----------
+ .. [1] “Spectral Response,” PV Performance Modeling Collaborative (PVPMC).
+ https://pvpmc.sandia.gov/modeling-guide/2-dc-module-iv/effective-irradiance/spectral-response/
+ .. [2] “Spectral Response | PVEducation,” www.pveducation.org.
+ https://www.pveducation.org/pvcdrom/solar-cell-operation/spectral-response
+
+ See Also
+ --------
+ pvlib.spectrum.qe_to_sr
+ """ # noqa: E501
+ if wavelength is None:
+ if hasattr(sr, "index"): # true for pandas objects
+ # use reference to index values instead of index alone so
+ # sr / wavelength returns a series with the same name
+ wavelength = sr.index.array
+ else:
+ raise TypeError(
+ "'sr' must have an '.index' attribute"
+ + " or 'wavelength' must be provided"
+ )
+ quantum_efficiency = (
+ sr
+ / wavelength
+ * _PLANCK_BY_LIGHT_SPEED_OVER_ELEMENTAL_CHARGE_BY_BILLION
+ )
+
+ if normalize:
+ quantum_efficiency = normalize_max2one(quantum_efficiency)
+
+ return quantum_efficiency
+
+
+def qe_to_sr(qe, wavelength=None, normalize=False):
+ """
+ Convert quantum efficiencies to spectral responsivities.
+ If ``wavelength`` is not provided, the quantum efficiency ``qe`` must be
+ a :py:class:`pandas.Series` or :py:class:`pandas.DataFrame`, with the
+ wavelengths in the index.
+
+ Provide wavelengths in nanometers, [nm].
+
+ Conversion is described in [1]_.
+
+ .. versionadded:: 0.11.0
+
+ Parameters
+ ----------
+ qe : numeric, pandas.Series or pandas.DataFrame
+ Quantum efficiency.
+ If pandas subtype, index must be the wavelength in nanometers, [nm].
+
+ wavelength : numeric, optional
+ Points where quantum efficiency is measured, in nanometers, [nm].
+
+ normalize : bool, default False
+ If True, the spectral response is normalized so that the maximum value
+ is 1.
+ For ``pandas.DataFrame``, normalization is done for each column.
+ For 2D arrays, normalization is done for each sub-array.
+
+ Returns
+ -------
+ spectral_response : numeric, same type as ``qe``
+ Spectral response, [A/W].
+
+ Notes
+ -----
+ - If ``qe`` is of type ``pandas.Series`` or ``pandas.DataFrame``,
+ column names will remain unchanged in the returned object.
+ - If ``wavelength`` is provided it will be used independently of the
+ datatype of ``qe``.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import pandas as pd
+ >>> from pvlib import spectrum
+ >>> wavelengths = np.array([350, 550, 750])
+ >>> quantum_efficiency = np.array([0.86, 0.90, 0.94])
+ >>> spectral_response = spectrum.qe_to_sr(quantum_efficiency, wavelengths)
+ >>> print(spectral_response)
+ array([0.24277287, 0.39924442, 0.56862085])
+
+ >>> quantum_efficiency_series = pd.Series(quantum_efficiency, index=wavelengths, name="dataset")
+ >>> sr = spectrum.qe_to_sr(quantum_efficiency_series)
+ >>> print(sr)
+ 350 0.242773
+ 550 0.399244
+ 750 0.568621
+ Name: dataset, dtype: float64
+
+ >>> sr = spectrum.qe_to_sr(quantum_efficiency_series, normalize=True)
+ >>> print(sr)
+ 350 0.426950
+ 550 0.702128
+ 750 1.000000
+ Name: dataset, dtype: float64
+
+ References
+ ----------
+ .. [1] “Spectral Response,” PV Performance Modeling Collaborative (PVPMC).
+ https://pvpmc.sandia.gov/modeling-guide/2-dc-module-iv/effective-irradiance/spectral-response/
+ .. [2] “Spectral Response | PVEducation,” www.pveducation.org.
+ https://www.pveducation.org/pvcdrom/solar-cell-operation/spectral-response
+
+ See Also
+ --------
+ pvlib.spectrum.sr_to_qe
+ """ # noqa: E501
+ if wavelength is None:
+ if hasattr(qe, "index"): # true for pandas objects
+ # use reference to index values instead of index alone so
+ # sr / wavelength returns a series with the same name
+ wavelength = qe.index.array
+ else:
+ raise TypeError(
+ "'qe' must have an '.index' attribute"
+ + " or 'wavelength' must be provided"
+ )
+ spectral_responsivity = (
+ qe
+ * wavelength
+ / _PLANCK_BY_LIGHT_SPEED_OVER_ELEMENTAL_CHARGE_BY_BILLION
+ )
+
+ if normalize:
+ spectral_responsivity = normalize_max2one(spectral_responsivity)
+
+ return spectral_responsivity
diff --git a/pvlib/tools.py b/pvlib/tools.py
index adf502a79d..3d766b6f72 100644
--- a/pvlib/tools.py
+++ b/pvlib/tools.py
@@ -507,3 +507,30 @@ def get_pandas_index(*args):
(a.index for a in args if isinstance(a, (pd.DataFrame, pd.Series))),
None
)
+
+
+def normalize_max2one(a):
+ r"""
+ Normalize an array so that the largest absolute value is ±1.
+
+ Handles both numpy arrays and pandas objects.
+ On 2D arrays, normalization is row-wise.
+ On pandas DataFrame, normalization is column-wise.
+
+ If all values of row are 0, the array is set to NaNs.
+
+ Parameters
+ ----------
+ a : array-like
+ The array to normalize.
+
+ Returns
+ -------
+ array-like
+ The normalized array.
+ """
+ try: # expect numpy array
+ res = a / np.max(np.absolute(a), axis=-1, keepdims=True)
+ except ValueError: # fails for pandas objects
+ res = a.div(a.abs().max(axis=0, skipna=True))
+ return res
| diff --git a/pvlib/tests/test_spectrum.py b/pvlib/tests/test_spectrum.py
index 793eaacfdf..7b86cb713e 100644
--- a/pvlib/tests/test_spectrum.py
+++ b/pvlib/tests/test_spectrum.py
@@ -140,7 +140,7 @@ def test_get_am15g():
def test_calc_spectral_mismatch_field(spectrl2_data):
# test that the mismatch is calculated correctly with
- # - default and custom reference sepctrum
+ # - default and custom reference spectrum
# - single or multiple sun spectra
# sample data
@@ -315,3 +315,107 @@ def test_spectral_factor_caballero_supplied_ambiguous():
with pytest.raises(ValueError):
spectrum.spectral_factor_caballero(1, 1, 1, module_type=None,
coefficients=None)
+
+
+@pytest.fixture
+def sr_and_eqe_fixture():
+ # Just some arbitrary data for testing the conversion functions
+ df = pd.DataFrame(
+ columns=("wavelength", "quantum_efficiency", "spectral_response"),
+ data=[
+ # nm, [0,1], A/W
+ [300, 0.85, 0.205671370402405],
+ [350, 0.86, 0.242772872514211],
+ [400, 0.87, 0.280680929019753],
+ [450, 0.88, 0.319395539919029],
+ [500, 0.89, 0.358916705212040],
+ [550, 0.90, 0.399244424898786],
+ [600, 0.91, 0.440378698979267],
+ [650, 0.92, 0.482319527453483],
+ [700, 0.93, 0.525066910321434],
+ [750, 0.94, 0.568620847583119],
+ [800, 0.95, 0.612981339238540],
+ [850, 0.90, 0.617014111207215],
+ [900, 0.80, 0.580719163489143],
+ [950, 0.70, 0.536358671833723],
+ [1000, 0.6, 0.483932636240953],
+ [1050, 0.4, 0.338752845368667],
+ ],
+ )
+ df.set_index("wavelength", inplace=True)
+ return df
+
+
+def test_sr_to_qe(sr_and_eqe_fixture):
+ # vector type
+ qe = spectrum.sr_to_qe(
+ sr_and_eqe_fixture["spectral_response"].values,
+ sr_and_eqe_fixture.index.values, # wavelength, nm
+ )
+ assert_allclose(qe, sr_and_eqe_fixture["quantum_efficiency"])
+ # pandas series type
+ # note: output Series' name should match the input
+ qe = spectrum.sr_to_qe(
+ sr_and_eqe_fixture["spectral_response"]
+ )
+ pd.testing.assert_series_equal(
+ qe, sr_and_eqe_fixture["quantum_efficiency"],
+ check_names=False
+ )
+ assert qe.name == "spectral_response"
+ # series normalization
+ qe = spectrum.sr_to_qe(
+ sr_and_eqe_fixture["spectral_response"] * 10, normalize=True
+ )
+ pd.testing.assert_series_equal(
+ qe,
+ sr_and_eqe_fixture["quantum_efficiency"]
+ / max(sr_and_eqe_fixture["quantum_efficiency"]),
+ check_names=False,
+ )
+ # error on lack of wavelength parameter if no pandas object is provided
+ with pytest.raises(TypeError, match="must have an '.index' attribute"):
+ _ = spectrum.sr_to_qe(sr_and_eqe_fixture["spectral_response"].values)
+
+
+def test_qe_to_sr(sr_and_eqe_fixture):
+ # vector type
+ sr = spectrum.qe_to_sr(
+ sr_and_eqe_fixture["quantum_efficiency"].values,
+ sr_and_eqe_fixture.index.values, # wavelength, nm
+ )
+ assert_allclose(sr, sr_and_eqe_fixture["spectral_response"])
+ # pandas series type
+ # note: output Series' name should match the input
+ sr = spectrum.qe_to_sr(
+ sr_and_eqe_fixture["quantum_efficiency"]
+ )
+ pd.testing.assert_series_equal(
+ sr, sr_and_eqe_fixture["spectral_response"],
+ check_names=False
+ )
+ assert sr.name == "quantum_efficiency"
+ # series normalization
+ sr = spectrum.qe_to_sr(
+ sr_and_eqe_fixture["quantum_efficiency"] * 10, normalize=True
+ )
+ pd.testing.assert_series_equal(
+ sr,
+ sr_and_eqe_fixture["spectral_response"]
+ / max(sr_and_eqe_fixture["spectral_response"]),
+ check_names=False,
+ )
+ # error on lack of wavelength parameter if no pandas object is provided
+ with pytest.raises(TypeError, match="must have an '.index' attribute"):
+ _ = spectrum.qe_to_sr(
+ sr_and_eqe_fixture["quantum_efficiency"].values
+ )
+
+
+def test_qe_and_sr_reciprocal_conversion(sr_and_eqe_fixture):
+ # test that the conversion functions are reciprocal
+ qe = spectrum.sr_to_qe(sr_and_eqe_fixture["spectral_response"])
+ sr = spectrum.qe_to_sr(qe)
+ assert_allclose(sr, sr_and_eqe_fixture["spectral_response"])
+ qe = spectrum.sr_to_qe(sr)
+ assert_allclose(qe, sr_and_eqe_fixture["quantum_efficiency"])
diff --git a/pvlib/tests/test_tools.py b/pvlib/tests/test_tools.py
index 583141a726..eb9e65c895 100644
--- a/pvlib/tests/test_tools.py
+++ b/pvlib/tests/test_tools.py
@@ -3,6 +3,7 @@
from pvlib import tools
import numpy as np
import pandas as pd
+from numpy.testing import assert_allclose
@pytest.mark.parametrize('keys, input_dict, expected', [
@@ -120,3 +121,26 @@ def test_get_pandas_index(args, args_idx):
assert index is None
else:
pd.testing.assert_index_equal(args[args_idx].index, index)
+
+
+@pytest.mark.parametrize('data_in,expected', [
+ (np.array([1, 2, 3, 4, 5]),
+ np.array([0.2, 0.4, 0.6, 0.8, 1])),
+ (np.array([[0, 1, 2], [0, 3, 6]]),
+ np.array([[0, 0.5, 1], [0, 0.5, 1]])),
+ (pd.Series([1, 2, 3, 4, 5]),
+ pd.Series([0.2, 0.4, 0.6, 0.8, 1])),
+ (pd.DataFrame({"a": [0, 1, 2], "b": [0, 2, 8]}),
+ pd.DataFrame({"a": [0, 0.5, 1], "b": [0, 0.25, 1]})),
+ # test with NaN and all zeroes
+ (pd.DataFrame({"a": [0, np.nan, 1], "b": [0, 0, 0]}),
+ pd.DataFrame({"a": [0, np.nan, 1], "b": [np.nan]*3})),
+ # test with negative values
+ (np.array([1, 2, -3, 4, -5]),
+ np.array([0.2, 0.4, -0.6, 0.8, -1])),
+ (pd.Series([-2, np.nan, 1]),
+ pd.Series([-1, np.nan, 0.5])),
+])
+def test_normalize_max2one(data_in, expected):
+ result = tools.normalize_max2one(data_in)
+ assert_allclose(result, expected)
| diff --git a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
index 8041d8f49b..fde3b170a9 100644
--- a/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
+++ b/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst
@@ -13,3 +13,5 @@ Spectrum
spectrum.spectral_factor_caballero
spectrum.spectral_factor_firstsolar
spectrum.spectral_factor_sapm
+ spectrum.sr_to_qe
+ spectrum.qe_to_sr
diff --git a/docs/sphinx/source/whatsnew/v0.11.0.rst b/docs/sphinx/source/whatsnew/v0.11.0.rst
index b5d543bff1..2f056cd3e4 100644
--- a/docs/sphinx/source/whatsnew/v0.11.0.rst
+++ b/docs/sphinx/source/whatsnew/v0.11.0.rst
@@ -19,6 +19,10 @@ Enhancements
shade perpendicular to ``axis_azimuth``. The function is applicable to both
fixed-tilt and one-axis tracking systems.
(:issue:`1689`, :pull:`1725`, :pull:`1962`)
+* Added conversion functions from spectral response ([A/W]) to quantum
+ efficiency ([unitless]) and vice versa. The conversion functions are
+ :py:func:`pvlib.spectrum.sr_to_qe` and :py:func:`pvlib.spectrum.qe_to_sr`
+ respectively. (:issue:`2040`, :pull:`2041`)
Bug fixes
@@ -42,3 +46,4 @@ Contributors
* Cliff Hansen (:ghuser:`cwhanse`)
* Mark Mikofski (:ghuser:`mikofski`)
* Siddharth Kaul (:ghuser:`k10blogger`)
+* Mark Campanelli (:ghuser:`markcampanelli`)
| [
{
"components": [
{
"doc": "Convert spectral responsivities to quantum efficiencies.\nIf ``wavelength`` is not provided, the spectral responsivity ``sr`` must be\na :py:class:`pandas.Series` or :py:class:`pandas.DataFrame`, with the\nwavelengths in the index.\n\nProvide wavelengths in nanometers, ... | [
"pvlib/tests/test_spectrum.py::test_sr_to_qe",
"pvlib/tests/test_spectrum.py::test_qe_to_sr",
"pvlib/tests/test_spectrum.py::test_qe_and_sr_reciprocal_conversion",
"pvlib/tests/test_tools.py::test_normalize_max2one[data_in0-expected0]",
"pvlib/tests/test_tools.py::test_normalize_max2one[data_in1-expected1]"... | [
"pvlib/tests/test_spectrum.py::test_spectrl2",
"pvlib/tests/test_spectrum.py::test_spectrl2_array",
"pvlib/tests/test_spectrum.py::test_spectrl2_series",
"pvlib/tests/test_spectrum.py::test_dayofyear_missing",
"pvlib/tests/test_spectrum.py::test_aoi_gt_90",
"pvlib/tests/test_spectrum.py::test_get_example_... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
Quantum efficiency & spectral response conversion funcs
- [x] Closes #2040 (partially addresses #1963)
- [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.
Although I've opened an issue, I doubt there is much to discuss about these functions behaviour: possibly citations and error messages IMO.
Anyway, feel free to reach about any question, suggestion, etc.
### Docs
- https://pvlib-python--2041.org.readthedocs.build/en/2041/reference/generated/pvlib.spectrum.sr_to_qe.html
- https://pvlib-python--2041.org.readthedocs.build/en/2041/reference/generated/pvlib.spectrum.qe_to_sr.html
- https://pvlib-python--2041.org.readthedocs.build/en/2041/reference/effects_on_pv_system_output/spectrum.html
-
----------
</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/spectrum/mismatch.py]
(definition of sr_to_qe:)
def sr_to_qe(sr, wavelength=None, normalize=False):
"""Convert spectral responsivities to quantum efficiencies.
If ``wavelength`` is not provided, the spectral responsivity ``sr`` must be
a :py:class:`pandas.Series` or :py:class:`pandas.DataFrame`, with the
wavelengths in the index.
Provide wavelengths in nanometers, [nm].
Conversion is described in [1]_.
.. versionadded:: 0.11.0
Parameters
----------
sr : numeric, pandas.Series or pandas.DataFrame
Spectral response, [A/W].
Index must be the wavelength in nanometers, [nm].
wavelength : numeric, optional
Points where spectral response is measured, in nanometers, [nm].
normalize : bool, default False
If True, the quantum efficiency is normalized so that the maximum value
is 1.
For ``pandas.DataFrame``, normalization is done for each column.
For 2D arrays, normalization is done for each sub-array.
Returns
-------
quantum_efficiency : numeric, same type as ``sr``
Quantum efficiency, in the interval [0, 1].
Notes
-----
- If ``sr`` is of type ``pandas.Series`` or ``pandas.DataFrame``,
column names will remain unchanged in the returned object.
- If ``wavelength`` is provided it will be used independently of the
datatype of ``sr``.
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> from pvlib import spectrum
>>> wavelengths = np.array([350, 550, 750])
>>> spectral_response = np.array([0.25, 0.40, 0.57])
>>> quantum_efficiency = spectrum.sr_to_qe(spectral_response, wavelengths)
>>> print(quantum_efficiency)
array([0.88560142, 0.90170326, 0.94227991])
>>> spectral_response_series = pd.Series(spectral_response, index=wavelengths, name="dataset")
>>> qe = spectrum.sr_to_qe(spectral_response_series)
>>> print(qe)
350 0.885601
550 0.901703
750 0.942280
Name: dataset, dtype: float64
>>> qe = spectrum.sr_to_qe(spectral_response_series, normalize=True)
>>> print(qe)
350 0.939850
550 0.956938
750 1.000000
Name: dataset, dtype: float64
References
----------
.. [1] “Spectral Response,” PV Performance Modeling Collaborative (PVPMC).
https://pvpmc.sandia.gov/modeling-guide/2-dc-module-iv/effective-irradiance/spectral-response/
.. [2] “Spectral Response | PVEducation,” www.pveducation.org.
https://www.pveducation.org/pvcdrom/solar-cell-operation/spectral-response
See Also
--------
pvlib.spectrum.qe_to_sr"""
(definition of qe_to_sr:)
def qe_to_sr(qe, wavelength=None, normalize=False):
"""Convert quantum efficiencies to spectral responsivities.
If ``wavelength`` is not provided, the quantum efficiency ``qe`` must be
a :py:class:`pandas.Series` or :py:class:`pandas.DataFrame`, with the
wavelengths in the index.
Provide wavelengths in nanometers, [nm].
Conversion is described in [1]_.
.. versionadded:: 0.11.0
Parameters
----------
qe : numeric, pandas.Series or pandas.DataFrame
Quantum efficiency.
If pandas subtype, index must be the wavelength in nanometers, [nm].
wavelength : numeric, optional
Points where quantum efficiency is measured, in nanometers, [nm].
normalize : bool, default False
If True, the spectral response is normalized so that the maximum value
is 1.
For ``pandas.DataFrame``, normalization is done for each column.
For 2D arrays, normalization is done for each sub-array.
Returns
-------
spectral_response : numeric, same type as ``qe``
Spectral response, [A/W].
Notes
-----
- If ``qe`` is of type ``pandas.Series`` or ``pandas.DataFrame``,
column names will remain unchanged in the returned object.
- If ``wavelength`` is provided it will be used independently of the
datatype of ``qe``.
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> from pvlib import spectrum
>>> wavelengths = np.array([350, 550, 750])
>>> quantum_efficiency = np.array([0.86, 0.90, 0.94])
>>> spectral_response = spectrum.qe_to_sr(quantum_efficiency, wavelengths)
>>> print(spectral_response)
array([0.24277287, 0.39924442, 0.56862085])
>>> quantum_efficiency_series = pd.Series(quantum_efficiency, index=wavelengths, name="dataset")
>>> sr = spectrum.qe_to_sr(quantum_efficiency_series)
>>> print(sr)
350 0.242773
550 0.399244
750 0.568621
Name: dataset, dtype: float64
>>> sr = spectrum.qe_to_sr(quantum_efficiency_series, normalize=True)
>>> print(sr)
350 0.426950
550 0.702128
750 1.000000
Name: dataset, dtype: float64
References
----------
.. [1] “Spectral Response,” PV Performance Modeling Collaborative (PVPMC).
https://pvpmc.sandia.gov/modeling-guide/2-dc-module-iv/effective-irradiance/spectral-response/
.. [2] “Spectral Response | PVEducation,” www.pveducation.org.
https://www.pveducation.org/pvcdrom/solar-cell-operation/spectral-response
See Also
--------
pvlib.spectrum.sr_to_qe"""
[end of new definitions in pvlib/spectrum/mismatch.py]
[start of new definitions in pvlib/tools.py]
(definition of normalize_max2one:)
def normalize_max2one(a):
"""Normalize an array so that the largest absolute value is ±1.
Handles both numpy arrays and pandas objects.
On 2D arrays, normalization is row-wise.
On pandas DataFrame, normalization is column-wise.
If all values of row are 0, the array is set to NaNs.
Parameters
----------
a : array-like
The array to normalize.
Returns
-------
array-like
The normalized array."""
[end of new definitions in pvlib/tools.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>
Spectral responsivity and quantum efficiency conversion functions
**Is your feature request related to a problem? Please describe.**
Add functions to convert from SR to EQE and vice versa.
**Describe the solution you'd like**
Two distinct functions for each one of the purposes, that work both with `pandas.Series` and vector inputs.
**Describe alternatives you've considered**
N/A.
**Additional context**
Initially proposed by @markcampanelli in #1963.
----------
--------------------
</issues> | d53f97e984bfdd268aa92f8bf482ced0edda0110 |
roboflow__supervision-1163 | 1,163 | roboflow/supervision | null | 3fbce7b6bbdccfbbd68a525cfa3993e16c0637c7 | 2024-05-05T11:59:11Z | diff --git a/docs/datasets.md b/docs/datasets/core.md
similarity index 97%
rename from docs/datasets.md
rename to docs/datasets/core.md
index 739315150..03d0c1966 100644
--- a/docs/datasets.md
+++ b/docs/datasets/core.md
@@ -1,5 +1,6 @@
---
comments: true
+status: new
---
# Datasets
diff --git a/docs/datasets/utils.md b/docs/datasets/utils.md
new file mode 100644
index 000000000..6be56303f
--- /dev/null
+++ b/docs/datasets/utils.md
@@ -0,0 +1,18 @@
+---
+comments: true
+status: new
+---
+
+# Datasets Utils
+
+<div class="md-typeset">
+ <h2><a href="#supervision.dataset.utils.rle_to_mask">rle_to_mask</a></h2>
+</div>
+
+:::supervision.dataset.utils.rle_to_mask
+
+<div class="md-typeset">
+ <h2><a href="#supervision.dataset.utils.mask_to_rle">mask_to_rle</a></h2>
+</div>
+
+:::supervision.dataset.utils.mask_to_rle
diff --git a/docs/detection/utils.md b/docs/detection/utils.md
index 5a9d2ba21..f9c9473bc 100644
--- a/docs/detection/utils.md
+++ b/docs/detection/utils.md
@@ -88,3 +88,15 @@ status: new
</div>
:::supervision.detection.utils.pad_boxes
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.utils.contains_holes">contains_holes</a></h2>
+</div>
+
+:::supervision.detection.utils.contains_holes
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.utils.contains_multiple_segments">contains_multiple_segments</a></h2>
+</div>
+
+:::supervision.detection.utils.contains_multiple_segments
diff --git a/mkdocs.yml b/mkdocs.yml
index cf206a82e..281c40c97 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -61,7 +61,9 @@ nav:
- Detection Smoother: detection/tools/smoother.md
- Save Detections: detection/tools/save_detections.md
- Trackers: trackers.md
- - Datasets: datasets.md
+ - Datasets:
+ - Core: datasets/core.md
+ - Utils: datasets/utils.md
- Utils:
- Video: utils/video.md
- Image: utils/image.md
diff --git a/supervision/__init__.py b/supervision/__init__.py
index 646800125..abe633908 100644
--- a/supervision/__init__.py
+++ b/supervision/__init__.py
@@ -35,6 +35,7 @@
ClassificationDataset,
DetectionDataset,
)
+from supervision.dataset.utils import mask_to_rle, rle_to_mask
from supervision.detection.annotate import BoxAnnotator
from supervision.detection.core import Detections
from supervision.detection.line_zone import LineZone, LineZoneAnnotator
@@ -48,6 +49,8 @@
box_non_max_suppression,
calculate_masks_centroids,
clip_boxes,
+ contains_holes,
+ contains_multiple_segments,
filter_polygons_by_area,
mask_iou_batch,
mask_non_max_suppression,
diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py
index 551e96da0..c8863df35 100644
--- a/supervision/dataset/core.py
+++ b/supervision/dataset/core.py
@@ -116,13 +116,12 @@ def split(
Tuple[DetectionDataset, DetectionDataset]: A tuple containing
the training and testing datasets.
- Example:
+ Examples:
```python
import supervision as sv
ds = sv.DetectionDataset(...)
- train_ds, test_ds = ds.split(split_ratio=0.7,
- random_state=42, shuffle=True)
+ train_ds, test_ds = ds.split(split_ratio=0.7, random_state=42, shuffle=True)
len(train_ds), len(test_ds)
# (700, 300)
```
@@ -229,7 +228,7 @@ def from_pascal_voc(
DetectionDataset: A DetectionDataset instance containing
the loaded images and annotations.
- Example:
+ Examples:
```python
import roboflow
from roboflow import Roboflow
@@ -286,7 +285,7 @@ def from_yolo(
DetectionDataset: A DetectionDataset instance
containing the loaded images and annotations.
- Example:
+ Examples:
```python
import roboflow
from roboflow import Roboflow
@@ -391,7 +390,7 @@ def from_coco(
DetectionDataset: A DetectionDataset instance containing
the loaded images and annotations.
- Example:
+ Examples:
```python
import roboflow
from roboflow import Roboflow
@@ -431,6 +430,20 @@ def as_coco(
Exports the dataset to COCO format. This method saves the
images and their corresponding annotations in COCO format.
+ !!! tip
+
+ The format of the mask is determined automatically based on its structure:
+
+ - If a mask contains multiple disconnected components or holes, it will be
+ saved using the Run-Length Encoding (RLE) format for efficient storage and
+ processing.
+ - If a mask consists of a single, contiguous region without any holes, it
+ will be encoded as a polygon, preserving the outline of the object.
+
+ This automatic selection ensures that the masks are stored in the most
+ appropriate and space-efficient format, complying with COCO dataset
+ standards.
+
Args:
images_directory_path (Optional[str]): The path to the directory
where the images should be saved.
@@ -482,7 +495,7 @@ def merge(cls, dataset_list: List[DetectionDataset]) -> DetectionDataset:
(DetectionDataset): A single `DetectionDataset` object containing
the merged data from the input list.
- Example:
+ Examples:
```python
import supervision as sv
@@ -567,13 +580,12 @@ def split(
Tuple[ClassificationDataset, ClassificationDataset]: A tuple containing
the training and testing datasets.
- Example:
+ Examples:
```python
import supervision as sv
cd = sv.ClassificationDataset(...)
- train_cd,test_cd = cd.split(split_ratio=0.7,
- random_state=42,shuffle=True)
+ train_cd,test_cd = cd.split(split_ratio=0.7, random_state=42,shuffle=True)
len(train_cd), len(test_cd)
# (700, 300)
```
@@ -635,7 +647,7 @@ def from_folder_structure(cls, root_directory_path: str) -> ClassificationDatase
Returns:
ClassificationDataset: The dataset.
- Example:
+ Examples:
```python
import roboflow
from roboflow import Roboflow
diff --git a/supervision/dataset/formats/coco.py b/supervision/dataset/formats/coco.py
index 4f8679d52..353e33f5e 100644
--- a/supervision/dataset/formats/coco.py
+++ b/supervision/dataset/formats/coco.py
@@ -5,13 +5,20 @@
import cv2
import numpy as np
+import numpy.typing as npt
from supervision.dataset.utils import (
approximate_mask_with_polygons,
map_detections_class_id,
+ mask_to_rle,
+ rle_to_mask,
)
from supervision.detection.core import Detections
-from supervision.detection.utils import polygon_to_mask
+from supervision.detection.utils import (
+ contains_holes,
+ contains_multiple_segments,
+ polygon_to_mask,
+)
from supervision.utils.file import read_json_file, save_json_file
@@ -57,13 +64,24 @@ def group_coco_annotations_by_image_id(
return annotations
-def _polygons_to_masks(
- polygons: List[np.ndarray], resolution_wh: Tuple[int, int]
-) -> np.ndarray:
+def coco_annotations_to_masks(
+ image_annotations: List[dict], resolution_wh: Tuple[int, int]
+) -> npt.NDArray[np.bool_]:
return np.array(
[
- polygon_to_mask(polygon=polygon, resolution_wh=resolution_wh)
- for polygon in polygons
+ rle_to_mask(
+ rle=np.array(image_annotation["segmentation"]["counts"]),
+ resolution_wh=resolution_wh,
+ )
+ if image_annotation["iscrowd"]
+ else polygon_to_mask(
+ polygon=np.reshape(
+ np.asarray(image_annotation["segmentation"], dtype=np.int32),
+ (-1, 2),
+ ),
+ resolution_wh=resolution_wh,
+ )
+ for image_annotation in image_annotations
],
dtype=bool,
)
@@ -83,13 +101,9 @@ def coco_annotations_to_detections(
xyxy[:, 2:4] += xyxy[:, 0:2]
if with_masks:
- polygons = [
- np.reshape(
- np.asarray(image_annotation["segmentation"], dtype=np.int32), (-1, 2)
- )
- for image_annotation in image_annotations
- ]
- mask = _polygons_to_masks(polygons=polygons, resolution_wh=resolution_wh)
+ mask = coco_annotations_to_masks(
+ image_annotations=image_annotations, resolution_wh=resolution_wh
+ )
return Detections(
class_id=np.asarray(class_ids, dtype=int), xyxy=xyxy, mask=mask
)
@@ -108,24 +122,35 @@ def detections_to_coco_annotations(
coco_annotations = []
for xyxy, mask, _, class_id, _, _ in detections:
box_width, box_height = xyxy[2] - xyxy[0], xyxy[3] - xyxy[1]
- polygon = []
+ segmentation = []
+ iscrowd = 0
if mask is not None:
- polygon = list(
- approximate_mask_with_polygons(
- mask=mask,
- min_image_area_percentage=min_image_area_percentage,
- max_image_area_percentage=max_image_area_percentage,
- approximation_percentage=approximation_percentage,
- )[0].flatten()
- )
+ iscrowd = contains_holes(mask=mask) or contains_multiple_segments(mask=mask)
+
+ if iscrowd:
+ segmentation = {
+ "counts": mask_to_rle(mask=mask),
+ "size": list(mask.shape[:2]),
+ }
+ else:
+ segmentation = [
+ list(
+ approximate_mask_with_polygons(
+ mask=mask,
+ min_image_area_percentage=min_image_area_percentage,
+ max_image_area_percentage=max_image_area_percentage,
+ approximation_percentage=approximation_percentage,
+ )[0].flatten()
+ )
+ ]
coco_annotation = {
"id": annotation_id,
"image_id": image_id,
"category_id": int(class_id),
"bbox": [xyxy[0], xyxy[1], box_width, box_height],
"area": box_width * box_height,
- "segmentation": [polygon] if polygon else [],
- "iscrowd": 0,
+ "segmentation": segmentation,
+ "iscrowd": iscrowd,
}
coco_annotations.append(coco_annotation)
annotation_id += 1
diff --git a/supervision/dataset/utils.py b/supervision/dataset/utils.py
index 05ee32013..32ece6bf1 100644
--- a/supervision/dataset/utils.py
+++ b/supervision/dataset/utils.py
@@ -2,10 +2,11 @@
import os
import random
from pathlib import Path
-from typing import Dict, List, Optional, Tuple, TypeVar
+from typing import Dict, List, Optional, Tuple, TypeVar, Union
import cv2
import numpy as np
+import numpy.typing as npt
from supervision.detection.core import Detections
from supervision.detection.utils import (
@@ -129,3 +130,123 @@ def train_test_split(
split_index = int(len(data) * train_ratio)
return data[:split_index], data[split_index:]
+
+
+def rle_to_mask(
+ rle: Union[npt.NDArray[np.int_], List[int]], resolution_wh: Tuple[int, int]
+) -> npt.NDArray[np.bool_]:
+ """
+ Converts run-length encoding (RLE) to a binary mask.
+
+ Args:
+ rle (Union[npt.NDArray[np.int_], List[int]]): The 1D RLE array, the format
+ used in the COCO dataset (column-wise encoding, values of an array with
+ even indices represent the number of pixels assigned as background,
+ values of an array with odd indices represent the number of pixels
+ assigned as foreground object).
+ resolution_wh (Tuple[int, int]): The width (w) and height (h)
+ of the desired binary mask.
+
+ Returns:
+ The generated 2D Boolean mask of shape `(h, w)`, where the foreground object is
+ marked with `True`'s and the rest is filled with `False`'s.
+
+ Raises:
+ AssertionError: If the sum of pixels encoded in RLE differs from the
+ number of pixels in the expected mask (computed based on resolution_wh).
+
+ Examples:
+ ```python
+ import supervision as sv
+
+ sv.rle_to_mask([5, 2, 2, 2, 5], (4, 4))
+ # array([
+ # [False, False, False, False],
+ # [False, True, True, False],
+ # [False, True, True, False],
+ # [False, False, False, False],
+ # ])
+ ```
+ """
+ if isinstance(rle, list):
+ rle = np.array(rle, dtype=int)
+
+ width, height = resolution_wh
+
+ assert width * height == np.sum(rle), (
+ "the sum of the number of pixels in the RLE must be the same "
+ "as the number of pixels in the expected mask"
+ )
+
+ zero_one_values = np.zeros(shape=(rle.size, 1), dtype=np.uint8)
+ zero_one_values[1::2] = 1
+
+ decoded_rle = np.repeat(zero_one_values, rle, axis=0)
+ decoded_rle = np.append(
+ decoded_rle, np.zeros(width * height - len(decoded_rle), dtype=np.uint8)
+ )
+ return decoded_rle.reshape((height, width), order="F")
+
+
+def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]:
+ """
+ Converts a binary mask into a run-length encoding (RLE).
+
+ Args:
+ mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
+ object and `False` indicates background.
+
+ Returns:
+ The run-length encoded mask. Values of a list with even indices
+ represent the number of pixels assigned as background (`False`), values
+ of a list with odd indices represent the number of pixels assigned
+ as foreground object (`True`).
+
+ Raises:
+ AssertionError: If input mask is not 2D or is empty.
+
+ Examples:
+ ```python
+ import numpy as np
+ import supervision as sv
+
+ mask = np.array([
+ [True, True, True, True],
+ [True, True, True, True],
+ [True, True, True, True],
+ [True, True, True, True],
+ ])
+ sv.mask_to_rle(mask)
+ # [0, 16]
+
+ mask = np.array([
+ [False, False, False, False],
+ [False, True, True, False],
+ [False, True, True, False],
+ [False, False, False, False],
+ ])
+ sv.mask_to_rle(mask)
+ # [5, 2, 2, 2, 5]
+ ```
+
+ { align=center width="800" }
+ """ # noqa E501 // docs
+ assert mask.ndim == 2, "Input mask must be 2D"
+ assert mask.size != 0, "Input mask cannot be empty"
+
+ on_value_change_indices = np.where(
+ mask.ravel(order="F") != np.roll(mask.ravel(order="F"), 1)
+ )[0]
+
+ on_value_change_indices = np.append(on_value_change_indices, mask.size)
+ # need to add 0 at the beginning when the same value is in the first and
+ # last element of the flattened mask
+ if on_value_change_indices[0] != 0:
+ on_value_change_indices = np.insert(on_value_change_indices, 0, 0)
+
+ rle = np.diff(on_value_change_indices)
+
+ if mask[0][0] == 1:
+ rle = np.insert(rle, 0, 0)
+
+ return list(rle)
diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py
index 9232089e5..742f94f6a 100644
--- a/supervision/detection/utils.py
+++ b/supervision/detection/utils.py
@@ -3,6 +3,7 @@
import cv2
import numpy as np
+import numpy.typing as npt
from supervision.config import CLASS_NAME_DATA_FIELD
@@ -603,18 +604,21 @@ def move_boxes(xyxy: np.ndarray, offset: np.ndarray) -> np.ndarray:
Returns:
np.ndarray: Repositioned bounding boxes.
- Example:
+ Examples:
```python
import numpy as np
import supervision as sv
- boxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]])
+ xyxy = np.array([
+ [10, 10, 20, 20],
+ [30, 30, 40, 40]
+ ])
offset = np.array([5, 5])
- moved_box = sv.move_boxes(boxes, offset)
- print(moved_box)
- # np.array([
+
+ sv.move_boxes(xyxy=xyxy, offset=offset)
+ # array([
# [15, 15, 25, 25],
- # [35, 35, 45, 45]
+ # [35, 35, 45, 45]
# ])
```
"""
@@ -669,16 +673,18 @@ def scale_boxes(xyxy: np.ndarray, factor: float) -> np.ndarray:
Returns:
np.ndarray: Scaled bounding boxes.
- Example:
+ Examples:
```python
import numpy as np
import supervision as sv
- boxes = np.array([[10, 10, 20, 20], [30, 30, 40, 40]])
- factor = 1.5
- scaled_bb = sv.scale_boxes(boxes, factor)
- print(scaled_bb)
- # np.array([
+ xyxy = np.array([
+ [10, 10, 20, 20],
+ [30, 30, 40, 40]
+ ])
+
+ scaled_bb = sv.scale_boxes(xyxy=xyxy, factor=1.5)
+ # array([
# [ 7.5, 7.5, 22.5, 22.5],
# [27.5, 27.5, 42.5, 42.5]
# ])
@@ -840,3 +846,121 @@ def get_data_item(
raise TypeError(f"Unsupported data type for key '{key}': {type(value)}")
return subset_data
+
+
+def contains_holes(mask: npt.NDArray[np.bool_]) -> bool:
+ """
+ Checks if the binary mask contains holes (background pixels fully enclosed by
+ foreground pixels).
+
+ Args:
+ mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
+ object and `False` indicates background.
+
+ Returns:
+ True if holes are detected, False otherwise.
+
+ Examples:
+ ```python
+ import numpy as np
+ import supervision as sv
+
+ mask = np.array([
+ [0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]
+ ]).astype(bool)
+
+ sv.contains_holes(mask=mask)
+ # True
+
+ mask = np.array([
+ [0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]
+ ]).astype(bool)
+
+ sv.contains_holes(mask=mask)
+ # False
+ ```
+
+ { align=center width="800" }
+ """ # noqa E501 // docs
+ mask_uint8 = mask.astype(np.uint8)
+ _, hierarchy = cv2.findContours(mask_uint8, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
+
+ if hierarchy is not None:
+ parent_contour_index = 3
+ for h in hierarchy[0]:
+ if h[parent_contour_index] != -1:
+ return True
+ return False
+
+
+def contains_multiple_segments(
+ mask: npt.NDArray[np.bool_], connectivity: int = 4
+) -> bool:
+ """
+ Checks if the binary mask contains multiple unconnected foreground segments.
+
+ Args:
+ mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
+ object and `False` indicates background.
+ connectivity (int) : Default: 4 is 4-way connectivity, which means that
+ foreground pixels are the part of the same segment/component
+ if their edges touch.
+ Alternatively: 8 for 8-way connectivity, when foreground pixels are
+ connected by their edges or corners touch.
+
+ Returns:
+ True when the mask contains multiple not connected components, False otherwise.
+
+ Raises:
+ ValueError: If connectivity(int) parameter value is not 4 or 8.
+
+ Examples:
+ ```python
+ import numpy as np
+ import supervision as sv
+
+ mask = np.array([
+ [0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1],
+ [0, 1, 1, 0, 1, 1],
+ [0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 0, 0]
+ ]).astype(bool)
+
+ sv.contains_multiple_segments(mask=mask, connectivity=4)
+ # True
+
+ mask = np.array([
+ [0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1],
+ [0, 0, 0, 0, 0, 0]
+ ]).astype(bool)
+
+ sv.contains_multiple_segments(mask=mask, connectivity=4)
+ # False
+ ```
+
+ { align=center width="800" }
+ """ # noqa E501 // docs
+ if connectivity != 4 and connectivity != 8:
+ raise ValueError(
+ "Incorrect connectivity value. Possible connectivity values: 4 or 8."
+ )
+ mask_uint8 = mask.astype(np.uint8)
+ labels = np.zeros_like(mask_uint8, dtype=np.int32)
+ number_of_labels, _ = cv2.connectedComponents(
+ mask_uint8, labels, connectivity=connectivity
+ )
+ return number_of_labels > 2
| diff --git a/test/dataset/formats/test_coco.py b/test/dataset/formats/test_coco.py
index 62d1b75bd..7e269dae4 100644
--- a/test/dataset/formats/test_coco.py
+++ b/test/dataset/formats/test_coco.py
@@ -1,5 +1,5 @@
from contextlib import ExitStack as DoesNotRaise
-from typing import Dict, List, Tuple
+from typing import Dict, List, Tuple, Union
import numpy as np
import pytest
@@ -10,24 +10,30 @@
classes_to_coco_categories,
coco_annotations_to_detections,
coco_categories_to_classes,
+ detections_to_coco_annotations,
group_coco_annotations_by_image_id,
)
-def mock_cock_coco_annotation(
+def mock_coco_annotation(
annotation_id: int = 0,
image_id: int = 0,
category_id: int = 0,
bbox: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0),
area: float = 0.0,
+ segmentation: Union[List[list], Dict] = None,
+ iscrowd: bool = False,
) -> dict:
+ if not segmentation:
+ segmentation = []
return {
"id": annotation_id,
"image_id": image_id,
"category_id": category_id,
"bbox": list(bbox),
"area": area,
- "iscrowd": 0,
+ "segmentation": segmentation,
+ "iscrowd": int(iscrowd),
}
@@ -101,74 +107,46 @@ def test_classes_to_coco_categories_and_back_to_classes(
[
([], {}, DoesNotRaise()), # empty coco annotations
(
- [mock_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0)],
- {
- 0: [
- mock_cock_coco_annotation(
- annotation_id=0, image_id=0, category_id=0
- )
- ]
- },
+ [mock_coco_annotation(annotation_id=0, image_id=0, category_id=0)],
+ {0: [mock_coco_annotation(annotation_id=0, image_id=0, category_id=0)]},
DoesNotRaise(),
), # single coco annotation
(
[
- mock_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0),
- mock_cock_coco_annotation(annotation_id=1, image_id=1, category_id=0),
+ mock_coco_annotation(annotation_id=0, image_id=0, category_id=0),
+ mock_coco_annotation(annotation_id=1, image_id=1, category_id=0),
],
{
- 0: [
- mock_cock_coco_annotation(
- annotation_id=0, image_id=0, category_id=0
- )
- ],
- 1: [
- mock_cock_coco_annotation(
- annotation_id=1, image_id=1, category_id=0
- )
- ],
+ 0: [mock_coco_annotation(annotation_id=0, image_id=0, category_id=0)],
+ 1: [mock_coco_annotation(annotation_id=1, image_id=1, category_id=0)],
},
DoesNotRaise(),
), # two coco annotations
(
[
- mock_cock_coco_annotation(annotation_id=0, image_id=0, category_id=0),
- mock_cock_coco_annotation(annotation_id=1, image_id=1, category_id=1),
- mock_cock_coco_annotation(annotation_id=2, image_id=1, category_id=2),
- mock_cock_coco_annotation(annotation_id=3, image_id=2, category_id=3),
- mock_cock_coco_annotation(annotation_id=4, image_id=3, category_id=1),
- mock_cock_coco_annotation(annotation_id=5, image_id=3, category_id=2),
- mock_cock_coco_annotation(annotation_id=5, image_id=3, category_id=3),
+ mock_coco_annotation(annotation_id=0, image_id=0, category_id=0),
+ mock_coco_annotation(annotation_id=1, image_id=1, category_id=1),
+ mock_coco_annotation(annotation_id=2, image_id=1, category_id=2),
+ mock_coco_annotation(annotation_id=3, image_id=2, category_id=3),
+ mock_coco_annotation(annotation_id=4, image_id=3, category_id=1),
+ mock_coco_annotation(annotation_id=5, image_id=3, category_id=2),
+ mock_coco_annotation(annotation_id=5, image_id=3, category_id=3),
],
{
0: [
- mock_cock_coco_annotation(
- annotation_id=0, image_id=0, category_id=0
- ),
+ mock_coco_annotation(annotation_id=0, image_id=0, category_id=0),
],
1: [
- mock_cock_coco_annotation(
- annotation_id=1, image_id=1, category_id=1
- ),
- mock_cock_coco_annotation(
- annotation_id=2, image_id=1, category_id=2
- ),
+ mock_coco_annotation(annotation_id=1, image_id=1, category_id=1),
+ mock_coco_annotation(annotation_id=2, image_id=1, category_id=2),
],
2: [
- mock_cock_coco_annotation(
- annotation_id=3, image_id=2, category_id=3
- ),
+ mock_coco_annotation(annotation_id=3, image_id=2, category_id=3),
],
3: [
- mock_cock_coco_annotation(
- annotation_id=4, image_id=3, category_id=1
- ),
- mock_cock_coco_annotation(
- annotation_id=5, image_id=3, category_id=2
- ),
- mock_cock_coco_annotation(
- annotation_id=5, image_id=3, category_id=3
- ),
+ mock_coco_annotation(annotation_id=4, image_id=3, category_id=1),
+ mock_coco_annotation(annotation_id=5, image_id=3, category_id=2),
+ mock_coco_annotation(annotation_id=5, image_id=3, category_id=3),
],
},
DoesNotRaise(),
@@ -195,7 +173,7 @@ def test_group_coco_annotations_by_image_id(
), # empty image annotations
(
[
- mock_cock_coco_annotation(
+ mock_coco_annotation(
category_id=0, bbox=(0, 0, 100, 100), area=100 * 100
)
],
@@ -209,10 +187,10 @@ def test_group_coco_annotations_by_image_id(
), # single image annotations
(
[
- mock_cock_coco_annotation(
+ mock_coco_annotation(
category_id=0, bbox=(0, 0, 100, 100), area=100 * 100
),
- mock_cock_coco_annotation(
+ mock_coco_annotation(
category_id=0, bbox=(100, 100, 100, 100), area=100 * 100
),
],
@@ -226,6 +204,156 @@ def test_group_coco_annotations_by_image_id(
),
DoesNotRaise(),
), # two image annotations
+ (
+ [
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(0, 0, 5, 5),
+ area=5 * 5,
+ segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]],
+ )
+ ],
+ (5, 5),
+ True,
+ Detections(
+ xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32),
+ class_id=np.array([0], dtype=int),
+ mask=np.array(
+ [
+ [
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ ]
+ ]
+ ),
+ ),
+ DoesNotRaise(),
+ ), # single image annotations with mask as polygon
+ (
+ [
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(0, 0, 5, 5),
+ area=5 * 5,
+ segmentation={
+ "size": [5, 5],
+ "counts": [0, 15, 2, 3, 2, 3],
+ },
+ iscrowd=True,
+ )
+ ],
+ (5, 5),
+ True,
+ Detections(
+ xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32),
+ class_id=np.array([0], dtype=int),
+ mask=np.array(
+ [
+ [
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ ]
+ ]
+ ),
+ ),
+ DoesNotRaise(),
+ ), # single image annotations with mask, RLE segmentation mask
+ (
+ [
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(0, 0, 5, 5),
+ area=5 * 5,
+ segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]],
+ ),
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(3, 0, 2, 2),
+ area=2 * 2,
+ segmentation={
+ "size": [5, 5],
+ "counts": [15, 2, 3, 2, 3],
+ },
+ iscrowd=True,
+ ),
+ ],
+ (5, 5),
+ True,
+ Detections(
+ xyxy=np.array([[0, 0, 5, 5], [3, 0, 5, 2]], dtype=np.float32),
+ class_id=np.array([0, 0], dtype=int),
+ mask=np.array(
+ [
+ [
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ ],
+ [
+ [0, 0, 0, 1, 1],
+ [0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ ],
+ ]
+ ),
+ ),
+ DoesNotRaise(),
+ ), # two image annotations with mask, one mask as polygon ans second as RLE
+ (
+ [
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(3, 0, 2, 2),
+ area=2 * 2,
+ segmentation={
+ "size": [5, 5],
+ "counts": [15, 2, 3, 2, 3],
+ },
+ iscrowd=True,
+ ),
+ mock_coco_annotation(
+ category_id=1,
+ bbox=(0, 0, 5, 5),
+ area=5 * 5,
+ segmentation=[[0, 0, 2, 0, 2, 2, 4, 2, 4, 4, 0, 4]],
+ ),
+ ],
+ (5, 5),
+ True,
+ Detections(
+ xyxy=np.array([[3, 0, 5, 2], [0, 0, 5, 5]], dtype=np.float32),
+ class_id=np.array([0, 1], dtype=int),
+ mask=np.array(
+ [
+ [
+ [0, 0, 0, 1, 1],
+ [0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ ],
+ [
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ ],
+ ]
+ ),
+ ),
+ DoesNotRaise(),
+ ), # two image annotations with mask, first mask as RLE and second as polygon
],
)
def test_coco_annotations_to_detections(
@@ -301,3 +429,131 @@ def test_build_coco_class_index_mapping(
coco_categories=coco_categories, target_classes=target_classes
)
assert result == expected_result
+
+
+@pytest.mark.parametrize(
+ "detections, image_id, annotation_id, expected_result, exception",
+ [
+ (
+ Detections(
+ xyxy=np.array([[0, 0, 100, 100]], dtype=np.float32),
+ class_id=np.array([0], dtype=int),
+ ),
+ 0,
+ 0,
+ [
+ mock_coco_annotation(
+ category_id=0, bbox=(0, 0, 100, 100), area=100 * 100
+ )
+ ],
+ DoesNotRaise(),
+ ), # no segmentation mask
+ (
+ Detections(
+ xyxy=np.array([[0, 0, 4, 5]], dtype=np.float32),
+ class_id=np.array([0], dtype=int),
+ mask=np.array(
+ [
+ [
+ [1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ ]
+ ]
+ ),
+ ),
+ 0,
+ 0,
+ [
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(0, 0, 4, 5),
+ area=4 * 5,
+ segmentation=[[0, 0, 0, 4, 3, 4, 3, 0]],
+ )
+ ],
+ DoesNotRaise(),
+ ), # segmentation mask in single component,no holes in mask,
+ # expects polygon mask
+ (
+ Detections(
+ xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32),
+ class_id=np.array([0], dtype=int),
+ mask=np.array(
+ [
+ [
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1],
+ [0, 0, 0, 1, 1],
+ ]
+ ]
+ ),
+ ),
+ 0,
+ 0,
+ [
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(0, 0, 5, 5),
+ area=5 * 5,
+ segmentation={
+ "size": [5, 5],
+ "counts": [0, 3, 2, 3, 2, 3, 5, 2, 3, 2],
+ },
+ iscrowd=True,
+ )
+ ],
+ DoesNotRaise(),
+ ), # segmentation mask with 2 components, no holes in mask, expects RLE mask
+ (
+ Detections(
+ xyxy=np.array([[0, 0, 5, 5]], dtype=np.float32),
+ class_id=np.array([0], dtype=int),
+ mask=np.array(
+ [
+ [
+ [0, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1],
+ [1, 1, 0, 0, 1],
+ [1, 1, 0, 0, 1],
+ [1, 1, 1, 1, 1],
+ ]
+ ]
+ ),
+ ),
+ 0,
+ 0,
+ [
+ mock_coco_annotation(
+ category_id=0,
+ bbox=(0, 0, 5, 5),
+ area=5 * 5,
+ segmentation={
+ "size": [5, 5],
+ "counts": [2, 10, 2, 3, 2, 6],
+ },
+ iscrowd=True,
+ )
+ ],
+ DoesNotRaise(),
+ ), # seg mask in single component, with holes in mask, expects RLE mask
+ ],
+)
+def test_detections_to_coco_annotations(
+ detections: Detections,
+ image_id: int,
+ annotation_id: int,
+ expected_result: List[Dict],
+ exception: Exception,
+) -> None:
+ with exception:
+ result, _ = detections_to_coco_annotations(
+ detections=detections,
+ image_id=image_id,
+ annotation_id=annotation_id,
+ )
+ assert result == expected_result
diff --git a/test/dataset/test_utils.py b/test/dataset/test_utils.py
index 5ca96ca59..41e1da5bc 100644
--- a/test/dataset/test_utils.py
+++ b/test/dataset/test_utils.py
@@ -2,13 +2,17 @@
from test.test_utils import mock_detections
from typing import Dict, List, Optional, Tuple, TypeVar
+import numpy as np
+import numpy.typing as npt
import pytest
from supervision import Detections
from supervision.dataset.utils import (
build_class_index_mapping,
map_detections_class_id,
+ mask_to_rle,
merge_class_lists,
+ rle_to_mask,
train_test_split,
)
@@ -229,3 +233,131 @@ def test_map_detections_class_id(
source_to_target_mapping=source_to_target_mapping, detections=detections
)
assert result == expected_result
+
+
+@pytest.mark.parametrize(
+ "mask, expected_rle, exception",
+ [
+ (
+ np.zeros((3, 3)).astype(bool),
+ [9],
+ DoesNotRaise(),
+ ), # mask with background only (mask with only False values)
+ (
+ np.ones((3, 3)).astype(bool),
+ [0, 9],
+ DoesNotRaise(),
+ ), # mask with foreground only (mask with only True values)
+ (
+ np.array(
+ [
+ [0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0],
+ ]
+ ).astype(bool),
+ [6, 3, 2, 1, 1, 1, 2, 3, 6],
+ DoesNotRaise(),
+ ), # mask where foreground object has hole
+ (
+ np.array(
+ [
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ ]
+ ).astype(bool),
+ [0, 5, 5, 5, 5, 5],
+ DoesNotRaise(),
+ ), # mask where foreground consists of 3 separate components
+ (
+ np.array([[[]]]).astype(bool),
+ None,
+ pytest.raises(AssertionError),
+ ), # raises AssertionError because mask dimentionality is not 2D
+ (
+ np.array([[]]).astype(bool),
+ None,
+ pytest.raises(AssertionError),
+ ), # raises AssertionError because mask is empty
+ ],
+)
+def test_mask_to_rle(
+ mask: npt.NDArray[np.bool_], expected_rle: List[int], exception: Exception
+) -> None:
+ with exception:
+ result = mask_to_rle(mask=mask)
+ assert result == expected_rle
+
+
+@pytest.mark.parametrize(
+ "rle, resolution_wh, expected_mask, exception",
+ [
+ (
+ np.array([9]),
+ [3, 3],
+ np.zeros((3, 3)).astype(bool),
+ DoesNotRaise(),
+ ), # mask with background only (mask with only False values); rle as array
+ (
+ [9],
+ [3, 3],
+ np.zeros((3, 3)).astype(bool),
+ DoesNotRaise(),
+ ), # mask with background only (mask with only False values); rle as list
+ (
+ np.array([0, 9]),
+ [3, 3],
+ np.ones((3, 3)).astype(bool),
+ DoesNotRaise(),
+ ), # mask with foreground only (mask with only True values)
+ (
+ np.array([6, 3, 2, 1, 1, 1, 2, 3, 6]),
+ [5, 5],
+ np.array(
+ [
+ [0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0],
+ ]
+ ).astype(bool),
+ DoesNotRaise(),
+ ), # mask where foreground object has hole
+ (
+ np.array([0, 5, 5, 5, 5, 5]),
+ [5, 5],
+ np.array(
+ [
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ [1, 0, 1, 0, 1],
+ ]
+ ).astype(bool),
+ DoesNotRaise(),
+ ), # mask where foreground consists of 3 separate components
+ (
+ np.array([0, 5, 5, 5, 5, 5]),
+ [2, 2],
+ None,
+ pytest.raises(AssertionError),
+ ), # raises AssertionError because number of pixels in RLE does not match
+ # number of pixels in expected mask (width x height).
+ ],
+)
+def test_rle_to_mask(
+ rle: npt.NDArray[np.int_],
+ resolution_wh: Tuple[int, int],
+ expected_mask: npt.NDArray[np.bool_],
+ exception: Exception,
+) -> None:
+ with exception:
+ result = rle_to_mask(rle=rle, resolution_wh=resolution_wh)
+ assert np.all(result == expected_mask)
diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py
index 097c5c6e5..6a2070dae 100644
--- a/test/detection/test_utils.py
+++ b/test/detection/test_utils.py
@@ -2,6 +2,7 @@
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
+import numpy.typing as npt
import pytest
from supervision.config import CLASS_NAME_DATA_FIELD
@@ -9,6 +10,8 @@
box_non_max_suppression,
calculate_masks_centroids,
clip_boxes,
+ contains_holes,
+ contains_multiple_segments,
filter_polygons_by_area,
get_data_item,
mask_non_max_suppression,
@@ -1265,3 +1268,138 @@ def test_get_data_item(
assert (
result[key] == expected_result[key]
), f"Mismatch in non-array data for key {key}"
+
+
+@pytest.mark.parametrize(
+ "mask, expected_result, exception",
+ [
+ (
+ np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 1, 0]]).astype(
+ bool
+ ),
+ False,
+ DoesNotRaise(),
+ ), # foreground object in one continuous piece
+ (
+ np.array([[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0]]).astype(
+ bool
+ ),
+ False,
+ DoesNotRaise(),
+ ), # foreground object in 2 seperate elements
+ (
+ np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]).astype(
+ bool
+ ),
+ False,
+ DoesNotRaise(),
+ ), # no foreground pixels in mask
+ (
+ np.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]).astype(
+ bool
+ ),
+ False,
+ DoesNotRaise(),
+ ), # only foreground pixels in mask
+ (
+ np.array([[1, 1, 1, 0], [1, 0, 1, 0], [1, 1, 1, 0], [0, 0, 0, 0]]).astype(
+ bool
+ ),
+ True,
+ DoesNotRaise(),
+ ), # foreground object has 1 hole
+ (
+ np.array([[1, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1]]).astype(
+ bool
+ ),
+ True,
+ DoesNotRaise(),
+ ), # foreground object has 2 holes
+ ],
+)
+def test_contains_holes(
+ mask: npt.NDArray[np.bool_], expected_result: bool, exception: Exception
+) -> None:
+ with exception:
+ result = contains_holes(mask)
+ assert result == expected_result
+
+
+@pytest.mark.parametrize(
+ "mask, connectivity, expected_result, exception",
+ [
+ (
+ np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 1, 0]]).astype(
+ bool
+ ),
+ 4,
+ False,
+ DoesNotRaise(),
+ ), # foreground object in one continuous piece
+ (
+ np.array([[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0]]).astype(
+ bool
+ ),
+ 4,
+ True,
+ DoesNotRaise(),
+ ), # foreground object in 2 seperate elements
+ (
+ np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]).astype(
+ bool
+ ),
+ 4,
+ False,
+ DoesNotRaise(),
+ ), # no foreground pixels in mask
+ (
+ np.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]).astype(
+ bool
+ ),
+ 4,
+ False,
+ DoesNotRaise(),
+ ), # only foreground pixels in mask
+ (
+ np.array([[1, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1]]).astype(
+ bool
+ ),
+ 4,
+ False,
+ DoesNotRaise(),
+ ), # foreground object has 2 holes, but is in single piece
+ (
+ np.array([[1, 1, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 1]]).astype(
+ bool
+ ),
+ 4,
+ True,
+ DoesNotRaise(),
+ ), # foreground object in 2 elements with respect to 4-way connectivity
+ (
+ np.array([[1, 1, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 1]]).astype(
+ bool
+ ),
+ 8,
+ False,
+ DoesNotRaise(),
+ ), # foreground object in single piece with respect to 8-way connectivity
+ (
+ np.array([[1, 1, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 1]]).astype(
+ bool
+ ),
+ 5,
+ None,
+ pytest.raises(ValueError),
+ ), # Incorrect connectivity parameter value, raises ValueError
+ ],
+)
+def test_contains_multiple_segments(
+ mask: npt.NDArray[np.bool_],
+ connectivity: int,
+ expected_result: bool,
+ exception: Exception,
+) -> None:
+ with exception:
+ result = contains_multiple_segments(mask=mask, connectivity=connectivity)
+ assert result == expected_result
| diff --git a/docs/datasets.md b/docs/datasets/core.md
similarity index 97%
rename from docs/datasets.md
rename to docs/datasets/core.md
index 739315150..03d0c1966 100644
--- a/docs/datasets.md
+++ b/docs/datasets/core.md
@@ -1,5 +1,6 @@
---
comments: true
+status: new
---
# Datasets
diff --git a/docs/datasets/utils.md b/docs/datasets/utils.md
new file mode 100644
index 000000000..6be56303f
--- /dev/null
+++ b/docs/datasets/utils.md
@@ -0,0 +1,18 @@
+---
+comments: true
+status: new
+---
+
+# Datasets Utils
+
+<div class="md-typeset">
+ <h2><a href="#supervision.dataset.utils.rle_to_mask">rle_to_mask</a></h2>
+</div>
+
+:::supervision.dataset.utils.rle_to_mask
+
+<div class="md-typeset">
+ <h2><a href="#supervision.dataset.utils.mask_to_rle">mask_to_rle</a></h2>
+</div>
+
+:::supervision.dataset.utils.mask_to_rle
diff --git a/docs/detection/utils.md b/docs/detection/utils.md
index 5a9d2ba21..f9c9473bc 100644
--- a/docs/detection/utils.md
+++ b/docs/detection/utils.md
@@ -88,3 +88,15 @@ status: new
</div>
:::supervision.detection.utils.pad_boxes
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.utils.contains_holes">contains_holes</a></h2>
+</div>
+
+:::supervision.detection.utils.contains_holes
+
+<div class="md-typeset">
+ <h2><a href="#supervision.detection.utils.contains_multiple_segments">contains_multiple_segments</a></h2>
+</div>
+
+:::supervision.detection.utils.contains_multiple_segments
diff --git a/mkdocs.yml b/mkdocs.yml
index cf206a82e..281c40c97 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -61,7 +61,9 @@ nav:
- Detection Smoother: detection/tools/smoother.md
- Save Detections: detection/tools/save_detections.md
- Trackers: trackers.md
- - Datasets: datasets.md
+ - Datasets:
+ - Core: datasets/core.md
+ - Utils: datasets/utils.md
- Utils:
- Video: utils/video.md
- Image: utils/image.md
| [
{
"components": [
{
"doc": "",
"lines": [
67,
86
],
"name": "coco_annotations_to_masks",
"signature": "def coco_annotations_to_masks( image_annotations: List[dict], resolution_wh: Tuple[int, int] ) -> npt.NDArray[np.bool_]:",
"type": "fun... | [
"test/dataset/formats/test_coco.py::test_coco_categories_to_classes[coco_categories0-expected_result0-exception0]",
"test/dataset/formats/test_coco.py::test_coco_categories_to_classes[coco_categories1-expected_result1-exception1]",
"test/dataset/formats/test_coco.py::test_coco_categories_to_classes[coco_categor... | [] | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
1114 rle support for coco
# Description
PR adds support for the RLE format in the COCO dataset. Based on #1114 .
It required implementing RLE encode/decode functions and extending the _coco_annotations_to_detections_/_detections_to_coco_annotations_ functions.
## Type of change
Please delete options that are not relevant.
- [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?
All functionalities are covered with unit tests + [notebook](https://colab.research.google.com/drive/1xjnGh007xB-RbRAEqkaA4H2e-GtO_dd1?usp=sharing) checks the functionalities on larger images.
## Any specific deployment considerations
None
## Docs
- [x] Docs updated? What were the changes: `docs/datasets/utils.md`
----------
</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/coco.py]
(definition of coco_annotations_to_masks:)
def coco_annotations_to_masks( image_annotations: List[dict], resolution_wh: Tuple[int, int] ) -> npt.NDArray[np.bool_]:
[end of new definitions in supervision/dataset/formats/coco.py]
[start of new definitions in supervision/dataset/utils.py]
(definition of rle_to_mask:)
def rle_to_mask( rle: Union[npt.NDArray[np.int_], List[int]], resolution_wh: Tuple[int, int] ) -> npt.NDArray[np.bool_]:
"""Converts run-length encoding (RLE) to a binary mask.
Args:
rle (Union[npt.NDArray[np.int_], List[int]]): The 1D RLE array, the format
used in the COCO dataset (column-wise encoding, values of an array with
even indices represent the number of pixels assigned as background,
values of an array with odd indices represent the number of pixels
assigned as foreground object).
resolution_wh (Tuple[int, int]): The width (w) and height (h)
of the desired binary mask.
Returns:
The generated 2D Boolean mask of shape `(h, w)`, where the foreground object is
marked with `True`'s and the rest is filled with `False`'s.
Raises:
AssertionError: If the sum of pixels encoded in RLE differs from the
number of pixels in the expected mask (computed based on resolution_wh).
Examples:
```python
import supervision as sv
sv.rle_to_mask([5, 2, 2, 2, 5], (4, 4))
# array([
# [False, False, False, False],
# [False, True, True, False],
# [False, True, True, False],
# [False, False, False, False],
# ])
```"""
(definition of mask_to_rle:)
def mask_to_rle(mask: npt.NDArray[np.bool_]) -> List[int]:
"""Converts a binary mask into a run-length encoding (RLE).
Args:
mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
object and `False` indicates background.
Returns:
The run-length encoded mask. Values of a list with even indices
represent the number of pixels assigned as background (`False`), values
of a list with odd indices represent the number of pixels assigned
as foreground object (`True`).
Raises:
AssertionError: If input mask is not 2D or is empty.
Examples:
```python
import numpy as np
import supervision as sv
mask = np.array([
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
[True, True, True, True],
])
sv.mask_to_rle(mask)
# [0, 16]
mask = np.array([
[False, False, False, False],
[False, True, True, False],
[False, True, True, False],
[False, False, False, False],
])
sv.mask_to_rle(mask)
# [5, 2, 2, 2, 5]
```
{ align=center width="800" }"""
[end of new definitions in supervision/dataset/utils.py]
[start of new definitions in supervision/detection/utils.py]
(definition of contains_holes:)
def contains_holes(mask: npt.NDArray[np.bool_]) -> bool:
"""Checks if the binary mask contains holes (background pixels fully enclosed by
foreground pixels).
Args:
mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
object and `False` indicates background.
Returns:
True if holes are detected, False otherwise.
Examples:
```python
import numpy as np
import supervision as sv
mask = np.array([
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]).astype(bool)
sv.contains_holes(mask=mask)
# True
mask = np.array([
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]).astype(bool)
sv.contains_holes(mask=mask)
# False
```
{ align=center width="800" }"""
(definition of contains_multiple_segments:)
def contains_multiple_segments( mask: npt.NDArray[np.bool_], connectivity: int = 4 ) -> bool:
"""Checks if the binary mask contains multiple unconnected foreground segments.
Args:
mask (npt.NDArray[np.bool_]): 2D binary mask where `True` indicates foreground
object and `False` indicates background.
connectivity (int) : Default: 4 is 4-way connectivity, which means that
foreground pixels are the part of the same segment/component
if their edges touch.
Alternatively: 8 for 8-way connectivity, when foreground pixels are
connected by their edges or corners touch.
Returns:
True when the mask contains multiple not connected components, False otherwise.
Raises:
ValueError: If connectivity(int) parameter value is not 4 or 8.
Examples:
```python
import numpy as np
import supervision as sv
mask = np.array([
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 1],
[0, 1, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0]
]).astype(bool)
sv.contains_multiple_segments(mask=mask, connectivity=4)
# True
mask = np.array([
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0]
]).astype(bool)
sv.contains_multiple_segments(mask=mask, connectivity=4)
# False
```
{ align=center width="800" }"""
[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 | |
conan-io__conan-16195 | 16,195 | conan-io/conan | null | 3a076230550ee48998c4c9db6c817969d83ee386 | 2024-05-02T22:33:12Z | diff --git a/conans/model/info.py b/conans/model/info.py
index 95e7862f5f4..04cf50d47e2 100644
--- a/conans/model/info.py
+++ b/conans/model/info.py
@@ -149,6 +149,14 @@ def full_package_mode(self):
self.package_id = self._package_id
self.recipe_revision = None
+ def revision_mode(self):
+ self.name = self._ref.name
+ self.version = self._ref.version
+ self.user = self._ref.user
+ self.channel = self._ref.channel
+ self.package_id = None
+ self.recipe_revision = self._ref.revision
+
def full_mode(self):
self.name = self._ref.name
self.version = self._ref.version
@@ -223,6 +231,10 @@ def full_package_mode(self):
for r in self._data.values():
r.full_package_mode()
+ def revision_mode(self):
+ for r in self._data.values():
+ r.revision_mode()
+
def full_mode(self):
for r in self._data.values():
r.full_mode()
@@ -285,6 +297,10 @@ def full_recipe_mode(self):
for r in self._refs:
r.full_recipe_mode()
+ def revision_mode(self):
+ for r in self._refs:
+ r.revision_mode()
+
def full_mode(self):
for r in self._refs:
r.full_mode()
| diff --git a/conans/test/integration/package_id/test_config_package_id.py b/conans/test/integration/package_id/test_config_package_id.py
index ec077e65254..9932497dd10 100644
--- a/conans/test/integration/package_id/test_config_package_id.py
+++ b/conans/test/integration/package_id/test_config_package_id.py
@@ -11,6 +11,7 @@
("myconfig/1.2.3#rev1:pid1#prev1", "minor_mode", "myconfig/1.2.Z"),
("myconfig/1.2.3#rev1:pid1#prev1", "patch_mode", "myconfig/1.2.3"),
("myconfig/1.2.3#rev1:pid1#prev1", "full_mode", "myconfig/1.2.3#rev1:pid1"),
+ ("myconfig/1.2.3#rev1:pid1#prev1", "revision_mode", "myconfig/1.2.3#rev1"),
("myconfig/1.2.3", "minor_mode", "myconfig/1.2.Z")])
def test_config_package_id(config_version, mode, result):
c = TestClient()
@@ -24,7 +25,8 @@ def test_config_package_id(config_version, mode, result):
rrev = info["Local Cache"]["pkg/0.1"]["revisions"]["485dad6cb11e2fa99d9afbe44a57a164"]
package_id = {"myconfig/1.2.Z": "c78b4d8224154390356fe04fe598d67aec930199",
"myconfig/1.2.3": "60005f5b11bef3ddd686b13f5c6bf576a9b882b8",
- "myconfig/1.2.3#rev1:pid1": "b1525975eb5420cef45b4ddd1544f87c29c773a5"}
+ "myconfig/1.2.3#rev1:pid1": "b1525975eb5420cef45b4ddd1544f87c29c773a5",
+ "myconfig/1.2.3#rev1": "aae875ae226416f177bf386a3e4ad6aaffce09e7"}
package_id = package_id.get(result)
pkg = rrev["packages"][package_id]
assert pkg["info"] == {"config_version": [result]}
| [
{
"components": [
{
"doc": "",
"lines": [
152,
158
],
"name": "RequirementInfo.revision_mode",
"signature": "def revision_mode(self):",
"type": "function"
},
{
"doc": "",
"lines": [
234,
236... | [
"conans/test/integration/package_id/test_config_package_id.py::test_config_package_id[myconfig/1.2.3#rev1:pid1#prev1-revision_mode-myconfig/1.2.3#rev1]"
] | [
"conans/test/integration/package_id/test_config_package_id.py::test_config_package_id[myconfig/1.2.3#rev1:pid1#prev1-minor_mode-myconfig/1.2.Z]",
"conans/test/integration/package_id/test_config_package_id.py::test_config_package_id[myconfig/1.2.3#rev1:pid1#prev1-patch_mode-myconfig/1.2.3]",
"conans/test/integra... | This is a feature request which requires a new feature to add in the code repository.
<<NEW FEATURE REQUEST>>
<request>
new revision_mode
Changelog: Feature: Add new ``revision_mode`` including everything down to the ``recipe-revision``, but not the ``package_id``.
Docs: https://github.com/conan-io/docs/pull/3754
Close https://github.com/conan-io/conan/issues/16114
----------
</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/info.py]
(definition of RequirementInfo.revision_mode:)
def revision_mode(self):
(definition of RequirementsInfo.revision_mode:)
def revision_mode(self):
(definition of PythonRequiresInfo.revision_mode:)
def revision_mode(self):
[end of new definitions in conans/model/info.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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.