🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
feat: rm swe-bench-dev.json
莘权 马005be3cfedd8
diff --git a/tests/data/swe-bench/swe-bench-dev.json b/tests/data/swe-bench/swe-bench-dev.jsondeleted file mode 100644index 2b9a0de81..000000000--- a/tests/data/swe-bench/swe-bench-dev.json+++ /dev/null@@ -1 +0,0 @@-[{"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4764", "base_commit": "a820c139ccbe6d1865d73c4a459945cd69899f8f", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -44,6 +44,7 @@\n dialect_selector,\n dialect_readout,\n )\n+from sqlfluff.core.linter import LintingResult\n from sqlfluff.core.config import progress_bar_configuration\n \n from sqlfluff.core.enums import FormatType, Color\n@@ -691,12 +692,16 @@ def lint(\n sys.exit(EXIT_SUCCESS)\n \n \n-def do_fixes(lnt, result, formatter=None, **kwargs):\n+def do_fixes(\n+ result: LintingResult, formatter: Optional[OutputStreamFormatter] = None, **kwargs\n+):\n \"\"\"Actually do the fixes.\"\"\"\n- click.echo(\"Persisting Changes...\")\n+ if formatter and formatter.verbosity >= 0:\n+ click.echo(\"Persisting Changes...\")\n res = result.persist_changes(formatter=formatter, **kwargs)\n if all(res.values()):\n- click.echo(\"Done. Please check your files to confirm.\")\n+ if formatter and formatter.verbosity >= 0:\n+ click.echo(\"Done. Please check your files to confirm.\")\n return True\n # If some failed then return false\n click.echo(\n@@ -708,7 +713,7 @@ def do_fixes(lnt, result, formatter=None, **kwargs):\n return False # pragma: no cover\n \n \n-def _stdin_fix(linter, formatter, fix_even_unparsable):\n+def _stdin_fix(linter: Linter, formatter, fix_even_unparsable):\n \"\"\"Handle fixing from stdin.\"\"\"\n exit_code = EXIT_SUCCESS\n stdin = sys.stdin.read()\n@@ -751,7 +756,7 @@ def _stdin_fix(linter, formatter, fix_even_unparsable):\n \n \n def _paths_fix(\n- linter,\n+ linter: Linter,\n formatter,\n paths,\n processes,\n@@ -765,11 +770,12 @@ def _paths_fix(\n ):\n \"\"\"Handle fixing from paths.\"\"\"\n # Lint the paths (not with the fix argument at this stage), outputting as we go.\n- click.echo(\"==== finding fixable violations ====\")\n+ if formatter.verbosity >= 0:\n+ click.echo(\"==== finding fixable violations ====\")\n exit_code = EXIT_SUCCESS\n \n with PathAndUserErrorHandler(formatter):\n- result = linter.lint_paths(\n+ result: LintingResult = linter.lint_paths(\n paths,\n fix=True,\n ignore_non_existent_files=False,\n@@ -781,20 +787,18 @@ def _paths_fix(\n \n # NB: We filter to linting violations here, because they're\n # the only ones which can be potentially fixed.\n- if result.num_violations(types=SQLLintError, fixable=True) > 0:\n- click.echo(\"==== fixing violations ====\")\n- click.echo(\n- f\"{result.num_violations(types=SQLLintError, fixable=True)} fixable \"\n- \"linting violations found\"\n- )\n+ num_fixable = result.num_violations(types=SQLLintError, fixable=True)\n+ if num_fixable > 0:\n+ if formatter.verbosity >= 0:\n+ click.echo(\"==== fixing violations ====\")\n+ click.echo(f\"{num_fixable} \" \"fixable linting violations found\")\n if force:\n- if warn_force:\n+ if warn_force and formatter.verbosity >= 0:\n click.echo(\n f\"{formatter.colorize('FORCE MODE', Color.red)}: \"\n \"Attempting fixes...\"\n )\n success = do_fixes(\n- linter,\n result,\n formatter,\n types=SQLLintError,\n@@ -809,9 +813,9 @@ def _paths_fix(\n c = click.getchar().lower()\n click.echo(\"...\")\n if c in (\"y\", \"\\r\", \"\\n\"):\n- click.echo(\"Attempting fixes...\")\n+ if formatter.verbosity >= 0:\n+ click.echo(\"Attempting fixes...\")\n success = do_fixes(\n- linter,\n result,\n formatter,\n types=SQLLintError,\n@@ -829,8 +833,9 @@ def _paths_fix(\n click.echo(\"Aborting...\")\n exit_code = EXIT_FAIL\n else:\n- click.echo(\"==== no fixable linting violations found ====\")\n- formatter.completion_message()\n+ if formatter.verbosity >= 0:\n+ click.echo(\"==== no fixable linting violations found ====\")\n+ formatter.completion_message()\n \n error_types = [\n (\n@@ -841,7 +846,7 @@ def _paths_fix(\n ]\n for num_violations_kwargs, message_format, error_level in error_types:\n num_violations = result.num_violations(**num_violations_kwargs)\n- if num_violations > 0:\n+ if num_violations > 0 and formatter.verbosity >= 0:\n click.echo(message_format.format(num_violations))\n exit_code = max(exit_code, error_level)\n \n@@ -880,10 +885,20 @@ def _paths_fix(\n \"--force\",\n is_flag=True,\n help=(\n- \"skip the confirmation prompt and go straight to applying \"\n+ \"Skip the confirmation prompt and go straight to applying \"\n \"fixes. **Use this with caution.**\"\n ),\n )\[email protected](\n+ \"-q\",\n+ \"--quiet\",\n+ is_flag=True,\n+ help=(\n+ \"Reduces the amount of output to stdout to a minimal level. \"\n+ \"This is effectively the opposite of -v. NOTE: It will only \"\n+ \"take effect if -f/--force is also set.\"\n+ ),\n+)\n @click.option(\n \"-x\",\n \"--fixed-suffix\",\n@@ -913,6 +928,7 @@ def fix(\n force: bool,\n paths: Tuple[str],\n bench: bool = False,\n+ quiet: bool = False,\n fixed_suffix: str = \"\",\n logger: Optional[logging.Logger] = None,\n processes: Optional[int] = None,\n@@ -932,6 +948,13 @@ def fix(\n \"\"\"\n # some quick checks\n fixing_stdin = (\"-\",) == paths\n+ if quiet:\n+ if kwargs[\"verbose\"]:\n+ click.echo(\n+ \"ERROR: The --quiet flag can only be used if --verbose is not set.\",\n+ )\n+ sys.exit(EXIT_ERROR)\n+ kwargs[\"verbose\"] = -1\n \n config = get_config(\n extra_config_path, ignore_local_config, require_dialect=False, **kwargs\ndiff --git a/src/sqlfluff/cli/formatters.py b/src/sqlfluff/cli/formatters.py\n--- a/src/sqlfluff/cli/formatters.py\n+++ b/src/sqlfluff/cli/formatters.py\n@@ -94,7 +94,7 @@ def __init__(\n ):\n self._output_stream = output_stream\n self.plain_output = self.should_produce_plain_output(nocolor)\n- self._verbosity = verbosity\n+ self.verbosity = verbosity\n self._filter_empty = filter_empty\n self.output_line_length = output_line_length\n \n@@ -116,13 +116,13 @@ def _format_config(self, linter: Linter) -> str:\n \"\"\"Format the config of a `Linter`.\"\"\"\n text_buffer = StringIO()\n # Only show version information if verbosity is high enough\n- if self._verbosity > 0:\n+ if self.verbosity > 0:\n text_buffer.write(\"==== sqlfluff ====\\n\")\n config_content = [\n (\"sqlfluff\", get_package_version()),\n (\"python\", get_python_version()),\n (\"implementation\", get_python_implementation()),\n- (\"verbosity\", self._verbosity),\n+ (\"verbosity\", self.verbosity),\n ]\n if linter.dialect:\n config_content.append((\"dialect\", linter.dialect.name))\n@@ -138,7 +138,7 @@ def _format_config(self, linter: Linter) -> str:\n col_width=41,\n )\n )\n- if self._verbosity > 1:\n+ if self.verbosity > 1:\n text_buffer.write(\"\\n== Raw Config:\\n\")\n text_buffer.write(self.format_config_vals(linter.config.iter_vals()))\n return text_buffer.getvalue()\n@@ -150,7 +150,7 @@ def dispatch_config(self, linter: Linter) -> None:\n def dispatch_persist_filename(self, filename, result):\n \"\"\"Dispatch filenames during a persist operation.\"\"\"\n # Only show the skip records at higher levels of verbosity\n- if self._verbosity >= 2 or result != \"SKIP\":\n+ if self.verbosity >= 2 or result != \"SKIP\":\n self._dispatch(self.format_filename(filename=filename, success=result))\n \n def _format_path(self, path: str) -> str:\n@@ -159,14 +159,14 @@ def _format_path(self, path: str) -> str:\n \n def dispatch_path(self, path: str) -> None:\n \"\"\"Dispatch paths for display.\"\"\"\n- if self._verbosity > 0:\n+ if self.verbosity > 0:\n self._dispatch(self._format_path(path))\n \n def dispatch_template_header(\n self, fname: str, linter_config: FluffConfig, file_config: FluffConfig\n ) -> None:\n \"\"\"Dispatch the header displayed before templating.\"\"\"\n- if self._verbosity > 1:\n+ if self.verbosity > 1:\n self._dispatch(self.format_filename(filename=fname, success=\"TEMPLATING\"))\n # This is where we output config diffs if they exist.\n if file_config:\n@@ -182,12 +182,12 @@ def dispatch_template_header(\n \n def dispatch_parse_header(self, fname: str) -> None:\n \"\"\"Dispatch the header displayed before parsing.\"\"\"\n- if self._verbosity > 1:\n+ if self.verbosity > 1:\n self._dispatch(self.format_filename(filename=fname, success=\"PARSING\"))\n \n def dispatch_lint_header(self, fname: str, rules: List[str]) -> None:\n \"\"\"Dispatch the header displayed before linting.\"\"\"\n- if self._verbosity > 1:\n+ if self.verbosity > 1:\n self._dispatch(\n self.format_filename(\n filename=fname, success=f\"LINTING ({', '.join(rules)})\"\n@@ -202,7 +202,7 @@ def dispatch_compilation_header(self, templater, message):\n \n def dispatch_processing_header(self, processes: int) -> None:\n \"\"\"Dispatch the header displayed before linting.\"\"\"\n- if self._verbosity > 0:\n+ if self.verbosity > 0:\n self._dispatch( # pragma: no cover\n f\"{self.colorize('effective configured processes: ', Color.lightgrey)} \"\n f\"{processes}\"\n@@ -228,7 +228,7 @@ def _format_file_violations(\n show = fails + warns > 0\n \n # Only print the filename if it's either a failure or verbosity > 1\n- if self._verbosity > 0 or show:\n+ if self.verbosity > 0 or show:\n text_buffer.write(self.format_filename(fname, success=fails == 0))\n text_buffer.write(\"\\n\")\n \n@@ -253,6 +253,8 @@ def dispatch_file_violations(\n self, fname: str, linted_file: LintedFile, only_fixable: bool\n ) -> None:\n \"\"\"Dispatch any violations found in a file.\"\"\"\n+ if self.verbosity < 0:\n+ return\n s = self._format_file_violations(\n fname,\n linted_file.get_violations(\n@@ -392,10 +394,13 @@ def format_filename(\n if isinstance(success, str):\n status_string = success\n else:\n- status_string = self.colorize(\n- success_text if success else \"FAIL\",\n- Color.green if success else Color.red,\n- )\n+ status_string = success_text if success else \"FAIL\"\n+\n+ if status_string in (\"PASS\", \"FIXED\", success_text):\n+ status_string = self.colorize(status_string, Color.green)\n+ elif status_string in (\"FAIL\", \"ERROR\"):\n+ status_string = self.colorize(status_string, Color.red)\n+\n return f\"== [{self.colorize(filename, Color.lightgrey)}] {status_string}\"\n \n def format_violation(\ndiff --git a/src/sqlfluff/core/linter/linted_dir.py b/src/sqlfluff/core/linter/linted_dir.py\n--- a/src/sqlfluff/core/linter/linted_dir.py\n+++ b/src/sqlfluff/core/linter/linted_dir.py\n@@ -117,7 +117,11 @@ def persist_changes(\n for file in self.files:\n if file.num_violations(fixable=True, **kwargs) > 0:\n buffer[file.path] = file.persist_tree(suffix=fixed_file_suffix)\n- result = buffer[file.path]\n+ result: Union[bool, str]\n+ if buffer[file.path] is True:\n+ result = \"FIXED\"\n+ else: # pragma: no cover\n+ result = buffer[file.path]\n else: # pragma: no cover TODO?\n buffer[file.path] = True\n result = \"SKIP\"\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -557,6 +557,18 @@ def test__cli__command_lint_parse(command):\n ),\n 1,\n ),\n+ # Test that setting --quiet with --verbose raises an error.\n+ (\n+ (\n+ fix,\n+ [\n+ \"--quiet\",\n+ \"--verbose\",\n+ \"test/fixtures/cli/fail_many.sql\",\n+ ],\n+ ),\n+ 2,\n+ ),\n ],\n )\n def test__cli__command_lint_parse_with_retcode(command, ret_code):\n@@ -1891,7 +1903,7 @@ def test_cli_fix_disabled_progress_bar_deprecated_option(\n \n \n def test__cli__fix_multiple_errors_no_show_errors():\n- \"\"\"Basic checking of lint functionality.\"\"\"\n+ \"\"\"Test the fix output.\"\"\"\n result = invoke_assert_code(\n ret_code=1,\n args=[\n@@ -1910,8 +1922,57 @@ def test__cli__fix_multiple_errors_no_show_errors():\n assert result.output.replace(\"\\\\\", \"/\").startswith(multiple_expected_output)\n \n \n+def test__cli__fix_multiple_errors_quiet_force():\n+ \"\"\"Test the fix --quiet option with --force.\"\"\"\n+ result = invoke_assert_code(\n+ ret_code=0,\n+ args=[\n+ fix,\n+ [\n+ \"--disable-progress-bar\",\n+ \"test/fixtures/linter/multiple_sql_errors.sql\",\n+ \"--force\",\n+ \"--quiet\",\n+ \"-x\",\n+ \"_fix\",\n+ ],\n+ ],\n+ )\n+ normalised_output = result.output.replace(\"\\\\\", \"/\")\n+ assert normalised_output.startswith(\n+ \"\"\"1 fixable linting violations found\n+== [test/fixtures/linter/multiple_sql_errors.sql] FIXED\"\"\"\n+ )\n+\n+\n+def test__cli__fix_multiple_errors_quiet_no_force():\n+ \"\"\"Test the fix --quiet option without --force.\"\"\"\n+ result = invoke_assert_code(\n+ ret_code=0,\n+ args=[\n+ fix,\n+ [\n+ \"--disable-progress-bar\",\n+ \"test/fixtures/linter/multiple_sql_errors.sql\",\n+ \"--quiet\",\n+ \"-x\",\n+ \"_fix\",\n+ ],\n+ # Test with the confirmation step.\n+ \"y\",\n+ ],\n+ )\n+ normalised_output = result.output.replace(\"\\\\\", \"/\")\n+ assert normalised_output.startswith(\n+ \"\"\"1 fixable linting violations found\n+Are you sure you wish to attempt to fix these? [Y/n] ...\n+== [test/fixtures/linter/multiple_sql_errors.sql] FIXED\n+All Finished\"\"\"\n+ )\n+\n+\n def test__cli__fix_multiple_errors_show_errors():\n- \"\"\"Basic checking of lint functionality.\"\"\"\n+ \"\"\"Test the fix --show-lint-violations option.\"\"\"\n result = invoke_assert_code(\n ret_code=1,\n args=[\n", "problem_statement": "Enable quiet mode/no-verbose in CLI for use in pre-commit hook\nThere seems to be only an option to increase the level of verbosity when using SQLFluff [CLI](https://docs.sqlfluff.com/en/stable/cli.html), not to limit it further.\r\n\r\nIt would be great to have an option to further limit the amount of prints when running `sqlfluff fix`, especially in combination with deployment using a pre-commit hook. For example, only print the return status and the number of fixes applied, similar to how it is when using `black` in a pre-commit hook:\r\n\r\n\r\nThis hides the potentially long list of fixes that are being applied to the SQL files, which can get quite verbose.\n", "hints_text": "", "created_at": "2023-04-16T14:24:42Z", "version": "1.4", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_force", "test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_no_force"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse[command26]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command5-2]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command6-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command7-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command8-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command9-2]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_lint_warning", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql0]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql1]", "test/cli/commands_test.py::test__cli__command__fix[LT02-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_format_stdin[select", "test/cli/commands_test.py::test__cli__command_format_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass"], "environment_setup_commit": "d19de0ecd16d298f9e3bfb91da122734c40c01e5"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2862", "base_commit": "447ecf862a4d2b977d0add9f444655357b9c4f1f", "patch": "diff --git a/src/sqlfluff/core/linter/common.py b/src/sqlfluff/core/linter/common.py\n--- a/src/sqlfluff/core/linter/common.py\n+++ b/src/sqlfluff/core/linter/common.py\n@@ -67,21 +67,3 @@ class ParsedString(NamedTuple):\n config: FluffConfig\n fname: str\n source_str: str\n-\n-\n-class EnrichedFixPatch(NamedTuple):\n- \"\"\"An edit patch for a source file.\"\"\"\n-\n- source_slice: slice\n- templated_slice: slice\n- fixed_raw: str\n- # The patch category, functions mostly for debugging and explanation\n- # than for function. It allows traceability of *why* this patch was\n- # generated.\n- patch_category: str\n- templated_str: str\n- source_str: str\n-\n- def dedupe_tuple(self):\n- \"\"\"Generate a tuple of this fix for deduping.\"\"\"\n- return (self.source_slice, self.fixed_raw)\ndiff --git a/src/sqlfluff/core/linter/linted_file.py b/src/sqlfluff/core/linter/linted_file.py\n--- a/src/sqlfluff/core/linter/linted_file.py\n+++ b/src/sqlfluff/core/linter/linted_file.py\n@@ -30,9 +30,9 @@\n from sqlfluff.core.templaters import TemplatedFile\n \n # Classes needed only for type checking\n-from sqlfluff.core.parser.segments.base import BaseSegment, FixPatch\n+from sqlfluff.core.parser.segments.base import BaseSegment, FixPatch, EnrichedFixPatch\n \n-from sqlfluff.core.linter.common import NoQaDirective, EnrichedFixPatch\n+from sqlfluff.core.linter.common import NoQaDirective\n \n # Instantiate the linter logger\n linter_logger: logging.Logger = logging.getLogger(\"sqlfluff.linter\")\n@@ -203,9 +203,7 @@ def is_clean(self) -> bool:\n return not any(self.get_violations(filter_ignore=True))\n \n @staticmethod\n- def _log_hints(\n- patch: Union[EnrichedFixPatch, FixPatch], templated_file: TemplatedFile\n- ):\n+ def _log_hints(patch: FixPatch, templated_file: TemplatedFile):\n \"\"\"Log hints for debugging during patch generation.\"\"\"\n # This next bit is ALL FOR LOGGING AND DEBUGGING\n max_log_length = 10\n@@ -279,18 +277,16 @@ def fix_string(self) -> Tuple[Any, bool]:\n dedupe_buffer = []\n # We use enumerate so that we get an index for each patch. This is entirely\n # so when debugging logs we can find a given patch again!\n- patch: Union[EnrichedFixPatch, FixPatch]\n+ patch: FixPatch # Could be FixPatch or its subclass, EnrichedFixPatch\n for idx, patch in enumerate(\n- self.tree.iter_patches(templated_str=self.templated_file.templated_str)\n+ self.tree.iter_patches(templated_file=self.templated_file)\n ):\n linter_logger.debug(\" %s Yielded patch: %s\", idx, patch)\n self._log_hints(patch, self.templated_file)\n \n- # Attempt to convert to source space.\n+ # Get source_slice.\n try:\n- source_slice = self.templated_file.templated_slice_to_source_slice(\n- patch.templated_slice,\n- )\n+ enriched_patch = patch.enrich(self.templated_file)\n except ValueError: # pragma: no cover\n linter_logger.info(\n \" - Skipping. Source space Value Error. i.e. attempted \"\n@@ -301,10 +297,10 @@ def fix_string(self) -> Tuple[Any, bool]:\n continue\n \n # Check for duplicates\n- dedupe_tuple = (source_slice, patch.fixed_raw)\n- if dedupe_tuple in dedupe_buffer:\n+ if enriched_patch.dedupe_tuple() in dedupe_buffer:\n linter_logger.info(\n- \" - Skipping. Source space Duplicate: %s\", dedupe_tuple\n+ \" - Skipping. Source space Duplicate: %s\",\n+ enriched_patch.dedupe_tuple(),\n )\n continue\n \n@@ -318,19 +314,10 @@ def fix_string(self) -> Tuple[Any, bool]:\n \n # Get the affected raw slices.\n local_raw_slices = self.templated_file.raw_slices_spanning_source_slice(\n- source_slice\n+ enriched_patch.source_slice\n )\n local_type_list = [slc.slice_type for slc in local_raw_slices]\n \n- enriched_patch = EnrichedFixPatch(\n- source_slice=source_slice,\n- templated_slice=patch.templated_slice,\n- patch_category=patch.patch_category,\n- fixed_raw=patch.fixed_raw,\n- templated_str=self.templated_file.templated_str[patch.templated_slice],\n- source_str=self.templated_file.source_str[source_slice],\n- )\n-\n # Deal with the easy cases of 1) New code at end 2) only literals\n if not local_type_list or set(local_type_list) == {\"literal\"}:\n linter_logger.info(\ndiff --git a/src/sqlfluff/core/parser/lexer.py b/src/sqlfluff/core/parser/lexer.py\n--- a/src/sqlfluff/core/parser/lexer.py\n+++ b/src/sqlfluff/core/parser/lexer.py\n@@ -535,6 +535,31 @@ def elements_to_segments(\n )\n )\n \n+ # Generate placeholders for any source-only slices that *follow*\n+ # the last element. This happens, for example, if a Jinja templated\n+ # file ends with \"{% endif %}\", and there's no trailing newline.\n+ if idx == len(elements) - 1:\n+ so_slices = [\n+ so\n+ for so in source_only_slices\n+ if so.source_idx >= source_slice.stop\n+ ]\n+ for so_slice in so_slices:\n+ segment_buffer.append(\n+ TemplateSegment(\n+ pos_marker=PositionMarker(\n+ slice(so_slice.source_idx, so_slice.end_source_idx()),\n+ slice(\n+ element.template_slice.stop,\n+ element.template_slice.stop,\n+ ),\n+ templated_file,\n+ ),\n+ source_str=so_slice.raw,\n+ block_type=so_slice.slice_type,\n+ )\n+ )\n+\n # Convert to tuple before return\n return tuple(segment_buffer)\n \ndiff --git a/src/sqlfluff/core/parser/segments/base.py b/src/sqlfluff/core/parser/segments/base.py\n--- a/src/sqlfluff/core/parser/segments/base.py\n+++ b/src/sqlfluff/core/parser/segments/base.py\n@@ -13,7 +13,16 @@\n from copy import deepcopy\n from dataclasses import dataclass, field, replace\n from io import StringIO\n-from typing import Any, Callable, Dict, Optional, List, Tuple, NamedTuple, Iterator\n+from typing import (\n+ Any,\n+ Callable,\n+ Dict,\n+ Optional,\n+ List,\n+ Tuple,\n+ Iterator,\n+ Union,\n+)\n import logging\n \n from tqdm import tqdm\n@@ -36,21 +45,54 @@\n from sqlfluff.core.parser.matchable import Matchable\n from sqlfluff.core.parser.markers import PositionMarker\n from sqlfluff.core.parser.context import ParseContext\n+from sqlfluff.core.templaters.base import TemplatedFile\n \n # Instantiate the linter logger (only for use in methods involved with fixing.)\n linter_logger = logging.getLogger(\"sqlfluff.linter\")\n \n \n-class FixPatch(NamedTuple):\n+@dataclass\n+class FixPatch:\n \"\"\"An edit patch for a templated file.\"\"\"\n \n templated_slice: slice\n fixed_raw: str\n # The patch category, functions mostly for debugging and explanation\n # than for function. It allows traceability of *why* this patch was\n- # generated. It has no siginificance for processing.\n+ # generated. It has no significance for processing.\n patch_category: str\n \n+ def enrich(self, templated_file: TemplatedFile) -> \"EnrichedFixPatch\":\n+ \"\"\"Convert patch to source space.\"\"\"\n+ source_slice = templated_file.templated_slice_to_source_slice(\n+ self.templated_slice,\n+ )\n+ return EnrichedFixPatch(\n+ source_slice=source_slice,\n+ templated_slice=self.templated_slice,\n+ patch_category=self.patch_category,\n+ fixed_raw=self.fixed_raw,\n+ templated_str=templated_file.templated_str[self.templated_slice],\n+ source_str=templated_file.source_str[source_slice],\n+ )\n+\n+\n+@dataclass\n+class EnrichedFixPatch(FixPatch):\n+ \"\"\"An edit patch for a source file.\"\"\"\n+\n+ source_slice: slice\n+ templated_str: str\n+ source_str: str\n+\n+ def enrich(self, templated_file: TemplatedFile) -> \"EnrichedFixPatch\":\n+ \"\"\"No-op override of base class function.\"\"\"\n+ return self\n+\n+ def dedupe_tuple(self):\n+ \"\"\"Generate a tuple of this fix for deduping.\"\"\"\n+ return (self.source_slice, self.fixed_raw)\n+\n \n @dataclass\n class AnchorEditInfo:\n@@ -1176,7 +1218,9 @@ def _validate_segment_after_fixes(self, rule_code, dialect, fixes_applied, segme\n def _log_apply_fixes_check_issue(message, *args): # pragma: no cover\n linter_logger.critical(message, *args)\n \n- def iter_patches(self, templated_str: str) -> Iterator[FixPatch]:\n+ def iter_patches(\n+ self, templated_file: TemplatedFile\n+ ) -> Iterator[Union[EnrichedFixPatch, FixPatch]]:\n \"\"\"Iterate through the segments generating fix patches.\n \n The patches are generated in TEMPLATED space. This is important\n@@ -1188,6 +1232,7 @@ def iter_patches(self, templated_str: str) -> Iterator[FixPatch]:\n \"\"\"\n # Does it match? If so we can ignore it.\n assert self.pos_marker\n+ templated_str = templated_file.templated_str\n matches = self.raw == templated_str[self.pos_marker.templated_slice]\n if matches:\n return\n@@ -1256,7 +1301,7 @@ def iter_patches(self, templated_str: str) -> Iterator[FixPatch]:\n insert_buff = \"\"\n \n # Now we deal with any changes *within* the segment itself.\n- yield from segment.iter_patches(templated_str=templated_str)\n+ yield from segment.iter_patches(templated_file=templated_file)\n \n # Once we've dealt with any patches from the segment, update\n # our position markers.\n@@ -1266,13 +1311,22 @@ def iter_patches(self, templated_str: str) -> Iterator[FixPatch]:\n # or insert. Also valid if we still have an insertion buffer here.\n end_diff = self.pos_marker.templated_slice.stop - templated_idx\n if end_diff or insert_buff:\n- yield FixPatch(\n- slice(\n- self.pos_marker.templated_slice.stop - end_diff,\n- self.pos_marker.templated_slice.stop,\n- ),\n- insert_buff,\n+ source_slice = segment.pos_marker.source_slice\n+ templated_slice = slice(\n+ self.pos_marker.templated_slice.stop - end_diff,\n+ self.pos_marker.templated_slice.stop,\n+ )\n+ # By returning an EnrichedFixPatch (rather than FixPatch), which\n+ # includes a source_slice field, we ensure that fixes adjacent\n+ # to source-only slices (e.g. {% endif %}) are placed\n+ # appropriately relative to source-only slices.\n+ yield EnrichedFixPatch(\n+ source_slice=source_slice,\n+ templated_slice=templated_slice,\n patch_category=\"end_point\",\n+ fixed_raw=insert_buff,\n+ templated_str=templated_file.templated_str[templated_slice],\n+ source_str=templated_file.source_str[source_slice],\n )\n \n def edit(self, raw):\ndiff --git a/src/sqlfluff/core/rules/base.py b/src/sqlfluff/core/rules/base.py\n--- a/src/sqlfluff/core/rules/base.py\n+++ b/src/sqlfluff/core/rules/base.py\n@@ -656,16 +656,18 @@ def indent(self) -> str:\n space = \" \"\n return space * self.tab_space_size if self.indent_unit == \"space\" else tab\n \n- def is_final_segment(self, context: RuleContext) -> bool:\n+ def is_final_segment(self, context: RuleContext, filter_meta: bool = True) -> bool:\n \"\"\"Is the current segment the final segment in the parse tree.\"\"\"\n- if len(self.filter_meta(context.siblings_post)) > 0:\n+ siblings_post = context.siblings_post\n+ if filter_meta:\n+ siblings_post = self.filter_meta(siblings_post)\n+ if len(siblings_post) > 0:\n # This can only fail on the last segment\n return False\n elif len(context.segment.segments) > 0:\n # This can only fail on the last base segment\n return False\n- elif context.segment.is_meta:\n- # We can't fail on a meta segment\n+ elif filter_meta and context.segment.is_meta:\n return False\n else:\n # We know we are at a leaf of the tree but not necessarily at the end of the\n@@ -674,9 +676,9 @@ def is_final_segment(self, context: RuleContext) -> bool:\n # one.\n child_segment = context.segment\n for parent_segment in context.parent_stack[::-1]:\n- possible_children = [\n- s for s in parent_segment.segments if not s.is_meta\n- ]\n+ possible_children = parent_segment.segments\n+ if filter_meta:\n+ possible_children = [s for s in possible_children if not s.is_meta]\n if len(possible_children) > possible_children.index(child_segment) + 1:\n return False\n child_segment = parent_segment\ndiff --git a/src/sqlfluff/core/templaters/slicers/tracer.py b/src/sqlfluff/core/templaters/slicers/tracer.py\n--- a/src/sqlfluff/core/templaters/slicers/tracer.py\n+++ b/src/sqlfluff/core/templaters/slicers/tracer.py\n@@ -289,7 +289,6 @@ def _slice_template(self) -> List[RawFileSlice]:\n # parts of the tag at a time.\n unique_alternate_id = None\n alternate_code = None\n- trimmed_content = \"\"\n if elem_type.endswith(\"_end\") or elem_type == \"raw_begin\":\n block_type = block_types[elem_type]\n block_subtype = None\n@@ -436,6 +435,16 @@ def _slice_template(self) -> List[RawFileSlice]:\n \"endfor\",\n \"endif\",\n ):\n+ # Replace RawSliceInfo for this slice with one that has\n+ # alternate ID and code for tracking. This ensures, for\n+ # instance, that if a file ends with \"{% endif %} (with\n+ # no newline following), that we still generate a\n+ # TemplateSliceInfo for it.\n+ unique_alternate_id = self.next_slice_id()\n+ alternate_code = f\"{result[-1].raw}\\0{unique_alternate_id}_0\"\n+ self.raw_slice_info[result[-1]] = RawSliceInfo(\n+ unique_alternate_id, alternate_code, []\n+ )\n # Record potential forward jump over this block.\n self.raw_slice_info[result[stack[-1]]].next_slice_indices.append(\n block_idx\ndiff --git a/src/sqlfluff/rules/L009.py b/src/sqlfluff/rules/L009.py\n--- a/src/sqlfluff/rules/L009.py\n+++ b/src/sqlfluff/rules/L009.py\n@@ -91,7 +91,7 @@ def _eval(self, context: RuleContext) -> Optional[LintResult]:\n \n \"\"\"\n # We only care about the final segment of the parse tree.\n- if not self.is_final_segment(context):\n+ if not self.is_final_segment(context, filter_meta=False):\n return None\n \n # Include current segment for complete stack and reverse.\n", "test_patch": "diff --git a/test/api/simple_test.py b/test/api/simple_test.py\n--- a/test/api/simple_test.py\n+++ b/test/api/simple_test.py\n@@ -72,16 +72,16 @@\n \"description\": \"Keywords must be consistently upper case.\",\n },\n {\n- \"code\": \"L009\",\n+ \"code\": \"L014\",\n \"line_no\": 1,\n \"line_pos\": 34,\n- \"description\": \"Files must end with a single trailing newline.\",\n+ \"description\": \"Unquoted identifiers must be consistently lower case.\",\n },\n {\n- \"code\": \"L014\",\n+ \"code\": \"L009\",\n \"line_no\": 1,\n- \"line_pos\": 34,\n- \"description\": \"Unquoted identifiers must be consistently lower case.\",\n+ \"line_pos\": 41,\n+ \"description\": \"Files must end with a single trailing newline.\",\n },\n ]\n \ndiff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -822,6 +822,10 @@ def test__templater_jinja_slice_template(test, result):\n (\"block_end\", slice(113, 127, None), slice(11, 11, None)),\n (\"block_start\", slice(27, 46, None), slice(11, 11, None)),\n (\"literal\", slice(46, 57, None), slice(11, 22, None)),\n+ (\"block_end\", slice(57, 70, None), slice(22, 22, None)),\n+ (\"block_start\", slice(70, 89, None), slice(22, 22, None)),\n+ (\"block_end\", slice(100, 113, None), slice(22, 22, None)),\n+ (\"block_end\", slice(113, 127, None), slice(22, 22, None)),\n ],\n ),\n (\n@@ -910,8 +914,20 @@ def test__templater_jinja_slice_template(test, result):\n (\"literal\", slice(91, 92, None), slice(0, 0, None)),\n (\"block_end\", slice(92, 104, None), slice(0, 0, None)),\n (\"literal\", slice(104, 113, None), slice(0, 9, None)),\n- (\"templated\", slice(113, 139, None), slice(9, 29, None)),\n- (\"literal\", slice(139, 156, None), slice(29, 46, None)),\n+ (\"templated\", slice(113, 139, None), slice(9, 28, None)),\n+ (\"literal\", slice(139, 156, None), slice(28, 28, None)),\n+ ],\n+ ),\n+ (\n+ # Test for issue 2822: Handle slicing when there's no newline after\n+ # the Jinja block end.\n+ \"{% if true %}\\nSELECT 1 + 1\\n{%- endif %}\",\n+ None,\n+ [\n+ (\"block_start\", slice(0, 13, None), slice(0, 0, None)),\n+ (\"literal\", slice(13, 26, None), slice(0, 13, None)),\n+ (\"literal\", slice(26, 27, None), slice(13, 13, None)),\n+ (\"block_end\", slice(27, 39, None), slice(13, 13, None)),\n ],\n ),\n ],\ndiff --git a/test/fixtures/rules/std_rule_cases/L009.yml b/test/fixtures/rules/std_rule_cases/L009.yml\n--- a/test/fixtures/rules/std_rule_cases/L009.yml\n+++ b/test/fixtures/rules/std_rule_cases/L009.yml\n@@ -33,3 +33,9 @@ test_pass_templated_macro_newlines:\n {{ columns }}\n {% endmacro %}\n SELECT {{ get_keyed_nulls(\"other_id\") }}\n+\n+test_fail_templated_no_newline:\n+ # Tricky because there's no newline at the end of the file (following the\n+ # templated code).\n+ fail_str: \"{% if true %}\\nSELECT 1 + 1\\n{%- endif %}\"\n+ fix_str: \"{% if true %}\\nSELECT 1 + 1\\n{%- endif %}\\n\"\n", "problem_statement": "fix keep adding new line on wrong place \n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nTo replicate this issue you can create a file eg. test.template.sql \r\n\r\n```\r\n{% if true %}\r\nSELECT 1 + 1\r\n{%- endif %}\r\n```\r\n\r\nthen run:\r\n```\r\nsqlfluff fix test.template.sql \r\n```\r\n\r\nThis will give you:\r\n```\r\nL: 2 | P: 12 | L009 | Files must end with a trailing newline.\r\n```\r\n\r\nAnd the result of the file is now:\r\n```\r\n{% if true %}\r\nSELECT 1 + 1\r\n\r\n{%- endif %}\r\n```\r\n\r\nIf i run it again it will complain on the same issue and the result of the file would be: \r\n```\r\n{% if true %}\r\nSELECT 1 + 1\r\n\r\n\r\n{%- endif %}\r\n```\r\n\r\nAnd so on. \n\n### Expected Behaviour\n\nThe expected behavior would be to add the new line at the end of the file, that is after `{%- endif %}` instead of adding the new line at the end of the SQL query - so the result should look like this: \r\n\r\n```\r\n{% if true %}\r\nSELECT 1 + 1\r\n{%- endif %}\r\n\r\n```\n\n### Observed Behaviour\n\nAdds a new line to the end of the SQL query instead of in the end of the file. \n\n### How to reproduce\n\nAlready mentioned above (in What Happened section).\n\n### Dialect\n\nsnowflake\n\n### Version\n\nsqlfluff, version 0.6.2\n\n### Configuration\n\n[sqlfluff]\r\nverbose = 1\r\ndialect = snowflake\r\ntemplater = jinja\r\nexclude_rules = L027,L031,L032,L036,L044,L046,L034\r\noutput_line_length = 121\r\nsql_file_exts=.sql\r\n\r\n[sqlfluff:rules]\r\ntab_space_size = 4\r\nmax_line_length = 250\r\nindent_unit = space\r\ncomma_style = trailing\r\nallow_scalar = True\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = aliases\r\n\r\n\r\n[sqlfluff:rules:L010] # Keywords\r\ncapitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L014]\r\nextended_capitalisation_policy = lower\r\n\r\n[sqlfluff:rules:L030] # function names\r\ncapitalisation_policy = upper\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "> Version\r\n> sqlfluff, version 0.6.2\r\n\r\nIs this correct? If so that is a VERY old version so please upgrade. Though confirmed this is still an issue in latest. But still, going to need to upgrade to get any fix for this.\n> > Version\r\n> > sqlfluff, version 0.6.2\r\n> \r\n> Is this correct? If so that is a VERY old version so please upgrade. Though confirmed this is still an issue in latest. But still, going to need to upgrade to get any fix for this.\r\n\r\nThanks for your response! I had sqlfluff globally installed with version 0.6.2 but i changed it now to 0.11.0 and still it is the same issue.\nThe rule probably needs updating to be \"template aware\". A few other rules have required similar updates and may provide useful inspiration for a fix.\r\n\r\n```\r\nsrc/sqlfluff/rules/L019.py\r\n140: and not last_seg.is_templated\r\n209: if last_seg.is_type(\"comma\") and not context.segment.is_templated:\r\n\r\nsrc/sqlfluff/rules/L003.py\r\n77: if elem.is_type(\"whitespace\") and elem.is_templated:\r\n148: templated_line = elem.is_templated\r\n\r\nsrc/sqlfluff/rules/L010.py\r\n87: if context.segment.is_templated:\r\n```\nI can't reproduce this issue with SQLFluff 0.11.0. This is the terminal output I get:\r\n```\r\n(sqlfluff-0.11.0) \u279c /tmp sqlfluff fix test.template.sql\r\n==== sqlfluff ====\r\nsqlfluff: 0.11.0 python: 3.9.1\r\nimplementation: cpython dialect: snowflake\r\nverbosity: 1 templater: jinja\r\n\r\n==== finding fixable violations ====\r\n=== [ path: test.template.sql ] ===\r\n\r\n== [test.template.sql] FAIL \r\nL: 2 | P: 1 | L003 | Indent expected and not found compared to line #1 \r\n==== fixing violations ====\r\n1 fixable linting violations found\r\nAre you sure you wish to attempt to fix these? [Y/n] ...\r\nAttempting fixes...\r\nPersisting Changes...\r\n== [test.template.sql] PASS\r\nDone. Please check your files to confirm.\r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n```\r\n\r\nAnd this is the resulting file. SQLFluff indented line 2 but no newline was added.\r\n```\r\n{% if true %}\r\n SELECT 1 + 1\r\n{%- endif %}\r\n```\nI can @barrywhart but it only works when the final newline in the file doesn't exist.\r\n\r\nIf on mac you can run something like this to strip the final newline character:\r\n\r\n```\r\ntruncate -s -1 test.sql > test2.sql\r\n```\r\n\r\nThen fix `test2.sql` with default config and you'll see it.\nThere's a bug in `JinjaTracer` -- if a Jinja block (e.g. `{% endif %}` is the final slice in the file (i. there's no final newline), that slice is missing from the output. This will have to be fixed before we can fix L009, because at present, L009 cannot \"see\" that `{% endif %}` after the `1`.", "created_at": "2022-03-14T19:46:08Z", "version": "0.10", "FAIL_TO_PASS": ["test/api/simple_test.py::test__api__lint_string", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-"], "PASS_TO_PASS": ["test/api/simple_test.py::test__api__lint_string_without_violations", "test/api/simple_test.py::test__api__lint_string_specific", "test/api/simple_test.py::test__api__lint_string_specific_single", "test/api/simple_test.py::test__api__lint_string_specific_exclude", "test/api/simple_test.py::test__api__lint_string_specific_exclude_single", "test/api/simple_test.py::test__api__lint_string_specific_exclude_all_failed_rules", "test/api/simple_test.py::test__api__fix_string", "test/api/simple_test.py::test__api__fix_string_specific", "test/api/simple_test.py::test__api__fix_string_specific_exclude", "test/api/simple_test.py::test__api__fix_string_unparsable", "test/api/simple_test.py::test__api__fix_string_unparsable_fix_even_unparsable", "test/api/simple_test.py::test__api__parse_string", "test/api/simple_test.py::test__api__parse_fail", "test/api/simple_test.py::test__api__config_path", "test/api/simple_test.py::test__api__config_override[kwargs0-expected0]", "test/api/simple_test.py::test__api__config_override[kwargs1-expected1]", "test/api/simple_test.py::test__api__invalid_dialect", "test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test_templater_set_block_handling", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n"], "environment_setup_commit": "3d52e8270d82aeccf4c516d059a80a6947919aea"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2336", "base_commit": "37a993f7ad841ab3035d1db5ce6525f2e5584fd5", "patch": "diff --git a/src/sqlfluff/core/rules/analysis/select.py b/src/sqlfluff/core/rules/analysis/select.py\n--- a/src/sqlfluff/core/rules/analysis/select.py\n+++ b/src/sqlfluff/core/rules/analysis/select.py\n@@ -124,7 +124,7 @@ def _has_value_table_function(table_expr, dialect):\n # We need the dialect to get the value table function names. If\n # we don't have it, assume the clause does not have a value table\n # function.\n- return False\n+ return False # pragma: no cover\n \n for function_name in table_expr.recursive_crawl(\"function_name\"):\n # Other rules can increase whitespace in the function name, so use strip to remove\n@@ -138,7 +138,7 @@ def _get_pivot_table_columns(segment, dialect):\n if not dialect:\n # We need the dialect to get the pivot table column names. If\n # we don't have it, assume the clause does not have a pivot table\n- return []\n+ return [] # pragma: no cover\n \n fc = segment.get_child(\"from_pivot_expression\")\n if not fc:\ndiff --git a/src/sqlfluff/core/rules/reference.py b/src/sqlfluff/core/rules/reference.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/sqlfluff/core/rules/reference.py\n@@ -0,0 +1,26 @@\n+\"\"\"Components for working with object and table references.\"\"\"\n+from typing import Sequence, Tuple\n+\n+\n+def object_ref_matches_table(\n+ possible_references: Sequence[Tuple[str, ...]], targets: Sequence[Tuple[str, ...]]\n+) -> bool:\n+ \"\"\"Return True if any of the possible references matches a target.\"\"\"\n+ # Simple case: If there are no references, assume okay\n+ # (i.e. no mismatch = good).\n+ if not possible_references:\n+ return True\n+ # Simple case: Reference exactly matches a target.\n+ if any(pr in targets for pr in possible_references):\n+ return True\n+ # Tricky case: If one is shorter than the other, check for a suffix match.\n+ # (Note this is an \"optimistic\" check, i.e. it assumes the ignored parts of\n+ # the target don't matter. In a SQL context, this is basically assuming\n+ # there was an earlier \"USE <<database>>\" or similar directive.\n+ for pr in possible_references:\n+ for t in targets:\n+ if (len(pr) < len(t) and pr == t[-len(pr) :]) or (\n+ len(t) < len(pr) and t == pr[-len(t) :]\n+ ):\n+ return True\n+ return False\ndiff --git a/src/sqlfluff/dialects/dialect_ansi.py b/src/sqlfluff/dialects/dialect_ansi.py\n--- a/src/sqlfluff/dialects/dialect_ansi.py\n+++ b/src/sqlfluff/dialects/dialect_ansi.py\n@@ -734,6 +734,18 @@ def extract_possible_references(\n return [refs[-level]]\n return []\n \n+ def extract_possible_multipart_references(\n+ self, levels: List[Union[ObjectReferenceLevel, int]]\n+ ) -> List[Tuple[ObjectReferencePart, ...]]:\n+ \"\"\"Extract possible multipart references, e.g. schema.table.\"\"\"\n+ levels_tmp = [self._level_to_int(level) for level in levels]\n+ min_level = min(levels_tmp)\n+ max_level = max(levels_tmp)\n+ refs = list(self.iter_raw_references())\n+ if len(refs) >= max_level:\n+ return [tuple(refs[-max_level : 1 - min_level])]\n+ return []\n+\n @staticmethod\n def _level_to_int(level: Union[ObjectReferenceLevel, int]) -> int:\n # If it's an ObjectReferenceLevel, get the value. Otherwise, assume it's\n@@ -1156,7 +1168,6 @@ def get_eventual_alias(self) -> Optional[AliasInfo]:\n return AliasInfo(segment.raw, segment, True, self, alias_expression, ref)\n \n # If not return the object name (or None if there isn't one)\n- # ref = self.get_child(\"object_reference\")\n if ref:\n # Return the last element of the reference.\n penultimate_ref: ObjectReferenceSegment.ObjectReferencePart = list(\ndiff --git a/src/sqlfluff/dialects/dialect_bigquery.py b/src/sqlfluff/dialects/dialect_bigquery.py\n--- a/src/sqlfluff/dialects/dialect_bigquery.py\n+++ b/src/sqlfluff/dialects/dialect_bigquery.py\n@@ -740,6 +740,18 @@ def extract_possible_references(self, level):\n return [refs[1], refs[2]]\n return super().extract_possible_references(level) # pragma: no cover\n \n+ def extract_possible_multipart_references(self, levels):\n+ \"\"\"Extract possible multipart references, e.g. schema.table.\"\"\"\n+ levels_tmp = [self._level_to_int(level) for level in levels]\n+ min_level = min(levels_tmp)\n+ max_level = max(levels_tmp)\n+ refs = list(self.iter_raw_references())\n+ if max_level == self.ObjectReferenceLevel.SCHEMA.value and len(refs) >= 3:\n+ return [tuple(refs[0 : max_level - min_level + 1])]\n+ # Note we aren't handling other possible cases. We'll add these as\n+ # needed.\n+ return super().extract_possible_multipart_references(levels)\n+\n \n @bigquery_dialect.segment()\n class HyphenatedObjectReferenceSegment(ObjectReferenceSegment): # type: ignore\ndiff --git a/src/sqlfluff/rules/L025.py b/src/sqlfluff/rules/L025.py\n--- a/src/sqlfluff/rules/L025.py\n+++ b/src/sqlfluff/rules/L025.py\n@@ -85,16 +85,18 @@ def _eval(self, context: RuleContext) -> EvalResultType:\n def _analyze_table_aliases(cls, query: L025Query, dialect: Dialect):\n # Get table aliases defined in query.\n for selectable in query.selectables:\n- select_info = get_select_statement_info(selectable.selectable, dialect)\n+ select_info = selectable.select_info\n if select_info:\n # Record the aliases.\n query.aliases += select_info.table_aliases\n \n- # Look at each table reference; if its an alias reference,\n+ # Look at each table reference; if it's an alias reference,\n # resolve the alias: could be an alias defined in \"query\"\n # itself or an \"ancestor\" query.\n for r in select_info.reference_buffer:\n- for tr in r.extract_possible_references(level=r.ObjectReferenceLevel.TABLE): # type: ignore\n+ for tr in r.extract_possible_references(\n+ level=r.ObjectReferenceLevel.TABLE\n+ ):\n # This function walks up the query's parent stack if necessary.\n cls._resolve_and_mark_reference(query, tr.part)\n \ndiff --git a/src/sqlfluff/rules/L026.py b/src/sqlfluff/rules/L026.py\n--- a/src/sqlfluff/rules/L026.py\n+++ b/src/sqlfluff/rules/L026.py\n@@ -1,13 +1,33 @@\n \"\"\"Implementation of Rule L026.\"\"\"\n-\n-from sqlfluff.core.rules.analysis.select import get_aliases_from_select\n-from sqlfluff.core.rules.base import EvalResultType, LintResult, RuleContext\n+from dataclasses import dataclass, field\n+from typing import cast, List, Optional, Tuple\n+\n+from sqlfluff.core.dialects.base import Dialect\n+from sqlfluff.core.rules.analysis.select_crawler import (\n+ Query as SelectCrawlerQuery,\n+ SelectCrawler,\n+)\n+from sqlfluff.core.dialects.common import AliasInfo\n+from sqlfluff.core.rules.base import (\n+ BaseRule,\n+ LintResult,\n+ RuleContext,\n+ EvalResultType,\n+)\n+from sqlfluff.core.rules.functional import sp\n from sqlfluff.core.rules.doc_decorators import document_configuration\n-from sqlfluff.rules.L020 import Rule_L020\n+from sqlfluff.core.rules.reference import object_ref_matches_table\n+\n+\n+@dataclass\n+class L026Query(SelectCrawlerQuery):\n+ \"\"\"SelectCrawler Query with custom L026 info.\"\"\"\n+\n+ aliases: List[AliasInfo] = field(default_factory=list)\n \n \n @document_configuration\n-class Rule_L026(Rule_L020):\n+class Rule_L026(BaseRule):\n \"\"\"References cannot reference objects not present in ``FROM`` clause.\n \n NB: This rule is disabled by default for BigQuery due to its use of\n@@ -36,61 +56,7 @@ class Rule_L026(Rule_L020):\n \n config_keywords = [\"force_enable\"]\n \n- @staticmethod\n- def _is_bad_tbl_ref(table_aliases, parent_select, tbl_ref):\n- \"\"\"Given a table reference, try to find what it's referring to.\"\"\"\n- # Is it referring to one of the table aliases?\n- if tbl_ref[0] in [a.ref_str for a in table_aliases]:\n- # Yes. Therefore okay.\n- return False\n-\n- # Not a table alias. It it referring to a correlated subquery?\n- if parent_select:\n- parent_aliases, _ = get_aliases_from_select(parent_select)\n- if parent_aliases and tbl_ref[0] in [a[0] for a in parent_aliases]:\n- # Yes. Therefore okay.\n- return False\n-\n- # It's not referring to an alias or a correlated subquery. Looks like a\n- # bad reference (i.e. referring to something unknown.)\n- return True\n-\n- def _lint_references_and_aliases(\n- self,\n- table_aliases,\n- standalone_aliases,\n- references,\n- col_aliases,\n- using_cols,\n- parent_select,\n- ):\n- # A buffer to keep any violations.\n- violation_buff = []\n-\n- # Check all the references that we have, do they reference present aliases?\n- for r in references:\n- tbl_refs = r.extract_possible_references(level=r.ObjectReferenceLevel.TABLE)\n- if tbl_refs and all(\n- self._is_bad_tbl_ref(table_aliases, parent_select, tbl_ref)\n- for tbl_ref in tbl_refs\n- ):\n- violation_buff.append(\n- LintResult(\n- # Return the first segment rather than the string\n- anchor=tbl_refs[0].segments[0],\n- description=f\"Reference {r.raw!r} refers to table/view \"\n- \"not found in the FROM clause or found in parent \"\n- \"subquery.\",\n- )\n- )\n- return violation_buff or None\n-\n def _eval(self, context: RuleContext) -> EvalResultType:\n- \"\"\"Override Rule L020 for dialects that use structs.\n-\n- Some dialects use structs (e.g. column.field) which look like\n- table references and so incorrectly trigger this rule.\n- \"\"\"\n # Config type hints\n self.force_enable: bool\n \n@@ -100,4 +66,128 @@ def _eval(self, context: RuleContext) -> EvalResultType:\n ):\n return LintResult()\n \n- return super()._eval(context=context)\n+ violations: List[LintResult] = []\n+ start_types = [\"select_statement\", \"delete_statement\", \"update_statement\"]\n+ if context.segment.is_type(\n+ *start_types\n+ ) and not context.functional.parent_stack.any(sp.is_type(*start_types)):\n+ dml_target_table: Optional[Tuple[str, ...]] = None\n+ if not context.segment.is_type(\"select_statement\"):\n+ # Extract first table reference. This will be the target\n+ # table in a DELETE or UPDATE statement.\n+ table_reference = next(\n+ context.segment.recursive_crawl(\"table_reference\"), None\n+ )\n+ if table_reference:\n+ dml_target_table = self._table_ref_as_tuple(table_reference)\n+\n+ # Verify table references in any SELECT statements found in or\n+ # below context.segment in the parser tree.\n+ crawler = SelectCrawler(\n+ context.segment, context.dialect, query_class=L026Query\n+ )\n+ query: L026Query = cast(L026Query, crawler.query_tree)\n+ self._analyze_table_references(\n+ query, dml_target_table, context.dialect, violations\n+ )\n+ return violations or None\n+\n+ @classmethod\n+ def _alias_info_as_tuples(cls, alias_info: AliasInfo) -> List[Tuple[str, ...]]:\n+ result: List[Tuple[str, ...]] = []\n+ if alias_info.aliased:\n+ result.append((alias_info.ref_str,))\n+ if alias_info.object_reference:\n+ result.append(cls._table_ref_as_tuple(alias_info.object_reference))\n+ return result\n+\n+ @staticmethod\n+ def _table_ref_as_tuple(table_reference) -> Tuple[str, ...]:\n+ return tuple(ref.part for ref in table_reference.iter_raw_references())\n+\n+ def _analyze_table_references(\n+ self,\n+ query: L026Query,\n+ dml_target_table: Optional[Tuple[str, ...]],\n+ dialect: Dialect,\n+ violations: List[LintResult],\n+ ):\n+ # For each query...\n+ for selectable in query.selectables:\n+ select_info = selectable.select_info\n+ if select_info:\n+ # Record the available tables.\n+ query.aliases += select_info.table_aliases\n+\n+ # Try and resolve each reference to a value in query.aliases (or\n+ # in an ancestor query).\n+ for r in select_info.reference_buffer:\n+ # This function walks up the query's parent stack if necessary.\n+ violation = self._resolve_reference(\n+ r, self._get_table_refs(r, dialect), dml_target_table, query\n+ )\n+ if violation:\n+ violations.append(violation)\n+\n+ # Visit children.\n+ for child in query.children:\n+ self._analyze_table_references(\n+ cast(L026Query, child), dml_target_table, dialect, violations\n+ )\n+\n+ @staticmethod\n+ def _get_table_refs(ref, dialect):\n+ \"\"\"Given ObjectReferenceSegment, determine possible table references.\"\"\"\n+ tbl_refs = []\n+ # First, handle any schema.table references.\n+ for sr, tr in ref.extract_possible_multipart_references(\n+ levels=[\n+ ref.ObjectReferenceLevel.SCHEMA,\n+ ref.ObjectReferenceLevel.TABLE,\n+ ]\n+ ):\n+ tbl_refs.append((tr, (sr.part, tr.part)))\n+ # Maybe check for simple table references. Two cases:\n+ # - For most dialects, skip this if it's a schema+table reference -- the\n+ # reference was specific, so we shouldn't ignore that by looking\n+ # elsewhere.)\n+ # - Always do this in BigQuery. BigQuery table references are frequently\n+ # ambiguous because BigQuery SQL supports structures, making some\n+ # multi-level \".\" references impossible to interpret with certainty.\n+ # We may need to genericize this code someday to support other\n+ # dialects. If so, this check should probably align somehow with\n+ # whether the dialect overrides\n+ # ObjectReferenceSegment.extract_possible_references().\n+ if not tbl_refs or dialect.name in [\"bigquery\"]:\n+ for tr in ref.extract_possible_references(\n+ level=ref.ObjectReferenceLevel.TABLE\n+ ):\n+ tbl_refs.append((tr, (tr.part,)))\n+ return tbl_refs\n+\n+ def _resolve_reference(\n+ self, r, tbl_refs, dml_target_table: Optional[Tuple[str, ...]], query: L026Query\n+ ):\n+ # Does this query define the referenced table?\n+ possible_references = [tbl_ref[1] for tbl_ref in tbl_refs]\n+ targets = []\n+ for alias in query.aliases:\n+ targets += self._alias_info_as_tuples(alias)\n+ if not object_ref_matches_table(possible_references, targets):\n+ # No. Check the parent query, if there is one.\n+ if query.parent:\n+ return self._resolve_reference(\n+ r, tbl_refs, dml_target_table, cast(L026Query, query.parent)\n+ )\n+ # No parent query. If there's a DML statement at the root, check its\n+ # target table.\n+ elif not dml_target_table or not object_ref_matches_table(\n+ possible_references, [dml_target_table]\n+ ):\n+ return LintResult(\n+ # Return the first segment rather than the string\n+ anchor=tbl_refs[0][0].segments[0],\n+ description=f\"Reference {r.raw!r} refers to table/view \"\n+ \"not found in the FROM clause or found in ancestor \"\n+ \"statement.\",\n+ )\n", "test_patch": "diff --git a/test/core/rules/reference_test.py b/test/core/rules/reference_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/core/rules/reference_test.py\n@@ -0,0 +1,72 @@\n+\"\"\"Test components for working with object and table references.\"\"\"\n+import pytest\n+\n+from sqlfluff.core.rules import reference\n+\n+\[email protected](\n+ \"possible_references, targets, result\",\n+ [\n+ # Empty list of references is always True.\n+ [[], [(\"abc\",)], True],\n+ # Simple cases: one reference, one target.\n+ [[(\"agent1\",)], [(\"agent1\",)], True],\n+ [[(\"agent1\",)], [(\"customer\",)], False],\n+ # Multiple references. If any match, good.\n+ [[(\"bar\",), (\"user_id\",)], [(\"bar\",)], True],\n+ [[(\"foo\",), (\"user_id\",)], [(\"bar\",)], False],\n+ # Multiple targets. If any reference matches, good.\n+ [[(\"table1\",)], [(\"table1\",), (\"table2\",), (\"table3\",)], True],\n+ [[(\"tbl2\",)], [(\"db\", \"sc\", \"tbl1\")], False],\n+ [[(\"tbl2\",)], [(\"db\", \"sc\", \"tbl2\")], True],\n+ # Multi-part references and targets. If one tuple is shorter than\n+ # the other, checks for a suffix match.\n+ [\n+ [\n+ (\n+ \"rc\",\n+ \"tbl1\",\n+ )\n+ ],\n+ [(\"db\", \"sc\", \"tbl1\")],\n+ False,\n+ ],\n+ [\n+ [\n+ (\n+ \"sc\",\n+ \"tbl1\",\n+ )\n+ ],\n+ [(\"db\", \"sc\", \"tbl1\")],\n+ True,\n+ ],\n+ [\n+ [\n+ (\n+ \"cb\",\n+ \"sc\",\n+ \"tbl1\",\n+ )\n+ ],\n+ [(\"db\", \"sc\", \"tbl1\")],\n+ False,\n+ ],\n+ [\n+ [\n+ (\n+ \"db\",\n+ \"sc\",\n+ \"tbl1\",\n+ )\n+ ],\n+ [(\"db\", \"sc\", \"tbl1\")],\n+ True,\n+ ],\n+ [[(\"public\", \"agent1\")], [(\"agent1\",)], True],\n+ [[(\"public\", \"agent1\")], [(\"public\",)], False],\n+ ],\n+)\n+def test_object_ref_matches_table(possible_references, targets, result):\n+ \"\"\"Test object_ref_matches_table().\"\"\"\n+ assert reference.object_ref_matches_table(possible_references, targets) == result\ndiff --git a/test/fixtures/rules/std_rule_cases/L026.yml b/test/fixtures/rules/std_rule_cases/L026.yml\n--- a/test/fixtures/rules/std_rule_cases/L026.yml\n+++ b/test/fixtures/rules/std_rule_cases/L026.yml\n@@ -110,3 +110,64 @@ test_pass_object_referenced_6:\n table3\n on table2.y_id = table3.y_id\n ) as cc\n+\n+test_pass_object_referenced_7:\n+ pass_str: |\n+ UPDATE my_table\n+ SET row_sum = (\n+ SELECT COUNT(*) AS row_sum\n+ FROM\n+ another_table\n+ WHERE\n+ another_table.id = my_table.id\n+ )\n+\n+test_fail_object_referenced_7:\n+ fail_str: |\n+ UPDATE my_table\n+ SET row_sum = (\n+ SELECT COUNT(*) AS row_sum\n+ FROM\n+ another_table\n+ WHERE\n+ another_table.id = my_tableeee.id\n+ )\n+\n+test_pass_object_referenced_8:\n+ pass_str: |\n+ DELETE FROM agent1\n+ WHERE EXISTS(\n+ SELECT customer.cust_id FROM customer\n+ WHERE agent1.agent_code <> customer.agent_code);\n+\n+test_pass_two_part_reference_8:\n+ pass_str: |\n+ delete from public.agent1\n+ where exists(\n+ select customer.cust_id from customer\n+ where agent1.agent_code <> customer.agent_code)\n+\n+test_pass_two_part_reference_9:\n+ pass_str: |\n+ delete from public.agent1\n+ where exists(\n+ select customer.cust_id from customer\n+ where public.agent1.agent_code <> customer.agent_code)\n+\n+test_fail_two_part_reference_10:\n+ fail_str: |\n+ select *\n+ from schema1.agent1\n+ where schema2.agent1.agent_code <> 'abc'\n+\n+test_fail_two_part_reference_11:\n+ fail_str: |\n+ delete from schema1.agent1\n+ where exists(\n+ select customer.cust_id from customer\n+ where schema2.agent1.agent_code <> customer.agent_code)\n+\n+test_pass_two_part_reference_11:\n+ pass_str: |\n+ select * from agent1\n+ where public.agent1.agent_code <> '3'\n", "problem_statement": "L026: Rule incorrectly flag column does not exist in `FROM` clause in an UPDATE statement.\n## Expected Behaviour\r\n\r\nL026 should not fail when a subquery in an UPDATE statement references a column from the UPDATE target.\r\n\r\n## Observed Behaviour\r\n\r\nL026 failed due to reference was not found in the FROM clause with the following error printed (When using `sample.sql` content below)\r\n\r\n```\r\nL: 7 | P: 28 | L026 | Reference 'my_table.id' refers to table/view not found\r\n | in the FROM clause or found in parent subquery.\r\n```\r\n\r\n## Steps to Reproduce\r\n\r\n1. Create `sample.sql` with the content below\r\n```\r\nUPDATE my_table\r\nSET row_sum = (\r\n SELECT COUNT(*) AS row_sum\r\n FROM\r\n another_table\r\n WHERE\r\n another_table.id = my_table.id\r\n);\r\n```\r\n2. Run SQLFluff by `sqlfluff lint sample.sql`\r\n\r\n## Dialect\r\n\r\nDefault / Ansi (No dialect specified)\r\n\r\n## Version\r\n```\r\n(.venv) ~/code/sqlfluff (main) $ sqlfluff --version\r\nsqlfluff, version 0.9.0\r\n```\r\n\r\n```\r\n(.venv) ~/code/sqlfluff (main) $ python --version\r\nPython 3.9.9\r\n```\r\n\r\n## Configuration\r\nDefault. No customization.\r\n\n", "hints_text": "", "created_at": "2022-01-17T21:35:10Z", "version": "0.8", "FAIL_TO_PASS": ["test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references0-targets0-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references1-targets1-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references2-targets2-False]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references3-targets3-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references4-targets4-False]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references5-targets5-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references6-targets6-False]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references7-targets7-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references8-targets8-False]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references9-targets9-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references10-targets10-False]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references11-targets11-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references12-targets12-True]", "test/core/rules/reference_test.py::test_object_ref_matches_table[possible_references13-targets13-False]"], "PASS_TO_PASS": [], "environment_setup_commit": "a5c4eae4e3e419fe95460c9afd9cf39a35a470c4"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-5074", "base_commit": "7b7fd603a19755a9f3707ebbf95d18ee635716d8", "patch": "diff --git a/src/sqlfluff/core/errors.py b/src/sqlfluff/core/errors.py\n--- a/src/sqlfluff/core/errors.py\n+++ b/src/sqlfluff/core/errors.py\n@@ -47,9 +47,15 @@ def __init__(\n self.line_pos = line_pos\n super().__init__(self.desc())\n \n+ def __eq__(self, other) -> bool:\n+ \"\"\"Errors compare equal if they are the same type and same content.\"\"\"\n+ if not isinstance(other, self.__class__):\n+ return False\n+ return self.__dict__ == other.__dict__\n+\n def __reduce__(\n self,\n- ) -> Tuple[Type[\"SQLBaseError\"], Tuple[Any, ...]]: # pragma: no cover\n+ ) -> Tuple[Type[\"SQLBaseError\"], Tuple[Any, ...]]:\n \"\"\"Prepare the SQLBaseError for pickling.\"\"\"\n return type(self), (\n self.description,\n@@ -169,6 +175,9 @@ def __init__(\n segment: Optional[\"BaseSegment\"] = None,\n line_no: int = 0,\n line_pos: int = 0,\n+ ignore: bool = False,\n+ fatal: bool = False,\n+ warning: Optional[bool] = None,\n ) -> None:\n # Store the segment on creation - we might need it later\n self.segment = segment\n@@ -177,13 +186,24 @@ def __init__(\n pos=segment.pos_marker if segment else None,\n line_no=line_no,\n line_pos=line_pos,\n+ ignore=ignore,\n+ fatal=fatal,\n+ warning=warning,\n )\n \n def __reduce__(\n self,\n- ) -> Tuple[Type[\"SQLParseError\"], Tuple[Any, ...]]: # pragma: no cover\n+ ) -> Tuple[Type[\"SQLParseError\"], Tuple[Any, ...]]:\n \"\"\"Prepare the SQLParseError for pickling.\"\"\"\n- return type(self), (self.description, self.segment, self.line_no, self.line_pos)\n+ return type(self), (\n+ self.description,\n+ self.segment,\n+ self.line_no,\n+ self.line_pos,\n+ self.ignore,\n+ self.fatal,\n+ self.warning,\n+ )\n \n \n class SQLLintError(SQLBaseError):\n@@ -208,20 +228,34 @@ def __init__(\n segment: \"BaseSegment\",\n rule: \"BaseRule\",\n fixes: Optional[List[\"LintFix\"]] = None,\n+ ignore: bool = False,\n+ fatal: bool = False,\n+ warning: Optional[bool] = None,\n ) -> None:\n- # Something about position, message and fix?\n self.segment = segment\n self.rule = rule\n self.fixes = fixes or []\n super().__init__(\n- description=description, pos=segment.pos_marker if segment else None\n+ description=description,\n+ pos=segment.pos_marker if segment else None,\n+ ignore=ignore,\n+ fatal=fatal,\n+ warning=warning,\n )\n \n def __reduce__(\n self,\n- ) -> Tuple[Type[\"SQLLintError\"], Tuple[Any, ...]]: # pragma: no cover\n+ ) -> Tuple[Type[\"SQLLintError\"], Tuple[Any, ...]]:\n \"\"\"Prepare the SQLLintError for pickling.\"\"\"\n- return type(self), (self.description, self.segment, self.rule, self.fixes)\n+ return type(self), (\n+ self.description,\n+ self.segment,\n+ self.rule,\n+ self.fixes,\n+ self.ignore,\n+ self.fatal,\n+ self.warning,\n+ )\n \n @property\n def fixable(self) -> bool:\ndiff --git a/src/sqlfluff/core/parser/markers.py b/src/sqlfluff/core/parser/markers.py\n--- a/src/sqlfluff/core/parser/markers.py\n+++ b/src/sqlfluff/core/parser/markers.py\n@@ -62,6 +62,11 @@ def __ge__(self, other: \"PositionMarker\") -> bool:\n def __le__(self, other: \"PositionMarker\") -> bool:\n return self.working_loc <= other.working_loc # pragma: no cover TODO?\n \n+ def __eq__(self, other) -> bool:\n+ if not isinstance(other, PositionMarker):\n+ return False # pragma: no cover\n+ return self.working_loc == other.working_loc\n+\n @property\n def working_loc(self) -> Tuple[int, int]:\n \"\"\"Location tuple for the working position.\"\"\"\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -379,6 +379,20 @@ def test__cli__command_render_stdin():\n \"test/fixtures/linter/operator_errors.sql\",\n ],\n ),\n+ # Check ignoring linting (multiprocess)\n+ # https://github.com/sqlfluff/sqlfluff/issues/5066\n+ (\n+ lint,\n+ [\n+ \"-n\",\n+ \"--ignore\",\n+ \"linting\",\n+ \"-p\",\n+ \"2\",\n+ \"test/fixtures/linter/operator_errors.sql\",\n+ \"test/fixtures/linter/comma_errors.sql\",\n+ ],\n+ ),\n # Check linting works in specifying multiple rules\n (\n lint,\ndiff --git a/test/core/errors_test.py b/test/core/errors_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/core/errors_test.py\n@@ -0,0 +1,75 @@\n+\"\"\"Tests pickling and unpickling of errors.\"\"\"\n+\n+import pickle\n+import pytest\n+import copy\n+\n+from sqlfluff.core.parser import PositionMarker, RawSegment\n+from sqlfluff.core.rules import BaseRule\n+from sqlfluff.core.templaters import TemplatedFile\n+\n+from sqlfluff.core.errors import SQLBaseError, SQLLintError, SQLParseError, SQLLexError\n+\n+\n+class Rule_T078(BaseRule):\n+ \"\"\"A dummy rule.\"\"\"\n+\n+ groups = (\"all\",)\n+\n+ def _eval(self, context):\n+ pass\n+\n+\n+def assert_pickle_robust(err: SQLBaseError):\n+ \"\"\"Test that the class remains the same through copying and pickling.\"\"\"\n+ # First try copying (and make sure they still compare equal)\n+ err_copy = copy.copy(err)\n+ assert err_copy == err\n+ # Then try picking (and make sure they also still compare equal)\n+ pickled = pickle.dumps(err)\n+ pickle_copy = pickle.loads(pickled)\n+ assert pickle_copy == err\n+\n+\[email protected](\n+ \"ignore\",\n+ [True, False],\n+)\n+def test__lex_error_pickle(ignore):\n+ \"\"\"Test lexing error pickling.\"\"\"\n+ template = TemplatedFile.from_string(\"foobar\")\n+ err = SQLLexError(\"Foo\", pos=PositionMarker(slice(0, 6), slice(0, 6), template))\n+ # Set ignore to true if configured.\n+ # NOTE: This not copying was one of the reasons for this test.\n+ err.ignore = ignore\n+ assert_pickle_robust(err)\n+\n+\[email protected](\n+ \"ignore\",\n+ [True, False],\n+)\n+def test__parse_error_pickle(ignore):\n+ \"\"\"Test parse error pickling.\"\"\"\n+ template = TemplatedFile.from_string(\"foobar\")\n+ segment = RawSegment(\"foobar\", PositionMarker(slice(0, 6), slice(0, 6), template))\n+ err = SQLParseError(\"Foo\", segment=segment)\n+ # Set ignore to true if configured.\n+ # NOTE: This not copying was one of the reasons for this test.\n+ err.ignore = ignore\n+ assert_pickle_robust(err)\n+\n+\[email protected](\n+ \"ignore\",\n+ [True, False],\n+)\n+def test__lint_error_pickle(ignore):\n+ \"\"\"Test lint error pickling.\"\"\"\n+ template = TemplatedFile.from_string(\"foobar\")\n+ segment = RawSegment(\"foobar\", PositionMarker(slice(0, 6), slice(0, 6), template))\n+ err = SQLLintError(\"Foo\", segment=segment, rule=Rule_T078)\n+ # Set ignore to true if configured.\n+ # NOTE: This not copying was one of the reasons for this test.\n+ err.ignore = ignore\n+ assert_pickle_robust(err)\n", "problem_statement": "Inconsistent output depending on --processes flag when --ignore linting is used\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nDepending on the value you set for the `--processes` flag when also using `--ignore linting`, different output with different exit codes are generated.\n\n### Expected Behaviour\n\nThe same exit code should be generated, independently of the `--processes` flag. Furthermore, from https://docs.sqlfluff.com/en/stable/production.html#using-sqlfluff-on-a-whole-sql-codebase I would expect that exit codes should be either `0` or `65`, not `1`.\n\n### Observed Behaviour\n\nSee the How to reproduce section.\n\n### How to reproduce\n\nCreate a `test.sql` file with the following content:\r\n\r\n```SQL\r\nCREATE TABLE example (\r\n id TEXT DEFAULT 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In condimentum congue est, ac orci aliquam.' PRIMARY KEY\r\n);\r\n```\r\n\r\nThe line is too long according to SQLFluff, caused by the large default value, so let's see the the output of SQLFluff.\r\n\r\nRunning\r\n\r\n```SHELL\r\nsqlfluff fix --dialect postgres --ignore linting --processes 2\r\n```\r\n\r\nresults in \r\n\r\n```\r\n==== finding fixable violations ====\r\n==== no fixable linting violations found ==== \r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n [1 unfixable linting violations found]\r\n```\r\n\r\nwith exit code `1`. Running the same with one process instead:\r\n\r\n```SHELL\r\nsqlfluff fix --dialect postgres --ignore linting --processes 1\r\n```\r\n\r\nresults in\r\n\r\n```\r\n==== finding fixable violations ====\r\n==== no fixable linting violations found ==== \r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n```\r\n\r\nand exit code `0`\r\n\r\nSame behaviour for `lint` and `format` commands.\n\n### Dialect\n\nPostgres\n\n### Version\n\n2.2.0, Python 3.10.6\n\n### Configuration\n\nNone, it's all in the CLI flags.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "This is _very_ interesting! I'll pick this one up \ud83d\udc4d \nIt's worth calling out that I think part of the problem here is that the docs are also out of date - but you're still right that the return codes should be _the same_ regardless of the `processes` setting.", "created_at": "2023-08-08T23:31:59Z", "version": "2.1", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/core/errors_test.py::test__lex_error_pickle[True]", "test/core/errors_test.py::test__lex_error_pickle[False]", "test/core/errors_test.py::test__parse_error_pickle[True]", "test/core/errors_test.py::test__parse_error_pickle[False]", "test/core/errors_test.py::test__lint_error_pickle[True]", "test/core/errors_test.py::test__lint_error_pickle[False]"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_empty_stdin", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse[command26]", "test/cli/commands_test.py::test__cli__command_lint_parse[command27]", "test/cli/commands_test.py::test__cli__command_lint_parse[command28]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command5-2]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command6-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command7-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command8-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command9-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command10-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command11-2]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_lint_warning", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql0]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql1]", "test/cli/commands_test.py::test__cli__command__fix[LT02-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_format_stdin[select", "test/cli/commands_test.py::test__cli__command_format_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_warn_unused_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_force", "test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_no_force", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass"], "environment_setup_commit": "7b7fd603a19755a9f3707ebbf95d18ee635716d8"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3436", "base_commit": "23cd31e77a712a210c734e38488d7a34afd83a25", "patch": "diff --git a/src/sqlfluff/core/templaters/slicers/tracer.py b/src/sqlfluff/core/templaters/slicers/tracer.py\n--- a/src/sqlfluff/core/templaters/slicers/tracer.py\n+++ b/src/sqlfluff/core/templaters/slicers/tracer.py\n@@ -40,6 +40,7 @@ class RawSliceInfo:\n unique_alternate_id: Optional[str]\n alternate_code: Optional[str]\n next_slice_indices: List[int] = field(default_factory=list)\n+ inside_block: bool = field(default=False) # {% block %}\n \n \n class JinjaTracer:\n@@ -101,13 +102,21 @@ def trace(self, append_to_templated: str = \"\") -> JinjaTrace:\n alt_id, content_info, literal = value\n target_slice_idx = self.find_slice_index(alt_id)\n slice_length = content_info if literal else len(str(content_info))\n- self.move_to_slice(target_slice_idx, slice_length)\n+ target_inside_block = self.raw_slice_info[\n+ self.raw_sliced[target_slice_idx]\n+ ].inside_block\n+ if not target_inside_block:\n+ # Normal case: Walk through the template.\n+ self.move_to_slice(target_slice_idx, slice_length)\n+ else:\n+ # {% block %} executes code elsewhere in the template but does\n+ # not move there. It's a bit like macro invocation.\n+ self.record_trace(slice_length, target_slice_idx)\n \n # TRICKY: The 'append_to_templated' parameter is only used by the dbt\n # templater, passing \"\\n\" for this parameter if we need to add one back.\n # (The Jinja templater does not pass this parameter, so\n # 'append_to_templated' gets the default value of \"\", empty string.)\n- # we receive the default value of \"\".) The dbt templater will\n # For more detail, see the comments near the call to slice_file() in\n # plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py.\n templated_str = self.make_template(self.raw_str).render() + append_to_templated\n@@ -197,7 +206,8 @@ def __init__(self, raw_str: str, env: Environment):\n \n # Internal bookkeeping\n self.slice_id: int = 0\n- self.inside_set_or_macro: bool = False\n+ self.inside_set_or_macro: bool = False # {% set %} or {% macro %}\n+ self.inside_block = False # {% block %}\n self.stack: List[int] = []\n self.idx_raw: int = 0\n \n@@ -211,7 +221,7 @@ def slice_info_for_literal(self, length, prefix=\"\") -> RawSliceInfo:\n \"\"\"Returns a RawSliceInfo for a literal.\n \n In the alternate template, literals are replaced with a uniquely\n- numbered, easily-to-parse literal. JinjaTracer uses this output as\n+ numbered, easy-to-parse literal. JinjaTracer uses this output as\n a \"breadcrumb trail\" to deduce the execution path through the template.\n \n This is important even if the original literal (i.e. in the raw SQL\n@@ -222,13 +232,16 @@ def slice_info_for_literal(self, length, prefix=\"\") -> RawSliceInfo:\n \"\"\"\n unique_alternate_id = self.next_slice_id()\n alternate_code = f\"\\0{prefix}{unique_alternate_id}_{length}\"\n- return self.make_raw_slice_info(unique_alternate_id, alternate_code)\n+ return self.make_raw_slice_info(\n+ unique_alternate_id, alternate_code, inside_block=self.inside_block\n+ )\n \n- def update_inside_set_or_macro(\n+ def update_inside_set_or_macro_or_block(\n self, block_type: str, trimmed_parts: List[str]\n ) -> None:\n \"\"\"Based on block tag, update whether we're in a set/macro section.\"\"\"\n if block_type == \"block_start\" and trimmed_parts[0] in (\n+ \"block\",\n \"macro\",\n \"set\",\n ):\n@@ -236,11 +249,12 @@ def update_inside_set_or_macro(\n # - {% set variable = value %}\n # - {% set variable %}value{% endset %}\n # https://jinja.palletsprojects.com/en/2.10.x/templates/#block-assignments\n- # When the second format is used, set the field\n- # 'inside_set_or_macro' to True. This info is used elsewhere,\n- # as other code inside these regions require special handling.\n- # (Generally speaking, JinjaTracer ignores the contents of these\n- # blocks, treating them like opaque templated regions.)\n+ # When the second format is used, set one of the fields\n+ # 'inside_set_or_macro' or 'inside_block' to True. This info is\n+ # used elsewhere, as other code inside these regions require\n+ # special handling. (Generally speaking, JinjaAnalyzer ignores\n+ # the contents of these blocks, treating them like opaque templated\n+ # regions.)\n try:\n # Entering a set/macro block. Build a source string consisting\n # of just this one Jinja command and see if it parses. If so,\n@@ -255,22 +269,33 @@ def update_inside_set_or_macro(\n isinstance(e.message, str)\n and \"Unexpected end of template\" in e.message\n ):\n- # It was opening a block, thus we're inside a set or macro.\n- self.inside_set_or_macro = True\n+ # It was opening a block, thus we're inside a set, macro, or\n+ # block.\n+ if trimmed_parts[0] == \"block\":\n+ self.inside_block = True\n+ else:\n+ self.inside_set_or_macro = True\n else:\n raise # pragma: no cover\n- elif block_type == \"block_end\" and (trimmed_parts[0] in (\"endmacro\", \"endset\")):\n- # Exiting a set/macro block.\n- self.inside_set_or_macro = False\n+ elif block_type == \"block_end\":\n+ if trimmed_parts[0] in (\"endmacro\", \"endset\"):\n+ # Exiting a set or macro.\n+ self.inside_set_or_macro = False\n+ elif trimmed_parts[0] == \"endblock\":\n+ # Exiting a {% block %} block.\n+ self.inside_block = False\n \n def make_raw_slice_info(\n- self, unique_alternate_id: Optional[str], alternate_code: Optional[str]\n+ self,\n+ unique_alternate_id: Optional[str],\n+ alternate_code: Optional[str],\n+ inside_block: bool = False,\n ) -> RawSliceInfo:\n \"\"\"Create RawSliceInfo as given, or \"empty\" if in set/macro block.\"\"\"\n if not self.inside_set_or_macro:\n- return RawSliceInfo(unique_alternate_id, alternate_code, [])\n+ return RawSliceInfo(unique_alternate_id, alternate_code, [], inside_block)\n else:\n- return RawSliceInfo(None, None, [])\n+ return RawSliceInfo(None, None, [], False)\n \n # We decide the \"kind\" of element we're dealing with using its _closing_\n # tag rather than its opening tag. The types here map back to similar types\n@@ -351,7 +376,7 @@ def analyze(self, make_template: Callable[[str], Template]) -> JinjaTracer:\n raw_slice_info = self.track_templated(\n m_open, m_close, tag_contents\n )\n- self.update_inside_set_or_macro(block_type, tag_contents)\n+ self.update_inside_set_or_macro_or_block(block_type, tag_contents)\n m_strip_right = regex.search(\n r\"\\s+$\", raw, regex.MULTILINE | regex.DOTALL\n )\n", "test_patch": "diff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -1060,6 +1060,61 @@ def test__templater_jinja_slice_template(test, result):\n (\"block_end\", slice(27, 39, None), slice(13, 13, None)),\n ],\n ),\n+ (\n+ # Test for issue 3434: Handle {% block %}.\n+ \"SELECT {% block table_name %}block_contents{% endblock %} \"\n+ \"FROM {{ self.table_name() }}\\n\",\n+ None,\n+ [\n+ (\"literal\", slice(0, 7, None), slice(0, 7, None)),\n+ (\"literal\", slice(29, 43, None), slice(7, 21, None)),\n+ (\"block_start\", slice(7, 29, None), slice(21, 21, None)),\n+ (\"literal\", slice(29, 43, None), slice(21, 21, None)),\n+ (\"block_end\", slice(43, 57, None), slice(21, 21, None)),\n+ (\"literal\", slice(57, 63, None), slice(21, 27, None)),\n+ (\"templated\", slice(63, 86, None), slice(27, 27, None)),\n+ (\"literal\", slice(29, 43, None), slice(27, 41, None)),\n+ (\"literal\", slice(86, 87, None), slice(41, 42, None)),\n+ ],\n+ ),\n+ (\n+ # Another test for issue 3434: Similar to the first, but uses\n+ # the block inside a loop.\n+ \"\"\"{% block table_name %}block_contents{% endblock %}\n+SELECT\n+{% for j in [4, 5, 6] %}\n+FROM {{ j }}{{ self.table_name() }}\n+{% endfor %}\n+\"\"\",\n+ None,\n+ [\n+ (\"literal\", slice(22, 36, None), slice(0, 14, None)),\n+ (\"block_start\", slice(0, 22, None), slice(14, 14, None)),\n+ (\"literal\", slice(22, 36, None), slice(14, 14, None)),\n+ (\"block_end\", slice(36, 50, None), slice(14, 14, None)),\n+ (\"literal\", slice(50, 58, None), slice(14, 22, None)),\n+ (\"block_start\", slice(58, 82, None), slice(22, 22, None)),\n+ (\"literal\", slice(82, 88, None), slice(22, 28, None)),\n+ (\"templated\", slice(88, 95, None), slice(28, 29, None)),\n+ (\"templated\", slice(95, 118, None), slice(29, 29, None)),\n+ (\"literal\", slice(22, 36, None), slice(29, 43, None)),\n+ (\"literal\", slice(118, 119, None), slice(43, 44, None)),\n+ (\"block_end\", slice(119, 131, None), slice(44, 44, None)),\n+ (\"literal\", slice(82, 88, None), slice(44, 50, None)),\n+ (\"templated\", slice(88, 95, None), slice(50, 51, None)),\n+ (\"templated\", slice(95, 118, None), slice(51, 51, None)),\n+ (\"literal\", slice(22, 36, None), slice(51, 65, None)),\n+ (\"literal\", slice(118, 119, None), slice(65, 66, None)),\n+ (\"block_end\", slice(119, 131, None), slice(66, 66, None)),\n+ (\"literal\", slice(82, 88, None), slice(66, 72, None)),\n+ (\"templated\", slice(88, 95, None), slice(72, 73, None)),\n+ (\"templated\", slice(95, 118, None), slice(73, 73, None)),\n+ (\"literal\", slice(22, 36, None), slice(73, 87, None)),\n+ (\"literal\", slice(118, 119, None), slice(87, 88, None)),\n+ (\"block_end\", slice(119, 131, None), slice(88, 88, None)),\n+ (\"literal\", slice(131, 132, None), slice(88, 89, None)),\n+ ],\n+ ),\n ],\n )\n def test__templater_jinja_slice_file(raw_file, override_context, result, caplog):\n", "problem_statement": "Fatal templating error with Jinja templater. Tracer produces odd results.\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nIssue found while assessing an Airflow project.\r\n\r\nThe smallest query I can make which triggers the issue is: \r\n```sql\r\nSELECT\r\n\t{% block table_name %}a{% endblock %}.b\r\nFROM d.{{ self.table_name() }}\r\n```\r\n\r\nWhen running this query through `lint` I get an `AssertionError`, or if running on the more friendly error message PR (#3433) I get: `WARNING Length of templated file mismatch with final slice: 21 != 19.`.\n\n### Expected Behaviour\n\nThis query should slice properly and probably eventually give a jinja error that the required variables are undefined.\n\n### Observed Behaviour\n\nI've dug a little into the error and the sliced file being produced is:\r\n\r\n```python\r\n[\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(0, 8, None), templated_slice=slice(0, 8, None)),\r\n TemplatedFileSlice(slice_type='block_start', source_slice=slice(8, 30, None), templated_slice=slice(8, 8, None)),\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(30, 31, None), templated_slice=slice(8, 9, None)),\r\n TemplatedFileSlice(slice_type='block_end', source_slice=slice(31, 45, None), templated_slice=slice(9, 9, None)),\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(45, 55, None), templated_slice=slice(9, 19, None)),\r\n TemplatedFileSlice(slice_type='templated', source_slice=slice(55, 78, None), templated_slice=slice(19, 19, None)),\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(78, 79, None), templated_slice=slice(19, 19, None))\r\n]\r\n```\r\n\r\nThe issue is that while the `source_slice` looks correct for the slices, almost all of the `templated_slices` values have zero length, and importantly the last one doesn't end at position 21.\r\n\r\nThe rendered file is `SELECT\\n\\ta.b\\nFROM d.a\\n` (I've included the escape chars) which is indeed 21 chars long.\r\n\r\n@barrywhart I might need your help to work out what's going on with the Jinja tracer here.\n\n### How to reproduce\n\nRun provided query, `main` branch. Set to the `jinja` templater.\n\n### Dialect\n\ndialect is set to `snowflake`, but I don't think we're getting far enough for that to make a difference.\n\n### Version\n\n`main` branch commit `cb6357c540d2d968f766f3a7a4fa16f231cb80e4` (and a few branches derived from it)\n\n### Configuration\n\nN/A\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "I'll take a look.\r\n\r\nAnd darn it -- first bug report against this code in the past couple months, I think. \ud83d\ude05\nStarting to look at this. One problem I noticed (perhaps not the only one) is that the trailing literal newline in the source string has no corresponding templated slice, so it's like building the templated slice array has stopped early for some reason.\r\n\r\nThe 0-length slices may be legit. Will share more as I learn things, but is `{% block %}` a Jinja builtin or an extension? If it's an extension, maybe base Jinja is just skipping it (i.e. rendering it as empty string). \nOk, I think the issue is not related to undefined variables. I get the same assertion error if I define the variable prior to the block, e.g.:\r\n```\r\n{% set table_name = \"abc\" %}\r\nSELECT {% block table_name %}a{% endblock %} FROM {{ self.table_name() }}\r\n```\r\n\r\nI'm pretty sure the real issue is that we aren't handling `{% block %}` correctly **at all** (probably because I hadn't heard of it before \ud83e\udd2a).\r\n\r\nII think it should be handled similarly to `{% set %}` or `{% macro %}` blocks, i.e. basically don't trace when they are **defined**, only when they are **used**.\r\n\r\nI should be able to fix it this week. For now, just need to let my brain recover from looking at this code again. Even though I wrote it, it's a little too \"meta\" for me to stare at it for more than 1-2 hours at a time. \ud83d\ude05", "created_at": "2022-06-07T21:36:59Z", "version": "0.13", "FAIL_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%"], "PASS_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[set_multiple_variables_and_define_macro]", "test/core/templaters/jinja_test.py::test_templater_set_block_handling", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_dynamic_variable_no_violations", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_config-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_is_incremental-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_ref-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_source-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_this-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_o_config_override_dbt_builtins/override_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_p_disable_dbt_builtins/disable_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n"], "environment_setup_commit": "6e8ce43a4958dbaa56256365c2a89d8db92e07d6"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2849", "base_commit": "0bbd70f38a3318b9a488d988d06e8005e222d6ac", "patch": "diff --git a/plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py b/plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py\n--- a/plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py\n+++ b/plugins/sqlfluff-templater-dbt/sqlfluff_templater_dbt/templater.py\n@@ -522,17 +522,21 @@ def make_template(in_str):\n # sliced_file to reflect the mapping of the added character(s) back\n # to the raw SQL.\n templated_sql = templated_sql + \"\\n\" * n_trailing_newlines\n- sliced_file.append(\n- TemplatedFileSlice(\n- slice_type=\"literal\",\n- source_slice=slice(\n- len(source_dbt_sql) - n_trailing_newlines, len(source_dbt_sql)\n- ),\n- templated_slice=slice(\n- len(templated_sql) - n_trailing_newlines, len(templated_sql)\n- ),\n+ if sliced_file and sliced_file[-1].templated_slice.stop != len(\n+ templated_sql\n+ ):\n+ sliced_file.append(\n+ TemplatedFileSlice(\n+ slice_type=\"literal\",\n+ source_slice=slice(\n+ len(source_dbt_sql) - n_trailing_newlines,\n+ len(source_dbt_sql),\n+ ),\n+ templated_slice=slice(\n+ len(templated_sql) - n_trailing_newlines, len(templated_sql)\n+ ),\n+ )\n )\n- )\n return (\n TemplatedFile(\n source_str=source_dbt_sql,\ndiff --git a/src/sqlfluff/core/templaters/base.py b/src/sqlfluff/core/templaters/base.py\n--- a/src/sqlfluff/core/templaters/base.py\n+++ b/src/sqlfluff/core/templaters/base.py\n@@ -73,6 +73,7 @@ def __init__(\n templated_str: Optional[str] = None,\n sliced_file: Optional[List[TemplatedFileSlice]] = None,\n raw_sliced: Optional[List[RawFileSlice]] = None,\n+ check_consistency=True,\n ):\n \"\"\"Initialise the TemplatedFile.\n \n@@ -104,6 +105,36 @@ def __init__(\n self._source_newlines = list(iter_indices_of_newlines(self.source_str))\n self._templated_newlines = list(iter_indices_of_newlines(self.templated_str))\n \n+ # NOTE: The \"check_consistency\" flag should always be True when using\n+ # SQLFluff in real life. This flag was only added because some legacy\n+ # templater tests in test/core/templaters/jinja_test.py use hardcoded\n+ # test data with issues that will trigger errors here. It would be cool\n+ # to fix that data someday. I (Barry H.) started looking into it, but\n+ # it was much trickier than I expected, because bits of the same data\n+ # are shared across multiple tests.\n+ if check_consistency:\n+ # Sanity check raw string and slices.\n+ pos = 0\n+ rfs: RawFileSlice\n+ for idx, rfs in enumerate(self.raw_sliced):\n+ assert rfs.source_idx == pos\n+ pos += len(rfs.raw)\n+ assert pos == len(self.source_str)\n+\n+ # Sanity check templated string and slices.\n+ previous_slice = None\n+ tfs: Optional[TemplatedFileSlice] = None\n+ for idx, tfs in enumerate(self.sliced_file):\n+ if previous_slice:\n+ assert (\n+ tfs.templated_slice.start == previous_slice.templated_slice.stop\n+ )\n+ else:\n+ assert tfs.templated_slice.start == 0\n+ previous_slice = tfs\n+ if self.sliced_file and templated_str is not None:\n+ assert tfs.templated_slice.stop == len(templated_str)\n+\n @classmethod\n def from_string(cls, raw):\n \"\"\"Create TemplatedFile from a string.\"\"\"\ndiff --git a/src/sqlfluff/core/templaters/slicers/tracer.py b/src/sqlfluff/core/templaters/slicers/tracer.py\n--- a/src/sqlfluff/core/templaters/slicers/tracer.py\n+++ b/src/sqlfluff/core/templaters/slicers/tracer.py\n@@ -77,9 +77,6 @@ def trace(self) -> JinjaTrace:\n except IndexError:\n pos2 = len(trace_template_output)\n p = trace_template_output[pos1 + 1 : pos2]\n- is_set_or_macro = p[:3] == \"set\"\n- if is_set_or_macro:\n- p = p[3:]\n m_id = regex.match(r\"^([0-9a-f]+)(_(\\d+))?\", p)\n if not m_id:\n raise ValueError( # pragma: no cover\n@@ -98,18 +95,7 @@ def trace(self) -> JinjaTrace:\n alt_id, content_info, literal = value\n target_slice_idx = self.find_slice_index(alt_id)\n slice_length = content_info if literal else len(str(content_info))\n- if not is_set_or_macro:\n- self.move_to_slice(target_slice_idx, slice_length)\n- else:\n- # If we find output from a {% set %} directive or a macro,\n- # record a trace without reading or updating the program\n- # counter. Such slices are always treated as \"templated\"\n- # because they are inserted during expansion of templated\n- # code (i.e. {% set %} variable or macro defined within the\n- # file).\n- self.record_trace(\n- slice_length, target_slice_idx, slice_type=\"templated\"\n- )\n+ self.move_to_slice(target_slice_idx, slice_length)\n return JinjaTrace(\n self.make_template(self.raw_str).render(), self.raw_sliced, self.sliced_file\n )\n@@ -241,9 +227,17 @@ def _slice_template(self) -> List[RawFileSlice]:\n idx,\n )\n )\n- self.raw_slice_info[result[-1]] = self.slice_info_for_literal(\n- len(raw), \"\" if set_idx is None else \"set\"\n- )\n+ if set_idx is None:\n+ rsi = self.slice_info_for_literal(\n+ len(raw), \"\" if set_idx is None else \"set\"\n+ )\n+ else:\n+ # For \"set\" blocks, don't generate alternate ID or code.\n+ # Sometimes, dbt users use {% set %} blocks to generate\n+ # queries that get sent to actual databases, thus causing\n+ # errors if we tamper with it.\n+ rsi = RawSliceInfo(None, None, [])\n+ self.raw_slice_info[result[-1]] = rsi\n idx += len(raw)\n continue\n str_buff += raw\n@@ -326,15 +320,20 @@ def _slice_template(self) -> List[RawFileSlice]:\n # effects, but return a unique slice ID.\n if trimmed_content:\n assert m_open and m_close\n- unique_id = self.next_slice_id()\n- unique_alternate_id = unique_id\n- prefix = \"set\" if set_idx is not None else \"\"\n- open_ = m_open.group(1)\n- close_ = m_close.group(1)\n- alternate_code = (\n- f\"\\0{prefix}{unique_alternate_id} {open_} \"\n- f\"{trimmed_content} {close_}\"\n- )\n+ # For \"set\" blocks, don't generate alternate ID or\n+ # code. Sometimes, dbt users use {% set %} blocks to\n+ # generate queries that get sent to actual\n+ # databases, thus causing errors if we tamper with\n+ # it.\n+ if set_idx is None:\n+ unique_id = self.next_slice_id()\n+ unique_alternate_id = unique_id\n+ open_ = m_open.group(1)\n+ close_ = m_close.group(1)\n+ alternate_code = (\n+ f\"\\0{unique_alternate_id} {open_} \"\n+ f\"{trimmed_content} {close_}\"\n+ )\n if block_type == \"block_start\" and trimmed_content.split()[0] in (\n \"macro\",\n \"set\",\n@@ -343,16 +342,24 @@ def _slice_template(self) -> List[RawFileSlice]:\n # - {% set variable = value %}\n # - {% set variable %}value{% endset %}\n # https://jinja.palletsprojects.com/en/2.10.x/templates/#block-assignments\n- # When the second format is used, set the variable 'is_set'\n+ # When the second format is used, set the variable 'set_idx'\n # to a non-None value. This info is used elsewhere, as\n # literals inside a {% set %} block require special handling\n # during the trace.\n trimmed_content_parts = trimmed_content.split(maxsplit=2)\n- if len(trimmed_content_parts) <= 2 or not trimmed_content_parts[\n- 2\n- ].startswith(\"=\"):\n+ if len(trimmed_content_parts) <= 2 or (\n+ not trimmed_content_parts[1].endswith(\"=\")\n+ and not trimmed_content_parts[2].startswith(\"=\")\n+ ):\n set_idx = len(result)\n- elif block_type == \"block_end\" and set_idx is not None:\n+ elif (\n+ block_type == \"block_end\"\n+ and set_idx is not None\n+ and (\n+ trimmed_content.startswith(\"endset\")\n+ or trimmed_content.startswith(\"endmacro\")\n+ )\n+ ):\n # Exiting a {% set %} block. Clear the indicator variable.\n set_idx = None\n m = regex.search(r\"\\s+$\", raw, regex.MULTILINE | regex.DOTALL)\n", "test_patch": "diff --git a/test/core/templaters/base_test.py b/test/core/templaters/base_test.py\n--- a/test/core/templaters/base_test.py\n+++ b/test/core/templaters/base_test.py\n@@ -134,6 +134,7 @@ def test__templated_file_get_line_pos_of_char_pos(\n templated_str=templated_str,\n sliced_file=file_slices,\n fname=\"test\",\n+ check_consistency=False,\n )\n res_line_no, res_line_pos = file.get_line_pos_of_char_pos(in_charpos)\n assert res_line_no == out_line_no\n@@ -287,6 +288,7 @@ def test__templated_file_templated_slice_to_source_slice(\n for rs in raw_slices\n ],\n fname=\"test\",\n+ check_consistency=False,\n )\n source_slice = file.templated_slice_to_source_slice(in_slice)\n literal_test = file.is_source_slice_literal(source_slice)\n@@ -303,5 +305,6 @@ def test__templated_file_source_only_slices():\n RawFileSlice(\"b\" * 7, \"comment\", 10),\n RawFileSlice(\"a\" * 10, \"literal\", 17),\n ],\n+ check_consistency=False,\n )\n assert file.source_only_slices() == [RawFileSlice(\"b\" * 7, \"comment\", 10)]\ndiff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -370,6 +370,35 @@ def test__templater_jinja_slices(case: RawTemplatedTestCase):\n assert actual_rs_source_list == case.expected_raw_sliced__source_list\n \n \n+def test_templater_set_block_handling():\n+ \"\"\"Test handling of literals in {% set %} blocks.\n+\n+ Specifically, verify they are not modified in the alternate template.\n+ \"\"\"\n+\n+ def run_query(sql):\n+ # Prior to the bug fix, this assertion failed. This was bad because,\n+ # inside JinjaTracer, dbt templates similar to the one in this test\n+ # would call the database with funky SQL (including weird strings it\n+ # uses internally like: 00000000000000000000000000000002.\n+ assert sql == \"\\n\\nselect 1 from foobarfoobarfoobarfoobar_dev\\n\\n\"\n+ return sql\n+\n+ t = JinjaTemplater(override_context=dict(run_query=run_query))\n+ instr = \"\"\"{% set my_query1 %}\n+select 1 from foobarfoobarfoobarfoobar_{{ \"dev\" }}\n+{% endset %}\n+{% set my_query2 %}\n+{{ my_query1 }}\n+{% endset %}\n+\n+{{ run_query(my_query2) }}\n+\"\"\"\n+ outstr, vs = t.process(in_str=instr, fname=\"test\", config=FluffConfig())\n+ assert str(outstr) == \"\\n\\n\\n\\n\\nselect 1 from foobarfoobarfoobarfoobar_dev\\n\\n\\n\"\n+ assert len(vs) == 0\n+\n+\n def test__templater_jinja_error_variable():\n \"\"\"Test missing variable error handling in the jinja templater.\"\"\"\n t = JinjaTemplater(override_context=dict(blah=\"foo\"))\n@@ -846,6 +875,45 @@ def test__templater_jinja_slice_template(test, result):\n (\"literal\", slice(312, 327, None), slice(27, 42, None)),\n ],\n ),\n+ (\n+ # Test for issue 2835. There's no space between \"col\" and \"=\"\n+ \"\"\"{% set col= \"col1\" %}\n+SELECT {{ col }}\n+\"\"\",\n+ None,\n+ [\n+ (\"block_start\", slice(0, 21, None), slice(0, 0, None)),\n+ (\"literal\", slice(21, 29, None), slice(0, 8, None)),\n+ (\"templated\", slice(29, 38, None), slice(8, 12, None)),\n+ (\"literal\", slice(38, 39, None), slice(12, 13, None)),\n+ ],\n+ ),\n+ (\n+ # Another test for issue 2835. The {% for %} loop inside the\n+ # {% set %} caused JinjaTracer to think the {% set %} ended\n+ # at the {% endfor %}\n+ \"\"\"{% set some_part_of_the_query %}\n+ {% for col in [\"col1\"] %}\n+ {{col}}\n+ {% endfor %}\n+{% endset %}\n+\n+SELECT {{some_part_of_the_query}}\n+FROM SOME_TABLE\n+\"\"\",\n+ None,\n+ [\n+ (\"block_start\", slice(0, 32, None), slice(0, 0, None)),\n+ (\"literal\", slice(32, 37, None), slice(0, 0, None)),\n+ (\"block_start\", slice(37, 62, None), slice(0, 0, None)),\n+ (\"block_end\", slice(79, 91, None), slice(0, 0, None)),\n+ (\"literal\", slice(91, 92, None), slice(0, 0, None)),\n+ (\"block_end\", slice(92, 104, None), slice(0, 0, None)),\n+ (\"literal\", slice(104, 113, None), slice(0, 9, None)),\n+ (\"templated\", slice(113, 139, None), slice(9, 29, None)),\n+ (\"literal\", slice(139, 156, None), slice(29, 46, None)),\n+ ],\n+ ),\n ],\n )\n def test__templater_jinja_slice_file(raw_file, override_context, result, caplog):\n", "problem_statement": "Lint and fix throws exception when having jinja for loop inside set\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nTo reproduce the error, create test.template.sql\r\n```\r\n{% set whitelisted= [\r\n {'name': 'COL_1'},\r\n {'name': 'COL_2'},\r\n {'name': 'COL_3'}\r\n] %}\r\n\r\n{% set some_part_of_the_query %}\r\n {% for col in whitelisted %}\r\n {{col.name}}{{ \", \" if not loop.last }}\r\n {% endfor %}\r\n{% endset %}\r\n\r\nSELECT {{some_part_of_the_query}}\r\nFROM SOME_TABLE\r\n\r\n```\r\n\r\nwhen running lint i get this error:\r\n```\r\n==== sqlfluff ====\r\nsqlfluff: 0.11.0 python: 3.8.12\r\nimplementation: cpython dialect: snowflake\r\nverbosity: 1 templater: jinja\r\n\r\n==== readout ====\r\n\r\n=== [ path: test.template.sql ] ===\r\n\r\nWARNING Unable to lint test.template.sql due to an internal error. Please report this as an issue with your query's contents and stacktrace below!\r\nTo hide this warning, add the failing file to .sqlfluffignore\r\nTraceback (most recent call last):\r\n File \"lib/python3.8/site-packages/sqlfluff/core/linter/runner.py\", line 103, in run\r\n yield partial()\r\n File \"lib/python3.8/site-packages/sqlfluff/core/linter/linter.py\", line 666, in lint_rendered\r\n parsed = cls.parse_rendered(rendered)\r\n File \"lib/python3.8/site-packages/sqlfluff/core/linter/linter.py\", line 352, in parse_rendered\r\n tokens, lvs, config = cls._lex_templated_file(\r\n File \"lib/python3.8/site-packages/sqlfluff/core/linter/linter.py\", line 139, in _lex_templated_file\r\n tokens, lex_vs = lexer.lex(templated_file)\r\n File \"lib/python3.8/site-packages/sqlfluff/core/parser/lexer.py\", line 321, in lex\r\n segments: Tuple[RawSegment, ...] = self.elements_to_segments(\r\n File \"lib/python3.8/site-packages/sqlfluff/core/parser/lexer.py\", line 348, in elements_to_segments\r\n source_slice = templated_file.templated_slice_to_source_slice(\r\n File \"lib/python3.8/site-packages/sqlfluff/core/templaters/base.py\", line 258, in templated_slice_to_source_slice\r\n ts_stop_sf_start, ts_stop_sf_stop = self._find_slice_indices_of_templated_pos(\r\n File \"lib/python3.8/site-packages/sqlfluff/core/templaters/base.py\", line 177, in _find_slice_indices_of_templated_pos\r\n raise ValueError(\"Position Not Found\")\r\nValueError: Position Not Found\r\n \r\n==== summary ====\r\nviolations: 0 status: PASS\r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n\r\n```\r\n\r\nThis is the rendered query:\r\n```\r\n SELECT\r\n\r\n COL_1,\r\n\r\n COL_2,\r\n\r\n COL_3\r\n\r\n\r\nFROM SOME_TABLE\r\n\r\n```\r\n\r\nAnd when trying around to make this work i removed the new lines between the selected columns like this:\r\n```\r\n{% set whitelisted= [\r\n {'name': 'COL_1'},\r\n {'name': 'COL_2'},\r\n {'name': 'COL_3'}\r\n] %}\r\n\r\n{% set some_part_of_the_query %}\r\n {% for col in whitelisted -%}\r\n {{col.name}}{{ \", \" if not loop.last }}\r\n {% endfor -%}\r\n{% endset %}\r\n\r\nSELECT {{some_part_of_the_query}}\r\nFROM SOME_TABLE\r\n\r\n```\r\n\r\nwhich renders:\r\n```\r\nSELECT\r\n COL_1,\r\n COL_2,\r\n COL_3\r\n\r\nFROM SOME_TABLE\r\n\r\n```\r\n\r\nAnd this will make the linter pass:\r\n\r\n```\r\n==== sqlfluff ====\r\nsqlfluff: 0.11.0 python: 3.8.12\r\nimplementation: cpython dialect: snowflake\r\nverbosity: 1 templater: jinja\r\n\r\n==== readout ====\r\n\r\n=== [ path: test.template.sql ] ===\r\n\r\n== [test.template.sql] PASS \r\n==== summary ====\r\nviolations: 0 status: PASS\r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n\r\n```\r\n\r\n\n\n### Expected Behaviour\n\nMy expectations is that the linter and fix should pass.\n\n### Observed Behaviour\n\nRight now lint and fix throws exception (see \"What Happened\" section)\n\n### How to reproduce\n\nMentioned above.\n\n### Dialect\n\nsnowflake\n\n### Version\n\nsqlfluff, version 0.11.0\n\n### Configuration\n\n[sqlfluff]\r\nverbose = 1\r\ndialect = snowflake\r\ntemplater = jinja\r\nexclude_rules = L027,L031,L032,L036,L044,L046,L034,L050\r\noutput_line_length = 121\r\nsql_file_exts=.sql\r\n\r\n[sqlfluff:rules]\r\ntab_space_size = 4\r\nmax_line_length = 250\r\nindent_unit = space\r\ncomma_style = trailing\r\nallow_scalar = True\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = aliases\r\n\r\n[sqlfluff:rules:L042]\r\nforbid_subquery_in = both\r\n\r\n[sqlfluff:rules:L010] # Keywords\r\ncapitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L014]\r\nextended_capitalisation_policy = lower\r\n\r\n[sqlfluff:rules:L030] # function names\r\nextended_capitalisation_policy = upper\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "", "created_at": "2022-03-12T21:48:15Z", "version": "0.10", "FAIL_TO_PASS": ["test/core/templaters/base_test.py::test__templated_file_get_line_pos_of_char_pos[01234\\n6789{{foo}}fo\\nbarss-01234\\n6789x\\nfo\\nbarfss-file_slices0-0-1-1]", "test/core/templaters/base_test.py::test__templated_file_get_line_pos_of_char_pos[01234\\n6789{{foo}}fo\\nbarss-01234\\n6789x\\nfo\\nbarfss-file_slices1-20-3-1]", "test/core/templaters/base_test.py::test__templated_file_get_line_pos_of_char_pos[01234\\n6789{{foo}}fo\\nbarss-01234\\n6789x\\nfo\\nbarfss-file_slices2-24-3-5]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice0-out_slice0-True-file_slices0-raw_slices0]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice1-out_slice1-True-file_slices1-raw_slices1]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice2-out_slice2-True-file_slices2-raw_slices2]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice3-out_slice3-False-file_slices3-raw_slices3]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice4-out_slice4-False-file_slices4-raw_slices4]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice5-out_slice5-True-file_slices5-raw_slices5]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice6-out_slice6-True-file_slices6-raw_slices6]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice7-out_slice7-True-file_slices7-raw_slices7]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice8-out_slice8-True-file_slices8-raw_slices8]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice9-out_slice9-True-file_slices9-raw_slices9]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice10-out_slice10-True-file_slices10-raw_slices10]", "test/core/templaters/base_test.py::test__templated_file_templated_slice_to_source_slice[in_slice11-out_slice11-False-file_slices11-raw_slices11]", "test/core/templaters/base_test.py::test__templated_file_source_only_slices", "test/core/templaters/jinja_test.py::test_templater_set_block_handling", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%"], "PASS_TO_PASS": ["test/core/templaters/base_test.py::test__indices_of_newlines[-positions0]", "test/core/templaters/base_test.py::test__indices_of_newlines[foo-positions1]", "test/core/templaters/base_test.py::test__indices_of_newlines[foo\\nbar-positions2]", "test/core/templaters/base_test.py::test__indices_of_newlines[\\nfoo\\n\\nbar\\nfoo\\n\\nbar\\n-positions3]", "test/core/templaters/base_test.py::test__templater_raw", "test/core/templaters/base_test.py::test__templated_file_find_slice_indices_of_templated_pos[100-True-file_slices0-10-11]", "test/core/templaters/base_test.py::test__templated_file_find_slice_indices_of_templated_pos[13-True-file_slices1-0-3]", "test/core/templaters/base_test.py::test__templated_file_find_slice_indices_of_templated_pos[28-True-file_slices2-2-5]", "test/core/templaters/base_test.py::test__templated_file_find_slice_indices_of_templated_pos[12-True-file_slices3-1-3]", "test/core/templaters/base_test.py::test__templated_file_find_slice_indices_of_templated_pos[20-True-file_slices4-2-3]", "test/core/templaters/base_test.py::test__templated_file_find_slice_indices_of_templated_pos[13-False-file_slices5-0-1]", "test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n"], "environment_setup_commit": "3d52e8270d82aeccf4c516d059a80a6947919aea"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-884", "base_commit": "c0bad78f3fa9549591738c77f869724f721e6830", "patch": "diff --git a/src/sqlfluff/core/dialects/dialect_ansi.py b/src/sqlfluff/core/dialects/dialect_ansi.py\n--- a/src/sqlfluff/core/dialects/dialect_ansi.py\n+++ b/src/sqlfluff/core/dialects/dialect_ansi.py\n@@ -50,7 +50,7 @@\n ansi_dialect.set_lexer_struct(\n [\n # name, type, pattern, kwargs\n- (\"whitespace\", \"regex\", r\"[\\t ]+\", dict(type=\"whitespace\")),\n+ (\"whitespace\", \"regex\", r\"[\\t ]+\", dict(type=\"whitespace\", is_whitespace=True)),\n (\n \"inline_comment\",\n \"regex\",\n@@ -64,9 +64,14 @@\n dict(\n is_comment=True,\n type=\"comment\",\n- subdivide=dict(type=\"newline\", name=\"newline\", regex=r\"\\r\\n|\\n\"),\n+ subdivide=dict(\n+ type=\"newline\", name=\"newline\", regex=r\"\\r\\n|\\n\", is_whitespace=True\n+ ),\n trim_post_subdivide=dict(\n- type=\"whitespace\", name=\"whitespace\", regex=r\"[\\t ]+\"\n+ type=\"whitespace\",\n+ name=\"whitespace\",\n+ regex=r\"[\\t ]+\",\n+ is_whitespace=True,\n ),\n ),\n ),\n@@ -83,7 +88,7 @@\n (\"not_equal\", \"regex\", r\"!=|<>\", dict(is_code=True)),\n (\"greater_than_or_equal\", \"regex\", r\">=\", dict(is_code=True)),\n (\"less_than_or_equal\", \"regex\", r\"<=\", dict(is_code=True)),\n- (\"newline\", \"regex\", r\"\\r\\n|\\n\", dict(type=\"newline\")),\n+ (\"newline\", \"regex\", r\"\\r\\n|\\n\", dict(type=\"newline\", is_whitespace=True)),\n (\"casting_operator\", \"regex\", r\"::\", dict(is_code=True)),\n (\"concat_operator\", \"regex\", r\"\\|\\|\", dict(is_code=True)),\n (\"equals\", \"singleton\", \"=\", dict(is_code=True)),\ndiff --git a/src/sqlfluff/core/parser/lexer.py b/src/sqlfluff/core/parser/lexer.py\n--- a/src/sqlfluff/core/parser/lexer.py\n+++ b/src/sqlfluff/core/parser/lexer.py\n@@ -74,12 +74,10 @@ def _trim(self, matched, start_pos):\n idx = 0\n \n if self.trim_post_subdivide:\n- trimmer = re.compile(self.trim_post_subdivide[\"regex\"], re.DOTALL)\n- TrimClass = RawSegment.make(\n- self.trim_post_subdivide[\"regex\"],\n- name=self.trim_post_subdivide[\"name\"],\n- type=self.trim_post_subdivide[\"type\"],\n- )\n+ class_kwargs = self.trim_post_subdivide.copy()\n+ pattern = class_kwargs.pop(\"regex\")\n+ trimmer = re.compile(pattern, re.DOTALL)\n+ TrimClass = RawSegment.make(pattern, **class_kwargs)\n \n for trim_mat in trimmer.finditer(matched):\n trim_span = trim_mat.span()\n@@ -132,12 +130,10 @@ def _subdivide(self, matched, start_pos):\n seg_buff = ()\n str_buff = matched\n pos_buff = start_pos\n- divider = re.compile(self.subdivide[\"regex\"], re.DOTALL)\n- DividerClass = RawSegment.make(\n- self.subdivide[\"regex\"],\n- name=self.subdivide[\"name\"],\n- type=self.subdivide[\"type\"],\n- )\n+ class_kwargs = self.subdivide.copy()\n+ pattern = class_kwargs.pop(\"regex\")\n+ divider = re.compile(pattern, re.DOTALL)\n+ DividerClass = RawSegment.make(pattern, **class_kwargs)\n \n while True:\n # Iterate through subdividing as appropriate\n", "test_patch": "diff --git a/test/core/dialects/ansi_test.py b/test/core/dialects/ansi_test.py\n--- a/test/core/dialects/ansi_test.py\n+++ b/test/core/dialects/ansi_test.py\n@@ -162,3 +162,14 @@ def test__dialect__ansi_specific_segment_not_parse(raw, err_locations, caplog):\n assert len(parsed.violations) > 0\n locs = [(v.line_no(), v.line_pos()) for v in parsed.violations]\n assert locs == err_locations\n+\n+\n+def test__dialect__ansi_is_whitespace():\n+ \"\"\"Test proper tagging with is_whitespace.\"\"\"\n+ lnt = Linter()\n+ with open(\"test/fixtures/parser/ansi/select_in_multiline_comment.sql\") as f:\n+ parsed = lnt.parse_string(f.read())\n+ # Check all the segments that *should* be whitespace, ARE\n+ for raw_seg in parsed.tree.iter_raw_seg():\n+ if raw_seg.type in (\"whitespace\", \"newline\"):\n+ assert raw_seg.is_whitespace\n", "problem_statement": "Whitespace token is_whitespace is False\nI expect segment.is_whitespace of a Whitespace token is True, however, it is set to False.\r\n\r\n## Expected Behaviour\r\nsegment.is_whitespace return True\r\n\r\n## Observed Behaviour\r\nsegment.is_whitespace return False\r\n## Steps to Reproduce\r\n\r\n## Version\r\nInclude the output of `sqlfluff --version` along with your Python version\r\n\r\n## Configuration\r\n```\r\nInclude your SQLFluff configuration here\r\n```\r\n\n", "hints_text": "To triage this issue, I searched the SQLFluff code to find all uses of `is_whitespace`. This is the only one I found:\r\n```\r\nsrc/sqlfluff/core/parser/segments/base.py:72: is_whitespace = False\r\n```\r\n\r\n@alanmcruickshank: What's the purpose of `is_whitespace`?\r\n\r\nI see that long ago (2019), there was a class `WhitespaceSegment` (also a `NewlineSegment`). Now it's not a class -- instead, it'd defined in `src/sqlfluff/core/rules/base.py`.\nOnce #866 is merged I'll pick up the rest of this which relates to some of the lexer objects.", "created_at": "2021-03-23T21:28:49Z", "version": "0.4", "FAIL_TO_PASS": ["test/core/dialects/ansi_test.py::test__dialect__ansi_is_whitespace"], "PASS_TO_PASS": ["test/core/dialects/ansi_test.py::test__dialect__ansi__file_lex[a", "test/core/dialects/ansi_test.py::test__dialect__ansi__file_lex[b.c-res1]", "test/core/dialects/ansi_test.py::test__dialect__ansi__file_lex[abc", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectKeywordSegment-select]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[NakedIdentifierSegment-online_sales]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[BareFunctionSegment-current_timestamp]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[FunctionSegment-current_timestamp()]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[NumericLiteralSegment-1000.0]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-online_sales", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[IntervalExpressionSegment-INTERVAL", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-CASE", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-CAST(ROUND(online_sales", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-name", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-MIN", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-DATE_ADD(CURRENT_DATE('America/New_York'),", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[1]]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[OFFSET(1)]]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[5:8]]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-4", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-bits[OFFSET(0)]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-(count_18_24", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-count_18_24", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectStatementSegment-SELECT", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-t.val/t.id]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-CAST(num", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-a.*]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-a.b.*]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-a.b.c.*]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ObjectReferenceSegment-a..c.*]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment--some_variable]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment--", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-concat(left(uaid,", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-c", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-NULL::INT]", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectTargetElementSegment-NULL::INT", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_not_match[ObjectReferenceSegment-\\n", "test/core/dialects/ansi_test.py::test__dialect__ansi_specific_segment_not_parse[SELECT"], "environment_setup_commit": "cbdcfb09feb4883de91de142956c3be6ac7f827d"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4151", "base_commit": "dc59c2a5672aacedaf91f0e6129b467eefad331b", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -680,7 +680,7 @@ def do_fixes(lnt, result, formatter=None, **kwargs):\n return False # pragma: no cover\n \n \[email protected]()\[email protected](cls=DeprecatedOptionsCommand)\n @common_options\n @core_options\n @click.option(\n@@ -710,9 +710,12 @@ def do_fixes(lnt, result, formatter=None, **kwargs):\n ),\n )\n @click.option(\n+ \"--disable_progress_bar\",\n \"--disable-progress-bar\",\n is_flag=True,\n help=\"Disables progress bars.\",\n+ cls=DeprecatedOption,\n+ deprecated=[\"--disable_progress_bar\"],\n )\n @click.option(\n \"--FIX-EVEN-UNPARSABLE\",\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -1775,6 +1775,46 @@ def test_cli_lint_enabled_progress_bar_multiple_files(\n assert r\"\\rrule L001:\" in raw_output\n assert r\"\\rrule L049:\" in raw_output\n \n+ def test_cli_fix_disabled_progress_bar(\n+ self, mock_disable_progress_bar: MagicMock\n+ ) -> None:\n+ \"\"\"When progress bar is disabled, nothing should be printed into output.\"\"\"\n+ result = invoke_assert_code(\n+ args=[\n+ fix,\n+ [\n+ \"--disable-progress-bar\",\n+ \"test/fixtures/linter/passing.sql\",\n+ ],\n+ ],\n+ )\n+ raw_output = repr(result.output)\n+\n+ assert (\n+ \"DeprecationWarning: The option '--disable_progress_bar' is deprecated, \"\n+ \"use '--disable-progress-bar'\"\n+ ) not in raw_output\n+\n+ def test_cli_fix_disabled_progress_bar_deprecated_option(\n+ self, mock_disable_progress_bar: MagicMock\n+ ) -> None:\n+ \"\"\"Same as above but checks additionally if deprecation warning is printed.\"\"\"\n+ result = invoke_assert_code(\n+ args=[\n+ fix,\n+ [\n+ \"--disable_progress_bar\",\n+ \"test/fixtures/linter/passing.sql\",\n+ ],\n+ ],\n+ )\n+ raw_output = repr(result.output)\n+\n+ assert (\n+ \"DeprecationWarning: The option '--disable_progress_bar' is deprecated, \"\n+ \"use '--disable-progress-bar'\"\n+ ) in raw_output\n+\n \n multiple_expected_output = \"\"\"==== finding fixable violations ====\n == [test/fixtures/linter/multiple_sql_errors.sql] FAIL\n", "problem_statement": "--disable_progress_bar Flag Broken for Fix\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nI ran `sqlfluff fix ${target} --dialect ansi --disable_progress_bar --force` on version 1.4.0 and got an error with exit code 2. Running with `--disable-progress-bar` appears to work fine, but it appears that compatibility with underscores was broken in version 1.4.0.\n\n### Expected Behaviour\n\nShould run as expected, with no error and no progress bar.\n\n### Observed Behaviour\n\nExit code 2 and stderr:\r\n```\r\nUsage: sqlfluff fix [OPTIONS] [PATHS]...\r\n Try 'sqlfluff fix -h' for help.\r\n\r\n Error: No such option: --disable_progress_bar (Possible options: --disable-noqa, --disable-progress-bar)\r\n```\n\n### How to reproduce\n\nSql file:\r\n```\r\nSELECT foo FROM bar;\r\n```\r\n\r\nCommand:\r\n```\r\nsqlfluff fix ${target} --dialect ansi --disable_progress_bar --force\r\n```\n\n### Dialect\n\nansi\n\n### Version\n\npython 3.10.3\r\nsqlfluff 1.4.0 and up appears to have this problem (tested through 1.4.2)\n\n### Configuration\n\nNo special configuration. Ran hermetically with `trunk`.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n--disable_progress_bar Flag Broken for Fix\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nI ran `sqlfluff fix ${target} --dialect ansi --disable_progress_bar --force` on version 1.4.0 and got an error with exit code 2. Running with `--disable-progress-bar` appears to work fine, but it appears that compatibility with underscores was broken in version 1.4.0.\n\n### Expected Behaviour\n\nShould run as expected, with no error and no progress bar.\n\n### Observed Behaviour\n\nExit code 2 and stderr:\r\n```\r\nUsage: sqlfluff fix [OPTIONS] [PATHS]...\r\n Try 'sqlfluff fix -h' for help.\r\n\r\n Error: No such option: --disable_progress_bar (Possible options: --disable-noqa, --disable-progress-bar)\r\n```\n\n### How to reproduce\n\nSql file:\r\n```\r\nSELECT foo FROM bar;\r\n```\r\n\r\nCommand:\r\n```\r\nsqlfluff fix ${target} --dialect ansi --disable_progress_bar --force\r\n```\n\n### Dialect\n\nansi\n\n### Version\n\npython 3.10.3\r\nsqlfluff 1.4.0 and up appears to have this problem (tested through 1.4.2)\n\n### Configuration\n\nNo special configuration. Ran hermetically with `trunk`.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "Looks like #3904 made `lint` work with both but updated `fix` to only accept `--disable-progress-bar`. I assume that was by accident. Should be relatively straightforward to fix by updating to match `lint`. \nLooks like #3904 made `lint` work with both but updated `fix` to only accept `--disable-progress-bar`. I assume that was by accident. Should be relatively straightforward to fix by updating to match `lint`. ", "created_at": "2022-12-11T16:33:31Z", "version": "1.3", "FAIL_TO_PASS": ["test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar_deprecated_option"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_lint_warning", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass"], "environment_setup_commit": "dc59c2a5672aacedaf91f0e6129b467eefad331b"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3354", "base_commit": "36e89cbf2d13d5d95d2430f905a2fd122cf103c7", "patch": "diff --git a/src/sqlfluff/core/templaters/placeholder.py b/src/sqlfluff/core/templaters/placeholder.py\n--- a/src/sqlfluff/core/templaters/placeholder.py\n+++ b/src/sqlfluff/core/templaters/placeholder.py\n@@ -21,6 +21,8 @@\n KNOWN_STYLES = {\n # e.g. WHERE bla = :name\n \"colon\": regex.compile(r\"(?<![:\\w\\x5c]):(?P<param_name>\\w+)(?!:)\", regex.UNICODE),\n+ # e.g. WHERE bla = table:name - use with caution as more prone to false positives\n+ \"colon_nospaces\": regex.compile(r\":(?P<param_name>\\w+)\", regex.UNICODE),\n # e.g. WHERE bla = :2\n \"numeric_colon\": regex.compile(\n r\"(?<![:\\w\\x5c]):(?P<param_name>\\d+)\", regex.UNICODE\n@@ -29,8 +31,10 @@\n \"pyformat\": regex.compile(\n r\"(?<![:\\w\\x5c])%\\((?P<param_name>[\\w_]+)\\)s\", regex.UNICODE\n ),\n- # e.g. WHERE bla = $name\n- \"dollar\": regex.compile(r\"(?<![:\\w\\x5c])\\$(?P<param_name>[\\w_]+)\", regex.UNICODE),\n+ # e.g. WHERE bla = $name or WHERE bla = ${name}\n+ \"dollar\": regex.compile(\n+ r\"(?<![:\\w\\x5c])\\${?(?P<param_name>[\\w_]+)}?\", regex.UNICODE\n+ ),\n # e.g. WHERE bla = ?\n \"question_mark\": regex.compile(r\"(?<![:\\w\\x5c])\\?\", regex.UNICODE),\n # e.g. WHERE bla = $3\n@@ -146,7 +150,7 @@ def process(\n param_name = found_param[\"param_name\"]\n last_literal_length = span[0] - last_pos_raw\n try:\n- replacement = context[param_name]\n+ replacement = str(context[param_name])\n except KeyError as err:\n # TODO: Add a url here so people can get more help.\n raise SQLTemplaterError(\n", "test_patch": "diff --git a/test/core/templaters/placeholder_test.py b/test/core/templaters/placeholder_test.py\n--- a/test/core/templaters/placeholder_test.py\n+++ b/test/core/templaters/placeholder_test.py\n@@ -79,6 +79,20 @@ def test__templater_raw():\n city_ids=\"(1, 2, 3, 45)\",\n ),\n ),\n+ (\n+ \"\"\"\n+ SELECT user_mail, city_id\n+ FROM users_data:table_suffix\n+ \"\"\",\n+ \"colon_nospaces\",\n+ \"\"\"\n+ SELECT user_mail, city_id\n+ FROM users_data42\n+ \"\"\",\n+ dict(\n+ table_suffix=\"42\",\n+ ),\n+ ),\n (\n \"\"\"\n SELECT user_mail, city_id\n@@ -123,6 +137,8 @@ def test__templater_raw():\n FROM users_data\n WHERE (city_id) IN %(city_id)s\n AND date > %(date)s\n+ AND someflag = %(someflag)s\n+ LIMIT %(limit)s\n \"\"\",\n \"pyformat\",\n \"\"\"\n@@ -130,10 +146,11 @@ def test__templater_raw():\n FROM users_data\n WHERE (city_id) IN (1, 2, 3, 45)\n AND date > '2020-10-01'\n+ AND someflag = False\n+ LIMIT 15\n \"\"\",\n dict(\n- city_id=\"(1, 2, 3, 45)\",\n- date=\"'2020-10-01'\",\n+ city_id=\"(1, 2, 3, 45)\", date=\"'2020-10-01'\", limit=15, someflag=False\n ),\n ),\n (\n@@ -142,6 +159,7 @@ def test__templater_raw():\n FROM users_data\n WHERE (city_id) IN $city_id\n AND date > $date\n+ OR date = ${date}\n \"\"\",\n \"dollar\",\n \"\"\"\n@@ -149,6 +167,7 @@ def test__templater_raw():\n FROM users_data\n WHERE (city_id) IN (1, 2, 3, 45)\n AND date > '2020-10-01'\n+ OR date = '2020-10-01'\n \"\"\",\n dict(\n city_id=\"(1, 2, 3, 45)\",\n@@ -221,6 +240,7 @@ def test__templater_raw():\n \"colon_simple_substitution\",\n \"colon_accept_block_at_end\",\n \"colon_tuple_substitution\",\n+ \"colon_nospaces\",\n \"question_mark\",\n \"numeric_colon\",\n \"pyformat\",\n", "problem_statement": "TypeError when using integer placeholder\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nAn exception occurs when trying to use integer substituents.\r\n\r\n### Expected Behaviour\r\n\r\nWork without errors.\r\n\r\n### Observed Behaviour\r\n\r\n\r\nAn exception occurs:\r\n```\r\n ...\r\n File \"venv/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 816, in render_file\r\n return self.render_string(raw_file, fname, config, encoding)\r\n File \"venv/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 787, in render_string\r\n templated_file, templater_violations = self.templater.process(\r\n File \"venv/lib/python3.9/site-packages/sqlfluff/core/templaters/placeholder.py\", line 183, in process\r\n start_template_pos, start_template_pos + len(replacement), None\r\nTypeError: object of type 'int' has no len()\r\n\r\n```\r\n\r\n### How to reproduce\r\n\r\n1. Create a file `example.sql`:\r\n```\r\nSELECT 1\r\nLIMIT %(capacity)s;\r\n```\r\n2. Copy `.sqlfluff` from the Configuration section\r\n3. Run `sqlfluff lint --dialect postgres example.sql`\r\n\r\n### Dialect\r\n\r\npostgres\r\n\r\n### Version\r\n\r\nsqlfluff, version 0.13.1\r\n\r\n### Configuration\r\n\r\n```\r\n[sqlfluff]\r\nexclude_rules = L031\r\ntemplater = placeholder\r\n\r\n[sqlfluff:templater:placeholder]\r\nparam_style = pyformat\r\ncapacity = 15\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [ ] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\nSupport Postgres-style variable substitution\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nThe Postgres `psql` utility supports flavor of colon-style variable substitution that currently confuses sqlfluff. E.g.,\r\n\r\n```sql\r\nALTER TABLE name:variable RENAME TO name;\r\n```\r\n\r\nRunning the above through sqlfluff produces this output:\r\n\r\n```\r\nsqlfluff lint --dialect postgres 2.sql\r\n== [2.sql] FAIL\r\nL: 1 | P: 1 | PRS | Line 1, Position 1: Found unparsable section: 'ALTER\r\n | TABLE name:variable RENAME TO name...'\r\n```\n\n### Use case\n\nI would like it if in the above the string \"name:variable\" were considered a valid table name (and other identifiers similarly).\n\n### Dialect\n\nThis applies to the Postgres dialect.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [X] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "\nThis sounds more like a templater feature than a dialect feature. Does psql allow variables to contain SQL fragments, e.g.: `WHERE foo = '3'`?\n> This sounds more like a templater feature than a dialect feature.\r\n\r\nTrue! After looking over the code some, that may well be the right place to implement this.\r\n\r\n> Does psql allow variables to contain SQL fragments, e.g.: WHERE foo = '3'?\r\n\r\nYes. E.g.,\r\n\r\n```\r\n% psql -v expression='2 + 2'\r\npsql (14.2, server 10.18)\r\nSSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)\r\nType \"help\" for help.\r\n\r\ndb=> select :expression;\r\n ?column?\r\n----------\r\n 4\r\n(1 row)\r\n\r\ndb=> select 5:expression;\r\n ?column?\r\n----------\r\n 54\r\n(1 row)\r\n```\r\n\r\nMore at the [docs](https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-VARIABLES).", "created_at": "2022-05-17T11:50:34Z", "version": "0.12", "FAIL_TO_PASS": ["test/core/templaters/placeholder_test.py::test__templater_param_style[colon_nospaces]", "test/core/templaters/placeholder_test.py::test__templater_param_style[pyformat]", "test/core/templaters/placeholder_test.py::test__templater_param_style[dollar]"], "PASS_TO_PASS": ["test/core/templaters/placeholder_test.py::test__templater_raw", "test/core/templaters/placeholder_test.py::test__templater_param_style[no_changes]", "test/core/templaters/placeholder_test.py::test__templater_param_style[colon_simple_substitution]", "test/core/templaters/placeholder_test.py::test__templater_param_style[colon_accept_block_at_end]", "test/core/templaters/placeholder_test.py::test__templater_param_style[colon_tuple_substitution]", "test/core/templaters/placeholder_test.py::test__templater_param_style[question_mark]", "test/core/templaters/placeholder_test.py::test__templater_param_style[numeric_colon]", "test/core/templaters/placeholder_test.py::test__templater_param_style[numeric_dollar]", "test/core/templaters/placeholder_test.py::test__templater_param_style[percent]", "test/core/templaters/placeholder_test.py::test__templater_param_style[ampersand]", "test/core/templaters/placeholder_test.py::test__templater_custom_regex", "test/core/templaters/placeholder_test.py::test__templater_exception", "test/core/templaters/placeholder_test.py::test__templater_setup", "test/core/templaters/placeholder_test.py::test__templater_styles"], "environment_setup_commit": "8f6fd1d8a8d69b2c463fbcf5bd1131c47f12ad88"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3700", "base_commit": "1000cf1beae75186cadf3a586c87e86e9f30ecb2", "patch": "diff --git a/src/sqlfluff/core/parser/segments/base.py b/src/sqlfluff/core/parser/segments/base.py\n--- a/src/sqlfluff/core/parser/segments/base.py\n+++ b/src/sqlfluff/core/parser/segments/base.py\n@@ -1749,6 +1749,11 @@ def add(self, value): # MutableSet\n \"\"\"Add an element.\"\"\"\n self.map[self.key(value)] = value\n \n+ def update(self, value):\n+ \"\"\"Add elements in 'value'.\"\"\"\n+ for v in value:\n+ self.add(v)\n+\n def discard(self, value): # MutableSet\n \"\"\"Remove an element. Do not raise an exception if absent.\"\"\"\n self.map.pop(self.key(value), None) # pragma: no cover\ndiff --git a/src/sqlfluff/rules/L028.py b/src/sqlfluff/rules/L028.py\n--- a/src/sqlfluff/rules/L028.py\n+++ b/src/sqlfluff/rules/L028.py\n@@ -3,8 +3,9 @@\n from typing import Iterator, List, Optional, Set\n \n from sqlfluff.core.dialects.common import AliasInfo, ColumnAliasInfo\n-from sqlfluff.core.parser.segments.base import BaseSegment\n+from sqlfluff.core.parser.segments.base import BaseSegment, IdentitySet\n from sqlfluff.core.parser.segments.raw import SymbolSegment\n+from sqlfluff.utils.analysis.select import SelectStatementColumnsAndTables\n from sqlfluff.utils.analysis.select_crawler import Query, SelectCrawler\n from sqlfluff.core.rules import (\n BaseRule,\n@@ -99,12 +100,16 @@ def _eval(self, context: RuleContext) -> EvalResultType:\n \n if not FunctionalContext(context).parent_stack.any(sp.is_type(*_START_TYPES)):\n crawler = SelectCrawler(context.segment, context.dialect)\n+ visited: IdentitySet = IdentitySet()\n if crawler.query_tree:\n # Recursively visit and check each query in the tree.\n- return list(self._visit_queries(crawler.query_tree))\n+ return list(self._visit_queries(crawler.query_tree, visited))\n return None\n \n- def _visit_queries(self, query: Query) -> Iterator[LintResult]:\n+ def _visit_queries(\n+ self, query: Query, visited: IdentitySet\n+ ) -> Iterator[LintResult]:\n+ select_info: Optional[SelectStatementColumnsAndTables] = None\n if query.selectables:\n select_info = query.selectables[0].select_info\n # How many table names are visible from here? If more than one then do\n@@ -138,8 +143,24 @@ def _visit_queries(self, query: Query) -> Iterator[LintResult]:\n self._fix_inconsistent_to,\n fixable,\n )\n- for child in query.children:\n- yield from self._visit_queries(child)\n+ children = list(query.children)\n+ # 'query.children' includes CTEs and \"main\" queries, but not queries in\n+ # the \"FROM\" list. We want to visit those as well.\n+ if select_info:\n+ for a in select_info.table_aliases:\n+ for q in SelectCrawler.get(query, a.from_expression_element):\n+ if not isinstance(q, Query):\n+ continue\n+ # Check for previously visited selectables to avoid possible\n+ # infinite recursion, e.g.:\n+ # WITH test1 AS (SELECT i + 1, j + 1 FROM test1)\n+ # SELECT * FROM test1;\n+ if any(s.selectable in visited for s in q.selectables):\n+ continue\n+ visited.update(s.selectable for s in q.selectables)\n+ children.append(q)\n+ for child in children:\n+ yield from self._visit_queries(child, visited)\n \n \n def _check_references(\ndiff --git a/src/sqlfluff/rules/L042.py b/src/sqlfluff/rules/L042.py\n--- a/src/sqlfluff/rules/L042.py\n+++ b/src/sqlfluff/rules/L042.py\n@@ -2,7 +2,7 @@\n import copy\n from functools import partial\n from typing import (\n- Generator,\n+ Iterator,\n List,\n NamedTuple,\n Optional,\n@@ -12,7 +12,9 @@\n TypeVar,\n cast,\n )\n+\n from sqlfluff.core.dialects.base import Dialect\n+from sqlfluff.core.dialects.common import AliasInfo\n from sqlfluff.core.parser.segments.base import BaseSegment\n from sqlfluff.core.parser.segments.raw import (\n CodeSegment,\n@@ -21,8 +23,15 @@\n SymbolSegment,\n WhitespaceSegment,\n )\n-from sqlfluff.core.rules import BaseRule, LintFix, LintResult, RuleContext\n+from sqlfluff.core.rules import (\n+ BaseRule,\n+ EvalResultType,\n+ LintFix,\n+ LintResult,\n+ RuleContext,\n+)\n from sqlfluff.utils.analysis.select import get_select_statement_info\n+from sqlfluff.utils.analysis.select_crawler import Query, Selectable, SelectCrawler\n from sqlfluff.core.rules.crawlers import SegmentSeekerCrawler\n from sqlfluff.core.rules.doc_decorators import (\n document_configuration,\n@@ -51,10 +60,11 @@\n \n \n class _NestedSubQuerySummary(NamedTuple):\n- parent_clause_type: str\n- parent_select_segments: Segments\n- clause_segments: Segments\n- subquery: BaseSegment\n+ query: Query\n+ selectable: Selectable\n+ table_alias: AliasInfo\n+ sc: SelectCrawler\n+ select_source_names: Set[str]\n \n \n @document_groups\n@@ -107,137 +117,164 @@ class Rule_L042(BaseRule):\n \"both\": [\"join_clause\", \"from_expression_element\"],\n }\n \n- def _eval(self, context: RuleContext) -> Optional[List[LintResult]]:\n+ def _eval(self, context: RuleContext) -> EvalResultType:\n \"\"\"Join/From clauses should not contain subqueries. Use CTEs instead.\"\"\"\n self.forbid_subquery_in: str\n- parent_types = self._config_mapping[self.forbid_subquery_in]\n- segment = FunctionalContext(context).segment\n- parent_stack = FunctionalContext(context).parent_stack\n+ functional_context = FunctionalContext(context)\n+ segment = functional_context.segment\n+ parent_stack = functional_context.parent_stack\n+ is_select = segment.all(is_type(*_SELECT_TYPES))\n is_select_child = parent_stack.any(is_type(*_SELECT_TYPES))\n- if is_select_child:\n+ if not is_select or is_select_child:\n # Nothing to do.\n return None\n \n- # Gather all possible offending Elements in one crawl\n- nested_subqueries: List[_NestedSubQuerySummary] = []\n- selects = segment.recursive_crawl(*_SELECT_TYPES, recurse_into=True)\n- for select in selects.iterate_segments():\n- for res in _find_nested_subqueries(select, context.dialect):\n- if res.parent_clause_type not in parent_types:\n- continue\n- nested_subqueries.append(res)\n+ crawler = SelectCrawler(context.segment, context.dialect)\n+ assert crawler.query_tree\n+\n+ # generate an instance which will track and shape our output CTE\n+ ctes = _CTEBuilder()\n+ # Init the output/final select &\n+ # populate existing CTEs\n+ for cte in crawler.query_tree.ctes.values():\n+ ctes.insert_cte(cte.cte_definition_segment) # type: ignore\n+\n+ is_with = segment.all(is_type(\"with_compound_statement\"))\n+ # TODO: consider if we can fix recursive CTEs\n+ is_recursive = is_with and len(segment.children(is_keyword(\"recursive\"))) > 0\n+ case_preference = _get_case_preference(segment)\n+ output_select = segment\n+ if is_with:\n+ output_select = segment.children(\n+ is_type(\n+ \"set_expression\",\n+ \"select_statement\",\n+ )\n+ )\n \n- if not nested_subqueries:\n- return None\n # If there are offending elements calculate fixes\n- return _calculate_fixes(\n+ clone_map = SegmentCloneMap(segment[0])\n+ result = self._lint_query(\n dialect=context.dialect,\n- root_select=segment,\n- nested_subqueries=nested_subqueries,\n- parent_stack=parent_stack,\n+ query=crawler.query_tree,\n+ ctes=ctes,\n+ case_preference=case_preference,\n+ clone_map=clone_map,\n )\n \n-\n-def _calculate_fixes(\n- dialect: Dialect,\n- root_select: Segments,\n- nested_subqueries: List[_NestedSubQuerySummary],\n- parent_stack: Segments,\n-) -> List[LintResult]:\n- \"\"\"Given the Root select and the offending subqueries calculate fixes.\"\"\"\n- is_with = root_select.all(is_type(\"with_compound_statement\"))\n- # TODO: consider if we can fix recursive CTEs\n- is_recursive = is_with and len(root_select.children(is_keyword(\"recursive\"))) > 0\n- case_preference = _get_case_preference(root_select)\n- # generate an instance which will track and shape our output CTE\n- ctes = _CTEBuilder()\n- # Init the output/final select &\n- # populate existing CTEs\n- for cte in root_select.children(is_type(\"common_table_expression\")):\n- assert isinstance(cte, CTEDefinitionSegment), \"TypeGuard\"\n- ctes.insert_cte(cte)\n-\n- output_select = root_select\n- if is_with:\n- output_select = root_select.children(\n- is_type(\n- \"set_expression\",\n- \"select_statement\",\n+ if result:\n+ lint_result, from_expression, alias_name, subquery_parent = result\n+ assert any(\n+ from_expression is seg for seg in subquery_parent.recursive_crawl_all()\n )\n- )\n+ this_seg_clone = clone_map[from_expression]\n+ new_table_ref = _create_table_ref(alias_name, context.dialect)\n+ this_seg_clone.segments = [new_table_ref]\n+ ctes.replace_with_clone(subquery_parent, clone_map)\n+\n+ # Issue 3617: In T-SQL (and possibly other dialects) the automated fix\n+ # leaves parentheses in a location that causes a syntax error. This is an\n+ # unusual corner case. For simplicity, we still generate the lint warning\n+ # but don't try to generate a fix. Someone could look at this later (a\n+ # correct fix would involve removing the parentheses.)\n+ bracketed_ctas = [seg.type for seg in parent_stack[-2:]] == [\n+ \"create_table_statement\",\n+ \"bracketed\",\n+ ]\n+ if bracketed_ctas or ctes.has_duplicate_aliases() or is_recursive:\n+ # If we have duplicate CTE names just don't fix anything\n+ # Return the lint warnings anyway\n+ return lint_result\n+\n+ # Compute fix.\n+ edit = [\n+ ctes.compose_select(\n+ clone_map[output_select[0]],\n+ case_preference=case_preference,\n+ ),\n+ ]\n+ lint_result.fixes = [\n+ LintFix.replace(\n+ segment[0],\n+ edit_segments=edit,\n+ )\n+ ]\n+ return lint_result\n+ return None\n \n- lint_results: List[LintResult] = []\n- clone_map = SegmentCloneMap(root_select[0])\n- is_new_name = False\n- new_table_ref = None\n- for parent_type, _, this_seg, subquery in nested_subqueries:\n- alias_name, is_new_name = ctes.create_cte_alias(\n- this_seg.children(is_type(\"alias_expression\"))\n- )\n- new_cte = _create_cte_seg(\n- alias_name=alias_name,\n- subquery=clone_map[subquery],\n- case_preference=case_preference,\n- dialect=dialect,\n- )\n- ctes.insert_cte(new_cte)\n- this_seg_clone = clone_map[this_seg[0]]\n- assert this_seg_clone.pos_marker, \"TypeGuard\"\n- new_table_ref = _create_table_ref(alias_name, dialect)\n- this_seg_clone.segments = (new_table_ref,)\n- anchor = subquery\n- # Grab the first keyword or symbol in the subquery to use as the\n- # anchor. This makes the lint warning less likely to be filtered out\n- # if a bit of the subquery happens to be templated.\n- for seg in subquery.recursive_crawl(\"keyword\", \"symbol\"):\n- anchor = seg\n- break\n- res = LintResult(\n- anchor=anchor,\n- description=f\"{parent_type} clauses should not contain \"\n- \"subqueries. Use CTEs instead\",\n- fixes=[],\n- )\n- lint_results.append(res)\n-\n- # Issue 3617: In T-SQL (and possibly other dialects) the automated fix\n- # leaves parentheses in a location that causes a syntax error. This is an\n- # unusual corner case. For simplicity, we still generate the lint warning\n- # but don't try to generate a fix. Someone could look at this later (a\n- # correct fix would involve removing the parentheses.)\n- bracketed_ctas = [seg.type for seg in parent_stack[-2:]] == [\n- \"create_table_statement\",\n- \"bracketed\",\n- ]\n- if bracketed_ctas or ctes.has_duplicate_aliases() or is_recursive:\n- # If we have duplicate CTE names just don't fix anything\n- # Return the lint warnings anyway\n- return lint_results\n-\n- # Add fixes to the last result only\n- edit = [\n- ctes.compose_select(\n- clone_map[output_select[0]],\n- case_preference=case_preference,\n- ),\n- ]\n- lint_results[-1].fixes = [\n- LintFix.replace(\n- root_select[0],\n- edit_segments=edit,\n- )\n- ]\n- if is_new_name:\n- assert lint_results[0].fixes[0].edit\n- assert new_table_ref\n- # If we're creating a new CTE name but the CTE name does not appear in\n- # the fix, discard the lint error. This prevents the rule from looping,\n- # i.e. making the same fix repeatedly.\n- if not any(\n- seg.uuid == new_table_ref.uuid for seg in edit[0].recursive_crawl_all()\n- ):\n- lint_results[-1].fixes = []\n- return lint_results\n+ def _nested_subqueries(\n+ self, query: Query, dialect: Dialect\n+ ) -> Iterator[_NestedSubQuerySummary]:\n+ parent_types = self._config_mapping[self.forbid_subquery_in]\n+ for q in [query] + list(query.ctes.values()):\n+ for selectable in q.selectables:\n+ if not selectable.select_info:\n+ continue # pragma: no cover\n+ select_source_names = set()\n+ for a in selectable.select_info.table_aliases:\n+ # For each table in FROM, return table name and any alias.\n+ if a.ref_str:\n+ select_source_names.add(a.ref_str)\n+ if a.object_reference:\n+ select_source_names.add(a.object_reference.raw)\n+ for table_alias in selectable.select_info.table_aliases:\n+ sc = SelectCrawler(table_alias.from_expression_element, dialect)\n+ if sc.query_tree:\n+ path_to = selectable.selectable.path_to(\n+ table_alias.from_expression_element\n+ )\n+ if not any(seg.is_type(*parent_types) for seg in path_to):\n+ continue\n+ if _is_correlated_subquery(\n+ Segments(sc.query_tree.selectables[0].selectable),\n+ select_source_names,\n+ dialect,\n+ ):\n+ continue\n+ yield _NestedSubQuerySummary(\n+ q, selectable, table_alias, sc, select_source_names\n+ )\n+\n+ def _lint_query(\n+ self,\n+ dialect: Dialect,\n+ query: Query,\n+ ctes: \"_CTEBuilder\",\n+ case_preference,\n+ clone_map,\n+ ) -> Optional[Tuple[LintResult, BaseSegment, str, BaseSegment]]:\n+ \"\"\"Given the root query, compute lint warnings.\"\"\"\n+ nsq: _NestedSubQuerySummary\n+ for nsq in self._nested_subqueries(query, dialect):\n+ alias_name, is_new_name = ctes.create_cte_alias(nsq.table_alias)\n+ anchor = nsq.table_alias.from_expression_element.segments[0]\n+ new_cte = _create_cte_seg(\n+ alias_name=alias_name,\n+ subquery=clone_map[anchor],\n+ case_preference=case_preference,\n+ dialect=dialect,\n+ )\n+ ctes.insert_cte(new_cte)\n+\n+ # Grab the first keyword or symbol in the subquery to\n+ # use as the anchor. This makes the lint warning less\n+ # likely to be filtered out if a bit of the subquery\n+ # happens to be templated.\n+ anchor = next(anchor.recursive_crawl(\"keyword\", \"symbol\"))\n+ res = LintResult(\n+ anchor=anchor,\n+ description=f\"{nsq.query.selectables[0].selectable.type} clauses \"\n+ \"should not contain subqueries. Use CTEs instead\",\n+ fixes=[],\n+ )\n+ if len(nsq.query.selectables) == 1:\n+ return (\n+ res,\n+ nsq.table_alias.from_expression_element,\n+ alias_name,\n+ nsq.query.selectables[0].selectable,\n+ )\n+ return None\n \n \n def _get_first_select_statement_descendant(\n@@ -252,27 +289,6 @@ def _get_first_select_statement_descendant(\n return None # pragma: no cover\n \n \n-def _get_sources_from_select(segment: BaseSegment, dialect: Dialect) -> Set[str]:\n- \"\"\"Given segment, return set of table or alias names it queries from.\"\"\"\n- result = set()\n- select = None\n- if segment.is_type(\"select_statement\"):\n- select = segment\n- elif segment.is_type(\"with_compound_statement\"):\n- # For WITH statement, process the main query underneath.\n- select = _get_first_select_statement_descendant(segment)\n- if select and select.is_type(\"select_statement\"):\n- select_info = get_select_statement_info(select, dialect)\n- if select_info:\n- for a in select_info.table_aliases:\n- # For each table in FROM, return table name and any alias.\n- if a.ref_str:\n- result.add(a.ref_str)\n- if a.object_reference:\n- result.add(a.object_reference.raw)\n- return result\n-\n-\n def _is_correlated_subquery(\n nested_select: Segments, select_source_names: Set[str], dialect: Dialect\n ):\n@@ -280,8 +296,6 @@ def _is_correlated_subquery(\n \n https://en.wikipedia.org/wiki/Correlated_subquery\n \"\"\"\n- if not nested_select:\n- return False # pragma: no cover\n select_statement = _get_first_select_statement_descendant(nested_select[0])\n if not select_statement:\n return False # pragma: no cover\n@@ -298,51 +312,6 @@ def _is_correlated_subquery(\n return False\n \n \n-def _find_nested_subqueries(\n- select: Segments,\n- dialect: Dialect,\n-) -> Generator[_NestedSubQuerySummary, None, None]:\n- \"\"\"Find possible offending elements and return enough to fix them.\"\"\"\n- select_types = [\n- \"with_compound_statement\",\n- \"set_expression\",\n- \"select_statement\",\n- ]\n- from_clause = select.children().first(is_type(\"from_clause\")).children()\n- offending_types = [\"join_clause\", \"from_expression_element\"]\n- select_source_names = _get_sources_from_select(select[0], dialect)\n-\n- # Match any of the types we care about\n- for this_seg in from_clause.children(is_type(*offending_types)).iterate_segments():\n- parent_type = this_seg[0].get_type()\n- # Ensure we are at the right depth (from_expression_element)\n- if not this_seg.all(is_type(\"from_expression_element\")):\n- this_seg = this_seg.children(\n- is_type(\"from_expression_element\"),\n- )\n-\n- table_expression_el = this_seg.children(\n- is_type(\"table_expression\"),\n- )\n-\n- # Is it bracketed? If so, lint that instead.\n- bracketed_expression = table_expression_el.children(\n- is_type(\"bracketed\"),\n- )\n- nested_select = bracketed_expression or table_expression_el\n- # If we find a child with a \"problem\" type, raise an issue.\n- # If not, we're fine.\n- seg = nested_select.children(is_type(*select_types))\n- if not seg:\n- # If there is no match there is no error\n- continue\n- # Type, parent_select, parent_sequence\n- if not _is_correlated_subquery(nested_select, select_source_names, dialect):\n- yield _NestedSubQuerySummary(\n- parent_type, select, this_seg, table_expression_el[0]\n- )\n-\n-\n class _CTEBuilder:\n \"\"\"Gather CTE parts, maintain order and track naming/aliasing.\"\"\"\n \n@@ -369,7 +338,9 @@ def has_duplicate_aliases(self) -> bool:\n def insert_cte(self, cte: CTEDefinitionSegment):\n \"\"\"Add a new CTE to the list as late as possible but before all its parents.\"\"\"\n # This should still have the position markers of its true position\n- inbound_subquery = Segments(cte).children().last()\n+ inbound_subquery = (\n+ Segments(cte).children().last(lambda seg: bool(seg.pos_marker))\n+ )\n insert_position = next(\n (\n i\n@@ -381,14 +352,11 @@ def insert_cte(self, cte: CTEDefinitionSegment):\n \n self.ctes.insert(insert_position, cte)\n \n- def create_cte_alias(\n- self, alias_segment: Optional[Segments] = None\n- ) -> Tuple[str, bool]:\n+ def create_cte_alias(self, alias: Optional[AliasInfo]) -> Tuple[str, bool]:\n \"\"\"Find or create the name for the next CTE.\"\"\"\n- if alias_segment:\n+ if alias and alias.aliased and alias.ref_str:\n # If we know the name use it\n- name = alias_segment.children().last()[0].raw\n- return name, False\n+ return alias.ref_str, False\n \n self.name_idx = self.name_idx + 1\n name = f\"prep_{self.name_idx}\"\n@@ -398,7 +366,7 @@ def create_cte_alias(\n return name, True\n \n def get_cte_segments(self) -> List[BaseSegment]:\n- \"\"\"Return a valid list of CTES with required padding Segements.\"\"\"\n+ \"\"\"Return a valid list of CTES with required padding segments.\"\"\"\n cte_segments: List[BaseSegment] = []\n for cte in self.ctes:\n cte_segments = cte_segments + [\n@@ -439,16 +407,24 @@ def compose_select(self, output_select: BaseSegment, case_preference: str):\n )\n return new_select\n \n+ def replace_with_clone(self, segment, clone_map):\n+ for idx, cte in enumerate(self.ctes):\n+ if any(segment is seg for seg in cte.recursive_crawl_all()):\n+ self.ctes[idx] = clone_map[self.ctes[idx]]\n+ return\n+\n \n def _is_child(maybe_parent: Segments, maybe_child: Segments) -> bool:\n \"\"\"Is the child actually between the start and end markers of the parent.\"\"\"\n- assert len(maybe_child) == 1, \"Cannot assess Childness of multiple Segments\"\n- assert len(maybe_parent) == 1, \"Cannot assess Childness of multiple Parents\"\n+ assert (\n+ len(maybe_child) == 1\n+ ), \"Cannot assess child relationship of multiple segments\"\n+ assert (\n+ len(maybe_parent) == 1\n+ ), \"Cannot assess child relationship of multiple parents\"\n child_markers = maybe_child[0].pos_marker\n parent_pos = maybe_parent[0].pos_marker\n- if not parent_pos or not child_markers:\n- return False # pragma: no cover\n-\n+ assert parent_pos and child_markers\n if child_markers < parent_pos.start_point_marker():\n return False # pragma: no cover\n \ndiff --git a/src/sqlfluff/utils/analysis/select_crawler.py b/src/sqlfluff/utils/analysis/select_crawler.py\n--- a/src/sqlfluff/utils/analysis/select_crawler.py\n+++ b/src/sqlfluff/utils/analysis/select_crawler.py\n@@ -33,8 +33,13 @@ class Selectable:\n \"\"\"A \"SELECT\" query segment.\"\"\"\n \n selectable: BaseSegment\n+ parent: Optional[BaseSegment]\n dialect: Dialect\n \n+ def as_str(self) -> str:\n+ \"\"\"String representation for logging/testing.\"\"\"\n+ return self.selectable.raw\n+\n @cached_property\n def select_info(self):\n \"\"\"Returns SelectStatementColumnsAndTables on the SELECT.\"\"\"\n@@ -112,7 +117,7 @@ def find_alias(self, table: str) -> Optional[AliasInfo]:\n \"\"\"Find corresponding table_aliases entry (if any) matching \"table\".\"\"\"\n alias_info = [\n t\n- for t in self.select_info.table_aliases\n+ for t in (self.select_info.table_aliases if self.select_info else [])\n if t.aliased and t.ref_str == table\n ]\n assert len(alias_info) <= 1\n@@ -131,8 +136,24 @@ class Query:\n parent: Optional[\"Query\"] = field(default=None)\n # Children (could be CTE, subselect, or other).\n children: List[\"Query\"] = field(default_factory=list)\n+ cte_definition_segment: Optional[BaseSegment] = field(default=None)\n cte_name_segment: Optional[BaseSegment] = field(default=None)\n \n+ def as_json(self) -> Dict:\n+ \"\"\"JSON representation for logging/testing.\"\"\"\n+ result = {}\n+ if self.query_type != QueryType.Simple:\n+ result[\"query_type\"] = self.query_type.name\n+ if self.selectables:\n+ result[\"selectables\"] = [\n+ s.as_str() for s in self.selectables\n+ ] # type: ignore\n+ if self.ctes:\n+ result[\"ctes\"] = {\n+ k: v.as_json() for k, v in self.ctes.items()\n+ } # type: ignore\n+ return result\n+\n def lookup_cte(self, name: str, pop: bool = True) -> Optional[\"Query\"]:\n \"\"\"Look up a CTE by name, in the current or any parent scope.\"\"\"\n cte = self.ctes.get(name.upper())\n@@ -146,7 +167,7 @@ def lookup_cte(self, name: str, pop: bool = True) -> Optional[\"Query\"]:\n return None\n \n def crawl_sources(\n- self, segment: BaseSegment, recurse_into=True, pop=False\n+ self, segment: BaseSegment, recurse_into=True, pop=False, lookup_cte=True\n ) -> Generator[Union[str, \"Query\"], None, None]:\n \"\"\"Find SELECTs, table refs, or value table function calls in segment.\n \n@@ -154,20 +175,26 @@ def crawl_sources(\n references or function call strings, yield those.\n \"\"\"\n found_nested_select = False\n- for seg in segment.recursive_crawl(\n+ types = [\n \"table_reference\",\n \"set_expression\",\n \"select_statement\",\n \"values_clause\",\n- recurse_into=recurse_into,\n+ ]\n+ for event, path in SelectCrawler.visit_segments(\n+ segment, recurse_into=recurse_into\n ):\n+ seg = path[-1]\n+ if event == \"end\" or not seg.is_type(*types):\n+ continue\n+\n if seg is segment:\n # If the starting segment itself matches the list of types we're\n # searching for, recursive_crawl() will return it. Skip that.\n continue\n \n if seg.is_type(\"table_reference\"):\n- if not seg.is_qualified():\n+ if not seg.is_qualified() and lookup_cte:\n cte = self.lookup_cte(seg.raw, pop=pop)\n if cte:\n # It's a CTE.\n@@ -179,7 +206,15 @@ def crawl_sources(\n \"set_expression\", \"select_statement\", \"values_clause\"\n )\n found_nested_select = True\n- crawler = SelectCrawler(seg, self.dialect, parent=self)\n+ seg_ = Segments(*path[1:]).first(\n+ sp.is_type(\n+ \"from_expression_element\",\n+ \"set_expression\",\n+ \"select_statement\",\n+ \"values_clause\",\n+ )\n+ )[0]\n+ crawler = SelectCrawler(seg_, self.dialect, parent=self)\n # We know this will pass because we specified parent=self above.\n assert crawler.query_tree\n yield crawler.query_tree\n@@ -234,9 +269,10 @@ def finish_segment():\n except ValueError:\n pass\n \n- # Stores the last CTE name we saw, so we can associate it with the\n- # corresponding Query.\n- cte_name_segment: Optional[BaseSegment] = None\n+ # Stacks for CTE definition & names we've seen but haven't consumed yet,\n+ # so we can associate with the corresponding Query.\n+ cte_definition_segment_stack: List[BaseSegment] = []\n+ cte_name_segment_stack: List[BaseSegment] = []\n \n # Visit segment and all its children\n for event, path in SelectCrawler.visit_segments(segment):\n@@ -263,9 +299,17 @@ def finish_segment():\n # added to this Query later.\n query = self.query_class(QueryType.Simple, dialect)\n append_query(query)\n- else:\n+ # Ignore segments under a from_expression_element.\n+ # Those will be nested queries, and we're only\n+ # interested in CTEs and \"main\" queries, i.e.\n+ # standalones or those following a block of CTEs.\n+ elif not any(\n+ seg.is_type(\"from_expression_element\") for seg in path[1:]\n+ ):\n # It's a select_statement or values_clause.\n- selectable = Selectable(path[-1], dialect)\n+ selectable = Selectable(\n+ path[-1], path[-2] if len(path) >= 2 else None, dialect\n+ )\n # Determine if this is part of a set_expression.\n if len(path) >= 2 and path[-2].is_type(\"set_expression\"):\n # It's part of a set_expression. Append to the\n@@ -280,27 +324,37 @@ def finish_segment():\n append_query(query)\n else:\n # We're processing a \"with\" statement.\n- if cte_name_segment:\n+ if cte_name_segment_stack:\n # If we have a CTE name, this is the Query for that\n # name.\n query = self.query_class(\n QueryType.Simple,\n dialect,\n- cte_name_segment=cte_name_segment,\n+ cte_definition_segment=cte_definition_segment_stack[-1],\n+ cte_name_segment=cte_name_segment_stack[-1],\n )\n if path[-1].is_type(\n \"select_statement\", \"values_clause\", \"update_statement\"\n ):\n # Add to the Query object we just created.\n- query.selectables.append(Selectable(path[-1], dialect))\n+ query.selectables.append(\n+ Selectable(\n+ path[-1],\n+ path[-2] if len(path) >= 2 else None,\n+ dialect,\n+ )\n+ )\n else:\n # Processing a set_expression. Nothing\n # additional to do here; we'll add selectables\n # to the Query later when we encounter those\n # child segments.\n pass\n- query_stack[-1].ctes[cte_name_segment.raw_upper] = query\n- cte_name_segment = None\n+ query_stack[-1].ctes[\n+ cte_name_segment_stack[-1].raw_upper\n+ ] = query\n+ cte_definition_segment_stack.pop()\n+ cte_name_segment_stack.pop()\n append_query(query)\n else:\n # There's no CTE name, so we're probably processing\n@@ -311,7 +365,8 @@ def finish_segment():\n # interested in CTEs and \"main\" queries, i.e.\n # standalones or those following a block of CTEs.\n if not any(\n- seg.is_type(\"from_expression_element\") for seg in path\n+ seg.is_type(\"from_expression_element\")\n+ for seg in path[1:]\n ):\n if path[-1].is_type(\n \"select_statement\", \"update_statement\"\n@@ -319,7 +374,11 @@ def finish_segment():\n # Processing a select_statement. Add it to the\n # Query object on top of the stack.\n query_stack[-1].selectables.append(\n- Selectable(path[-1], dialect)\n+ Selectable(\n+ path[-1],\n+ path[-2] if len(path) >= 2 else None,\n+ dialect,\n+ )\n )\n else:\n # Processing a set_expression. Nothing\n@@ -328,13 +387,19 @@ def finish_segment():\n elif path[-1].is_type(\"with_compound_statement\"):\n # Beginning a \"with\" statement, i.e. a block of CTEs.\n query = self.query_class(QueryType.WithCompound, dialect)\n- if cte_name_segment:\n- query_stack[-1].ctes[cte_name_segment.raw_upper] = query\n- cte_name_segment = None\n+ if cte_name_segment_stack:\n+ query_stack[-1].ctes[\n+ cte_name_segment_stack[-1].raw_upper\n+ ] = query\n+ query.cte_definition_segment = cte_definition_segment_stack[-1]\n+ cte_definition_segment_stack.pop()\n+ cte_name_segment_stack.pop()\n append_query(query)\n elif path[-1].is_type(\"common_table_expression\"):\n- # This is a \"<<cte name>> AS\". Grab the name for later.\n- cte_name_segment = path[-1].segments[0]\n+ # This is a \"<<cte name>> AS\". Save definition segment and\n+ # name for later.\n+ cte_definition_segment_stack.append(path[-1])\n+ cte_name_segment_stack.append(path[-1].segments[0])\n elif event == \"end\":\n finish_segment()\n \n@@ -355,13 +420,14 @@ def get(cls, query: Query, segment: BaseSegment) -> List[Union[str, \"Query\"]]:\n return list(query.crawl_sources(segment, True))\n \n @classmethod\n- def visit_segments(cls, seg, path=None):\n+ def visit_segments(cls, seg, path=None, recurse_into=True):\n \"\"\"Recursively visit all segments.\"\"\"\n if path is None:\n path = []\n path.append(seg)\n yield \"start\", path\n- for seg in seg.segments:\n- yield from cls.visit_segments(seg, path)\n+ if recurse_into:\n+ for seg in seg.segments:\n+ yield from cls.visit_segments(seg, path, recurse_into)\n yield \"end\", path\n path.pop()\n", "test_patch": "diff --git a/test/fixtures/rules/std_rule_cases/L042.yml b/test/fixtures/rules/std_rule_cases/L042.yml\n--- a/test/fixtures/rules/std_rule_cases/L042.yml\n+++ b/test/fixtures/rules/std_rule_cases/L042.yml\n@@ -99,7 +99,7 @@ double_nested_fail:\n L042:\n forbid_subquery_in: both\n \n-double_nested_unfixable_cte_clash:\n+double_nested_fail_2:\n fail_str: |\n select\n a.x, a.y, b.z\n@@ -109,6 +109,20 @@ double_nested_unfixable_cte_clash:\n select x, z from p_cte\n ) as b\n ) as b on (a.x = b.x)\n+ fix_str: |\n+ with b as (\n+ select x, z from (\n+ select x, z from p_cte\n+ ) as b\n+ )\n+ select\n+ a.x, a.y, b.z\n+ from a\n+ join b on (a.x = b.x)\n+ violations_after_fix:\n+ - description: select_statement clauses should not contain subqueries. Use CTEs instead\n+ line_no: 2\n+ line_pos: 20\n configs:\n rules:\n L042:\n@@ -127,6 +141,23 @@ unfixable_cte_clash:\n select 1\n ) as b\n ) as c on (a.x = b.x)\n+ fix_str: |\n+ with \"b\" as (\n+ select x, z from p_cte\n+ ),\n+ c as (\n+ select x, z from (\n+ select 1\n+ ) as b\n+ )\n+ select\n+ a.x, a.y, b.z\n+ from a\n+ join c on (a.x = b.x)\n+ violations_after_fix:\n+ - description: select_statement clauses should not contain subqueries. Use CTEs instead\n+ line_no: 5\n+ line_pos: 20\n configs:\n rules:\n L042:\n@@ -458,10 +489,16 @@ issue_3572_correlated_subquery_3:\n issue_3598_avoid_looping_1:\n fail_str: |\n WITH cte1 AS (\n- \tSELECT a\n- \tFROM (SELECT a)\n+ SELECT a\n+ FROM (SELECT a)\n+ )\n+ SELECT a FROM cte1\n+ fix_str: |\n+ WITH prep_1 AS (SELECT a),\n+ cte1 AS (\n+ SELECT a\n+ FROM prep_1\n )\n-\n SELECT a FROM cte1\n configs:\n rules:\n@@ -474,8 +511,37 @@ issue_3598_avoid_looping_2:\n SELECT *\n FROM (SELECT * FROM mongo.temp)\n )\n-\n SELECT * FROM cte1\n+ fix_str: |\n+ WITH prep_1 AS (SELECT * FROM mongo.temp),\n+ cte1 AS (\n+ SELECT *\n+ FROM prep_1\n+ )\n+ SELECT * FROM cte1\n+ configs:\n+ rules:\n+ L042:\n+ forbid_subquery_in: both\n+\n+test_fail_subquery_in_cte:\n+ fail_str: |\n+ with b as (\n+ select x, z from (\n+ select x, z from p_cte\n+ )\n+ )\n+ select b.z\n+ from b\n+ fix_str: |\n+ with prep_1 as (\n+ select x, z from p_cte\n+ ),\n+ b as (\n+ select x, z from prep_1\n+ )\n+ select b.z\n+ from b\n configs:\n rules:\n L042:\ndiff --git a/test/utils/analysis/test_select_crawler.py b/test/utils/analysis/test_select_crawler.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/utils/analysis/test_select_crawler.py\n@@ -0,0 +1,197 @@\n+\"\"\"Test the select_crawler module.\"\"\"\n+import pytest\n+\n+from sqlfluff.core.linter.linter import Linter\n+from sqlfluff.utils.analysis import select_crawler\n+\n+\[email protected](\n+ \"sql, expected_json\",\n+ [\n+ (\n+ # Test trivial query.\n+ \"select 1\",\n+ {\"selectables\": [\"select 1\"]},\n+ ),\n+ (\n+ # Test set expression.\n+ \"select 1 union select 2\",\n+ {\"selectables\": [\"select 1\", \"select 2\"]},\n+ ),\n+ (\n+ # Test multiple CTEs.\n+ \"with cte1 as (select 1 as x), cte2 as (select 2 as y) \"\n+ \"select * from cte1 join cte2 using (x)\",\n+ {\n+ \"ctes\": {\n+ \"CTE1\": {\"selectables\": [\"select 1 as x\"]},\n+ \"CTE2\": {\"selectables\": [\"select 2 as y\"]},\n+ },\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\"select * from cte1 join cte2 using (x)\"],\n+ },\n+ ),\n+ (\n+ # Nested CTEs (from L044 test suite)\n+ \"\"\"\n+ with a as (\n+ with b as (select 1 from c)\n+ select * from b\n+ )\n+ select * from a\n+ \"\"\",\n+ {\n+ \"ctes\": {\n+ \"A\": {\n+ \"ctes\": {\"B\": {\"selectables\": [\"select 1 from c\"]}},\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\"select * from b\"],\n+ }\n+ },\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\"select * from a\"],\n+ },\n+ ),\n+ (\n+ # Nested CTEs (from L044 test suite)\n+ \"\"\"\n+ with b as (select 1 from c)\n+ select * from (\n+ with a as (select * from b)\n+ select * from a\n+ )\n+ \"\"\",\n+ {\n+ \"ctes\": {\"B\": {\"selectables\": [\"select 1 from c\"]}},\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\n+ \"select * from (\\n\"\n+ \" with a as (select * from b)\\n\"\n+ \" select * from a\\n\"\n+ \" )\"\n+ ],\n+ },\n+ ),\n+ (\n+ # Test that subquery in \"from\" not included.\n+ \"select a.x from (select z from b)\",\n+ {\"selectables\": [\"select a.x from (select z from b)\"]},\n+ ),\n+ (\n+ # Test that subquery in \"from\" / \"join\" not included.\n+ \"select a.x from a join (select z from b) as b on (a.x = b.x)\",\n+ {\n+ \"selectables\": [\n+ \"select a.x from a join (select z from b) as b on (a.x = b.x)\"\n+ ]\n+ },\n+ ),\n+ (\n+ # In CTE main query, test that subquery in \"from\" not included.\n+ \"with prep as (select 1) select a.x from (select z from b)\",\n+ {\n+ \"ctes\": {\"PREP\": {\"selectables\": [\"select 1\"]}},\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\"select a.x from (select z from b)\"],\n+ },\n+ ),\n+ (\n+ # In CTE main query, test that subquery in \"from\" / \"join\" not included.\n+ \"with prep as (select 1) \"\n+ \"select a.x from a join (select z from b) as b on (a.x = b.x)\",\n+ {\n+ \"ctes\": {\"PREP\": {\"selectables\": [\"select 1\"]}},\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\n+ \"select a.x from a join (select z from b) as b on (a.x = \" \"b.x)\"\n+ ],\n+ },\n+ ),\n+ (\n+ \"\"\"with prep_1 as (\n+ with d as (\n+ select x, z from b\n+ )\n+ select * from d\n+)\n+select\n+ a.x, a.y, b.z\n+from a\n+join prep_1 using (x)\n+\"\"\",\n+ {\n+ \"ctes\": {\n+ \"PREP_1\": {\n+ \"ctes\": {\n+ \"D\": {\"selectables\": [\"select x, z from b\"]},\n+ },\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\"select * from d\"],\n+ }\n+ },\n+ \"query_type\": \"WithCompound\",\n+ \"selectables\": [\n+ \"select\\n a.x, a.y, b.z\\nfrom a\\njoin prep_1 using (x)\"\n+ ],\n+ },\n+ ),\n+ ],\n+)\n+def test_select_crawler_constructor(sql, expected_json):\n+ \"\"\"Test SelectCrawler when created using constructor.\"\"\"\n+ linter = Linter(dialect=\"ansi\")\n+ parsed = linter.parse_string(sql)\n+ segments = list(\n+ parsed.tree.recursive_crawl(\n+ \"with_compound_statement\",\n+ \"set_expression\",\n+ \"select_statement\",\n+ )\n+ )\n+ segment = segments[0]\n+ crawler = select_crawler.SelectCrawler(segment, linter.dialect)\n+ assert all(\n+ cte.cte_definition_segment is not None\n+ for cte in crawler.query_tree.ctes.values()\n+ )\n+ json_query_tree = crawler.query_tree.as_json()\n+ assert expected_json == json_query_tree\n+\n+\n+def test_select_crawler_nested():\n+ \"\"\"Test invoking with an outer from_expression_segment.\"\"\"\n+ sql = \"\"\"\n+select\n+ a.x, a.y, b.z\n+from a\n+join (\n+ with d as (\n+ select x, z from b\n+ )\n+ select * from d\n+) using (x)\n+ \"\"\"\n+ linter = Linter(dialect=\"ansi\")\n+ parsed = linter.parse_string(sql)\n+ segments = list(\n+ parsed.tree.recursive_crawl(\n+ \"with_compound_statement\",\n+ \"set_expression\",\n+ \"select_statement\",\n+ )\n+ )\n+ segment = segments[0]\n+ crawler = select_crawler.SelectCrawler(segment, linter.dialect)\n+ sc = select_crawler.SelectCrawler(\n+ crawler.query_tree.selectables[0]\n+ .select_info.table_aliases[1]\n+ .from_expression_element,\n+ linter.dialect,\n+ )\n+ assert sc.query_tree.as_json() == {\n+ \"selectables\": [\n+ \"select * from d\",\n+ ],\n+ \"ctes\": {\"D\": {\"selectables\": [\"select x, z from b\"]}},\n+ \"query_type\": \"WithCompound\",\n+ }\n", "problem_statement": "L042 loop limit on fixes reached when CTE itself contains a subquery\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nWhile running `sqlfluff fix --dialect snowflake` on a sql file, I get \r\n```\r\n==== finding fixable violations ====\r\nWARNING Loop limit on fixes reached [10]. \r\n==== no fixable linting violations found ==== \r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n [22 unfixable linting violations found]\r\n```\r\n\r\n```\r\nINSERT OVERWRITE INTO dwh.test_table\r\n\r\nWITH cte1 AS (\r\n\tSELECT *\r\n\tFROM (SELECT\r\n\t\t*,\r\n\t\tROW_NUMBER() OVER (PARTITION BY r ORDER BY updated_at DESC) AS latest\r\n\t\tFROM mongo.temp\r\n\tWHERE latest = 1\r\n))\r\n\r\nSELECT * FROM cte1 WHERE 1=1;\r\n```\r\n\r\nAll of the 22 violations are a mix of L002, L003 and L004.\r\n\r\n### Expected Behaviour\r\n\r\n`sqlfluff` should be able to fix the violations\r\n\r\n### Observed Behaviour\r\n\r\nEven if I try to fix the violations manually, it still shows the same error.\r\n\r\n### How to reproduce\r\n\r\nI will try to generate a sql file that will be able to reproduce the issue\r\n\r\n### Dialect\r\n\r\nSnowflake\r\n\r\n### Version\r\n\r\n1.1.0\r\n\r\n### Configuration\r\n\r\n```\r\n# https://docs.sqlfluff.com/en/stable/rules.html\r\n\r\n[sqlfluff]\r\nexclude_rules = L029, L031, L034\r\n\r\n[sqlfluff:indentation]\r\nindented_joins = true\r\nindented_using_on = true\r\n\r\n[sqlfluff:rules:L002]\r\ntab_space_size = 4\r\n\r\n[sqlfluff:rules:L003]\r\nhanging_indents = true\r\nindent_unit = tab\r\ntab_space_size = 4\r\n\r\n[sqlfluff:rules:L004]\r\nindent_unit = tab\r\ntab_space_size = 4\r\n\r\n[sqlfluff:rules:L010]\r\ncapitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L011]\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:L012]\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:L014]\r\nextended_capitalisation_policy = lower\r\n\r\n[sqlfluff:rules:L016]\r\nignore_comment_clauses = true\r\nignore_comment_lines = true\r\nindent_unit = tab\r\ntab_space_size = 4\r\n\r\n[sqlfluff:rules:L019]\r\ncomma_style = trailing\r\n\r\n[sqlfluff:rules:L022]\r\ncomma_style = trailing\r\n\r\n[sqlfluff:rules:L028]\r\nsingle_table_references = unqualified\r\n\r\n[sqlfluff:rules:L030]\r\nextended_capitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L040]\r\ncapitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L042]\r\nforbid_subquery_in = both\r\n\r\n[sqlfluff:rules:L054]\r\ngroup_by_and_order_by_style = explicit\r\n\r\n[sqlfluff:rules:L063]\r\nextended_capitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L066]\r\nmin_alias_length = 3\r\nmax_alias_length = 15\r\n\r\n[sqlfluff:templater:jinja:context]\r\nparams = {\"DB\": \"DEMO\"}\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "Unfortunately there is not much we can do without the SQL that produces this error (ideally a minimal reproducible example SQL) so will need to close this issue if we don\u2019t get that.\nI have updated the issue with a sample query. The query is very vague but it reproduces the error. Let me know if it helps.\nLooks like this simpler example also produces it:\r\n\r\n```sql\r\nWITH cte1 AS (\r\n\tSELECT a\r\n\tFROM (SELECT a)\r\n)\r\n\r\nSELECT a FROM cte1\r\n```\r\n\r\nThis only has one linting failure:\r\n\r\n```\r\n$ sqlfluff lint test.sql --dialect snowflake \r\n== [test.sql] FAIL \r\nL: 3 | P: 7 | L042 | from_expression_element clauses should not contain\r\n | subqueries. Use CTEs instead\r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n```\r\n\r\nSo basically L042 gets in a recursive loop when trying to fix CTEs that also break L042.\r\n\r\nFor now you can manually fix that (or exclude L042 for this query) to prevent the error.\nAnother good test query:\r\n```\r\nWITH cte1 AS (\r\n SELECT *\r\n FROM (SELECT * FROM mongo.temp)\r\n)\r\n\r\nSELECT * FROM cte1\r\n```\nPR #3697 avoids the looping behavior. Lint issues are still flagged, but the rule does not attempt to fix it _if_ it would cause a loop. We should still try and figure out why this is happening, so the rule can actually autofix the code, but that's lower priority (and probably a separate PR).", "created_at": "2022-07-31T18:22:12Z", "version": "1.2", "FAIL_TO_PASS": ["test/utils/analysis/test_select_crawler.py::test_select_crawler_constructor[select", "test/utils/analysis/test_select_crawler.py::test_select_crawler_constructor[with", "test/utils/analysis/test_select_crawler.py::test_select_crawler_constructor[\\n", "test/utils/analysis/test_select_crawler.py::test_select_crawler_nested"], "PASS_TO_PASS": [], "environment_setup_commit": "388dd01e05c7dcb880165c7241ed4027d9d0171e"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3608", "base_commit": "d783e421b714ed989d9e641977ea9b3b6ffaf807", "patch": "diff --git a/src/sqlfluff/cli/__init__.py b/src/sqlfluff/cli/__init__.py\n--- a/src/sqlfluff/cli/__init__.py\n+++ b/src/sqlfluff/cli/__init__.py\n@@ -1 +1,6 @@\n \"\"\"init py for cli.\"\"\"\n+\n+\n+EXIT_SUCCESS = 0\n+EXIT_FAIL = 1\n+EXIT_ERROR = 2\ndiff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -22,6 +22,7 @@\n from tqdm import tqdm\n from sqlfluff.cli.autocomplete import shell_completion_enabled, dialect_shell_complete\n \n+from sqlfluff.cli import EXIT_SUCCESS, EXIT_ERROR, EXIT_FAIL\n from sqlfluff.cli.formatters import (\n format_linting_result_header,\n OutputStreamFormatter,\n@@ -154,7 +155,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):\n Color.red,\n )\n )\n- sys.exit(1)\n+ sys.exit(EXIT_ERROR)\n elif exc_type is SQLFluffUserError:\n click.echo(\n \"\\nUser Error: \"\n@@ -163,7 +164,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):\n Color.red,\n )\n )\n- sys.exit(1)\n+ sys.exit(EXIT_ERROR)\n \n \n def common_options(f: Callable) -> Callable:\n@@ -335,7 +336,7 @@ def get_config(\n color=Color.red,\n )\n )\n- sys.exit(66)\n+ sys.exit(EXIT_ERROR)\n except KeyError:\n click.echo(\n OutputStreamFormatter.colorize_helper(\n@@ -344,7 +345,7 @@ def get_config(\n color=Color.red,\n )\n )\n- sys.exit(66)\n+ sys.exit(EXIT_ERROR)\n from_root_kwargs = {}\n if \"require_dialect\" in kwargs:\n from_root_kwargs[\"require_dialect\"] = kwargs.pop(\"require_dialect\")\n@@ -365,7 +366,7 @@ def get_config(\n color=Color.red,\n )\n )\n- sys.exit(66)\n+ sys.exit(EXIT_ERROR)\n \n \n def get_linter_and_formatter(\n@@ -380,7 +381,7 @@ def get_linter_and_formatter(\n dialect_selector(dialect)\n except KeyError: # pragma: no cover\n click.echo(f\"Error: Unknown dialect '{cfg.get('dialect')}'\")\n- sys.exit(66)\n+ sys.exit(EXIT_ERROR)\n formatter = OutputStreamFormatter(\n output_stream=output_stream or make_output_stream(cfg),\n nocolor=cfg.get(\"nocolor\"),\n@@ -635,7 +636,7 @@ def lint(\n formatter.completion_message()\n sys.exit(result.stats()[\"exit code\"])\n else:\n- sys.exit(0)\n+ sys.exit(EXIT_SUCCESS)\n \n \n def do_fixes(lnt, result, formatter=None, **kwargs):\n@@ -730,7 +731,7 @@ def fix(\n verbose = config.get(\"verbose\")\n progress_bar_configuration.disable_progress_bar = disable_progress_bar\n \n- exit_code = 0\n+ exit_code = EXIT_SUCCESS\n \n formatter.dispatch_config(lnt)\n \n@@ -780,7 +781,7 @@ def fix(\n )\n \n click.echo(stdout, nl=False)\n- sys.exit(1 if templater_error or unfixable_error else exit_code)\n+ sys.exit(EXIT_FAIL if templater_error or unfixable_error else exit_code)\n \n # Lint the paths (not with the fix argument at this stage), outputting as we go.\n click.echo(\"==== finding fixable violations ====\")\n@@ -816,7 +817,7 @@ def fix(\n fixed_file_suffix=fixed_suffix,\n )\n if not success:\n- sys.exit(1) # pragma: no cover\n+ sys.exit(EXIT_FAIL) # pragma: no cover\n else:\n click.echo(\n \"Are you sure you wish to attempt to fix these? [Y/n] \", nl=False\n@@ -833,16 +834,16 @@ def fix(\n fixed_file_suffix=fixed_suffix,\n )\n if not success:\n- sys.exit(1) # pragma: no cover\n+ sys.exit(EXIT_FAIL) # pragma: no cover\n else:\n formatter.completion_message()\n elif c == \"n\":\n click.echo(\"Aborting...\")\n- exit_code = 1\n+ exit_code = EXIT_FAIL\n else: # pragma: no cover\n click.echo(\"Invalid input, please enter 'Y' or 'N'\")\n click.echo(\"Aborting...\")\n- exit_code = 1\n+ exit_code = EXIT_FAIL\n else:\n click.echo(\"==== no fixable linting violations found ====\")\n formatter.completion_message()\n@@ -851,7 +852,7 @@ def fix(\n (\n dict(types=SQLLintError, fixable=False),\n \" [{} unfixable linting violations found]\",\n- 1,\n+ EXIT_FAIL,\n ),\n ]\n for num_violations_kwargs, message_format, error_level in error_types:\n@@ -986,7 +987,7 @@ def parse(\n import cProfile\n except ImportError: # pragma: no cover\n click.echo(\"The cProfiler is not available on your platform.\")\n- sys.exit(1)\n+ sys.exit(EXIT_ERROR)\n pr = cProfile.Profile()\n pr.enable()\n \n@@ -1053,9 +1054,9 @@ def parse(\n click.echo(\"\\n\".join(profiler_buffer.getvalue().split(\"\\n\")[:50]))\n \n if violations_count > 0 and not nofail:\n- sys.exit(66) # pragma: no cover\n+ sys.exit(EXIT_FAIL) # pragma: no cover\n else:\n- sys.exit(0)\n+ sys.exit(EXIT_SUCCESS)\n \n \n # This \"__main__\" handler allows invoking SQLFluff using \"python -m\", which\ndiff --git a/src/sqlfluff/cli/formatters.py b/src/sqlfluff/cli/formatters.py\n--- a/src/sqlfluff/cli/formatters.py\n+++ b/src/sqlfluff/cli/formatters.py\n@@ -6,6 +6,7 @@\n import click\n from colorama import Style\n \n+from sqlfluff.cli import EXIT_FAIL, EXIT_SUCCESS\n from sqlfluff.cli.helpers import (\n get_package_version,\n get_python_version,\n@@ -14,6 +15,7 @@\n wrap_field,\n )\n from sqlfluff.cli.outputstream import OutputStream\n+\n from sqlfluff.core import SQLBaseError, FluffConfig, Linter, TimingSummary\n from sqlfluff.core.enums import Color\n from sqlfluff.core.linter import LintedFile, LintingResult, ParsedString\n@@ -517,7 +519,7 @@ def handle_files_with_tmp_or_prs_errors(self, lint_result: LintingResult) -> int\n color,\n )\n )\n- return 1 if num_filtered_errors else 0\n+ return EXIT_FAIL if num_filtered_errors else EXIT_SUCCESS\n \n def print_out_violations_and_timing(\n self,\ndiff --git a/src/sqlfluff/core/linter/linting_result.py b/src/sqlfluff/core/linter/linting_result.py\n--- a/src/sqlfluff/core/linter/linting_result.py\n+++ b/src/sqlfluff/core/linter/linting_result.py\n@@ -11,6 +11,7 @@\n )\n from typing_extensions import Literal\n \n+from sqlfluff.cli import EXIT_FAIL, EXIT_SUCCESS\n \n from sqlfluff.core.errors import (\n CheckTuple,\n@@ -23,8 +24,6 @@\n \n # Classes needed only for type checking\n from sqlfluff.core.parser.segments.base import BaseSegment\n-\n-\n from sqlfluff.core.linter.linted_dir import LintedDir\n \n \n@@ -133,7 +132,9 @@ def stats(self) -> Dict[str, Any]:\n all_stats[\"unclean rate\"] = 0\n all_stats[\"clean files\"] = all_stats[\"clean\"]\n all_stats[\"unclean files\"] = all_stats[\"unclean\"]\n- all_stats[\"exit code\"] = 65 if all_stats[\"violations\"] > 0 else 0\n+ all_stats[\"exit code\"] = (\n+ EXIT_FAIL if all_stats[\"violations\"] > 0 else EXIT_SUCCESS\n+ )\n all_stats[\"status\"] = \"FAIL\" if all_stats[\"violations\"] > 0 else \"PASS\"\n return all_stats\n \n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -71,7 +71,7 @@ def invoke_assert_code(\n def test__cli__command_directed():\n \"\"\"Basic checking of lint functionality.\"\"\"\n result = invoke_assert_code(\n- ret_code=65,\n+ ret_code=1,\n args=[\n lint,\n [\n@@ -95,7 +95,7 @@ def test__cli__command_dialect():\n \"\"\"Check the script raises the right exception on an unknown dialect.\"\"\"\n # The dialect is unknown should be a non-zero exit code\n invoke_assert_code(\n- ret_code=66,\n+ ret_code=2,\n args=[\n lint,\n [\n@@ -112,7 +112,7 @@ def test__cli__command_no_dialect():\n \"\"\"Check the script raises the right exception no dialect.\"\"\"\n # The dialect is unknown should be a non-zero exit code\n result = invoke_assert_code(\n- ret_code=1,\n+ ret_code=2,\n args=[\n lint,\n [\"-\"],\n@@ -129,7 +129,7 @@ def test__cli__command_parse_error_dialect_explicit_warning():\n # and a human-readable warning should be dislayed.\n # Dialect specified as commandline option.\n result = invoke_assert_code(\n- ret_code=66,\n+ ret_code=1,\n args=[\n parse,\n [\n@@ -152,7 +152,7 @@ def test__cli__command_parse_error_dialect_implicit_warning():\n # and a human-readable warning should be dislayed.\n # Dialect specified in .sqlfluff config.\n result = invoke_assert_code(\n- ret_code=66,\n+ ret_code=1,\n args=[\n # Config sets dialect to tsql\n parse,\n@@ -173,7 +173,7 @@ def test__cli__command_parse_error_dialect_implicit_warning():\n def test__cli__command_dialect_legacy():\n \"\"\"Check the script raises the right exception on a legacy dialect.\"\"\"\n result = invoke_assert_code(\n- ret_code=66,\n+ ret_code=2,\n args=[\n lint,\n [\n@@ -190,7 +190,7 @@ def test__cli__command_dialect_legacy():\n def test__cli__command_extra_config_fail():\n \"\"\"Check the script raises the right exception non-existent extra config path.\"\"\"\n result = invoke_assert_code(\n- ret_code=66,\n+ ret_code=2,\n args=[\n lint,\n [\n@@ -429,7 +429,7 @@ def test__cli__command_lint_parse(command):\n [\"test/fixtures/cli/unknown_jinja_tag/test.sql\", \"-vvvvvvv\"],\n \"y\",\n ),\n- 65,\n+ 1,\n ),\n ],\n )\n@@ -461,7 +461,7 @@ def test__cli__command_lint_skip_ignore_files():\n \"--disregard-sqlfluffignores\",\n ],\n )\n- assert result.exit_code == 65\n+ assert result.exit_code == 1\n assert \"L009\" in result.output.strip()\n \n \n@@ -488,7 +488,7 @@ def test__cli__command_lint_ignore_local_config():\n \"test/fixtures/cli/ignore_local_config/ignore_local_config_test.sql\",\n ],\n )\n- assert result.exit_code == 65\n+ assert result.exit_code == 1\n assert \"L012\" in result.output.strip()\n \n \n@@ -561,7 +561,7 @@ def generic_roundtrip_test(\n old_mode = stat.S_IMODE(status.st_mode)\n # Check that we first detect the issue\n invoke_assert_code(\n- ret_code=65, args=[lint, [\"--dialect=ansi\", \"--rules\", rulestring, filepath]]\n+ ret_code=1, args=[lint, [\"--dialect=ansi\", \"--rules\", rulestring, filepath]]\n )\n # Fix the file (in force mode)\n if force:\n@@ -997,7 +997,7 @@ def test__cli__command_fix_stdin_error_exit_code(\n \"rule,fname,prompt,exit_code,fix_exit_code\",\n [\n (\"L001\", \"test/fixtures/linter/indentation_errors.sql\", \"y\", 0, 0),\n- (\"L001\", \"test/fixtures/linter/indentation_errors.sql\", \"n\", 65, 1),\n+ (\"L001\", \"test/fixtures/linter/indentation_errors.sql\", \"n\", 1, 1),\n ],\n )\n def test__cli__command__fix_no_force(rule, fname, prompt, exit_code, fix_exit_code):\n@@ -1075,7 +1075,7 @@ def test__cli__command_parse_serialize_from_stdin(serialize, write_file, tmp_pat\n ],\n }\n ],\n- 65,\n+ 1,\n ),\n ],\n )\n@@ -1115,7 +1115,7 @@ def test__cli__command_lint_serialize_from_stdin(serialize, sql, expected, exit_\n )\n def test__cli__command_fail_nice_not_found(command):\n \"\"\"Check commands fail as expected when then don't find files.\"\"\"\n- result = invoke_assert_code(args=command, ret_code=1)\n+ result = invoke_assert_code(args=command, ret_code=2)\n assert \"could not be accessed\" in result.output\n \n \n@@ -1180,7 +1180,7 @@ def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_\n # note the file is in here twice. two files = two payloads.\n result = invoke_assert_code(\n args=[lint, cmd_args],\n- ret_code=65,\n+ ret_code=1,\n )\n \n if write_file:\n@@ -1226,7 +1226,7 @@ def test__cli__command_lint_serialize_github_annotation():\n \"--disable_progress_bar\",\n ),\n ],\n- ret_code=65,\n+ ret_code=1,\n )\n result = json.loads(result.output)\n assert result == [\n@@ -1337,7 +1337,7 @@ def test__cli__command_lint_serialize_github_annotation_native():\n \"--disable_progress_bar\",\n ),\n ],\n- ret_code=65,\n+ ret_code=1,\n )\n \n assert result.output == \"\\n\".join(\n@@ -1381,7 +1381,7 @@ def test__cli__command_lint_serialize_annotation_level_error_failure_equivalent(\n \"--disable_progress_bar\",\n ),\n ],\n- ret_code=65,\n+ ret_code=1,\n )\n \n result_failure = invoke_assert_code(\n@@ -1396,7 +1396,7 @@ def test__cli__command_lint_serialize_annotation_level_error_failure_equivalent(\n \"--disable_progress_bar\",\n ),\n ],\n- ret_code=65,\n+ ret_code=1,\n )\n \n assert result_error.output == result_failure.output\n@@ -1450,7 +1450,7 @@ def test_cli_encoding(encoding, method, expect_success, tmpdir):\n shutil.copy(sql_path, tmpdir)\n options = [str(tmpdir / \"encoding_test.sql\")]\n result = invoke_assert_code(\n- ret_code=65,\n+ ret_code=1,\n args=[\n lint,\n options,\n@@ -1479,7 +1479,7 @@ def test_cli_no_disable_noqa_flag():\n def test_cli_disable_noqa_flag():\n \"\"\"Test that --disable_noqa flag ignores inline noqa comments.\"\"\"\n result = invoke_assert_code(\n- ret_code=65,\n+ ret_code=1,\n args=[\n lint,\n [\n@@ -1563,7 +1563,7 @@ def test_cli_lint_enabled_progress_bar_multiple_paths(\n ) -> None:\n \"\"\"When progress bar is enabled, there should be some tracks in output.\"\"\"\n result = invoke_assert_code(\n- ret_code=65,\n+ ret_code=1,\n args=[\n lint,\n [\ndiff --git a/test/rules/std_roundtrip_test.py b/test/rules/std_roundtrip_test.py\n--- a/test/rules/std_roundtrip_test.py\n+++ b/test/rules/std_roundtrip_test.py\n@@ -34,7 +34,7 @@ def generic_roundtrip_test(source_file, rulestring):\n runner = CliRunner()\n # Check that we first detect the issue\n result = runner.invoke(lint, [\"--rules\", rulestring, \"--dialect=ansi\", filepath])\n- assert result.exit_code == 65\n+ assert result.exit_code == 1\n # Fix the file (in force mode)\n result = runner.invoke(\n fix, [\"--rules\", rulestring, \"--dialect=ansi\", \"-f\", filepath]\n@@ -80,7 +80,7 @@ def jinja_roundtrip_test(\n result = runner.invoke(\n lint, [\"--rules\", rulestring, \"--dialect=ansi\", sql_filepath]\n )\n- assert result.exit_code == 65\n+ assert result.exit_code == 1\n # Fix the file (in force mode)\n result = runner.invoke(\n fix, [\"--rules\", rulestring, \"-f\", \"--dialect=ansi\", sql_filepath]\n", "problem_statement": "Return codes are inconsistent\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nWorking on #3431 - I noticed that we're inconsistent in our return codes.\r\n\r\nIn `commands.py` we call `sys.exit()` in 15 places (currently).\r\n\r\n- Twice we call `sys.exit(0)` on success, at the end of `parse` and `lint` (`fix` is a handled differently, see below). \u2714\ufe0f \r\n- Six times we call `sys.exit(1)` for a selection of things:\r\n - Not having `cProfiler` installed.\r\n - Failing to apply fixes\r\n - User Errors and OSError (in `PathAndUserErrorHandler`)\r\n- Five times we call `sys.exit(66)` for a selection of things:\r\n - User Errors (including unknown dialect or failing to load a dialect or config)\r\n - If parsing failed when calling `parse`.\r\n- Once we use `handle_files_with_tmp_or_prs_errors` to determine the exit code (which returns 1 or 0)\r\n- Once we use `LintingResult.stats` to determine the exit code (which returns either 65 or 0)\r\n- Once we do a mixture of the above (see end of `fix`)\r\n\r\nThis neither DRY, or consistent ... or helpful?\r\n\r\n### Expected Behaviour\r\n\r\nWe should have consistent return codes for specific scenarios. There are up for discussion, but I would suggest:\r\n\r\n- 0 for success (obviously)\r\n- 1 for a fail which is error related: not having libraries installed, user errors etc...\r\n- 65 for a linting fail (i.e. no errors in running, but issues were found in either parsing or linting).\r\n- 66 for a fixing fail (i.e. we tried to fix errors but failed to do so for some reason).\r\n\r\nThese would be defined as constants at the top of `commands.py`.\r\n\r\n### Observed Behaviour\r\n\r\nsee above\r\n\r\n### How to reproduce\r\n\r\nsee above\r\n\r\n### Dialect\r\n\r\nN/A\r\n\r\n### Version\r\n\r\nDescription is as per code in #3431\r\n\r\n### Configuration\r\n\r\n-\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "I'm happy to contribute the changes for this one, but would appreciate views on what the error codes we should align on first @barrywhart @tunetheweb \nI'm not familiar with any widespread conventions about exit codes, except to keep them below 256.\r\n\r\nThis Stack Overflow post has a lot of discussion, often self-contradictory. https://stackoverflow.com/questions/1101957/are-there-any-standard-exit-status-codes-in-linux\r\n\r\nOverall, your proposal sounds good to me.\r\n\r\nCan you also search the existing issues for any mention of exit codes? I think there may be one or two open issues, perhaps related to the behavior when \"fix\" finds issues but some are unfixable. Because of its multifaceted nature as a linter and fixer that is used both interactively (e.g. during pre-commit) and in batch (CICD), SQLFluff perhaps has more stringent requirements for precise exit codes than some other tools. Do you think it'd be useful to review existing (and or write some new) user documentation before starting the coding, to help get a better understanding of the various use cases?\r\n\r\n\r\n\nAgree with @barrywhart 's comments.\r\n\r\nOnly question is why 65/66 instead of just 2/3?\n> Only question is why 65/66 instead of just 2/3?\r\n\r\nThis was initially because I had read that codes 0-64 were reserved for system usage but it appears things aren't that consistent.\r\n\r\n> This Stack Overflow post has a lot of discussion, often self-contradictory...\r\n\r\nI'm wondering based on this post whether we should simplify things:\r\n- 0: success\r\n- 1: fail (on linting or fixing, but due to finding issues with code or unable to fix, no \"errors\")\r\n- 2: fail because misuse or error\r\n\r\nIt's slightly less granular but a little more consistent with the bash approach (from the most recent post on that SO question):\r\n\r\n> Exit status 0: success\r\n> Exit status 1: \"failure\", as defined by the program\r\n> Exit status 2: command line usage error\nCleaning up the exit codes seems sensible. How likely do we think it is to break things for users?\nRelatively unlikely I reckon - I'm not sure the existing codes are sufficiently granular to be useful right now.", "created_at": "2022-07-14T15:06:34Z", "version": "1.1", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-1]", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/rules/std_roundtrip_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/rules/std_roundtrip_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/rules/std_roundtrip_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/rules/std_roundtrip_test.py::test__cli__command__fix[L010-test/fixtures/linter/whitespace_errors.sql]", "test/rules/std_roundtrip_test.py::test__cli__command__fix[L011-test/fixtures/dialects/ansi/select_simple_i.sql]", "test/rules/std_roundtrip_test.py::test__cli__command__fix[L012-test/fixtures/dialects/ansi/select_simple_i.sql]", "test/rules/std_roundtrip_test.py::test__cli__command__fix_templated[L010]", "test/rules/std_roundtrip_test.py::test__cli__command__fix_templated[L001]"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files"], "environment_setup_commit": "d83ab36bbb21f62cf0780d095a8be8cd366735d7"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3435", "base_commit": "8e724ef8906eecce7179f4b7c52d4fc0672e4bd9", "patch": "diff --git a/src/sqlfluff/rules/L027.py b/src/sqlfluff/rules/L027.py\n--- a/src/sqlfluff/rules/L027.py\n+++ b/src/sqlfluff/rules/L027.py\n@@ -99,23 +99,6 @@ def _lint_references_and_aliases(\n )\n )\n \n- all_table_aliases = [t.ref_str for t in table_aliases] + standalone_aliases\n-\n- # For qualified references, we want to check that the alias is actually\n- # valid\n- if (\n- this_ref_type == \"qualified\"\n- and list(r.iter_raw_references())[0].part not in all_table_aliases\n- ):\n- violation_buff.append(\n- LintResult(\n- anchor=r,\n- description=f\"Qualified reference {r.raw!r} not found in \"\n- f\"available tables/view aliases {all_table_aliases} in select \"\n- \"with more than one referenced table/view.\",\n- )\n- )\n-\n return violation_buff or None\n \n def _init_ignore_words_list(self):\n", "test_patch": "diff --git a/test/fixtures/rules/std_rule_cases/L027.yml b/test/fixtures/rules/std_rule_cases/L027.yml\n--- a/test/fixtures/rules/std_rule_cases/L027.yml\n+++ b/test/fixtures/rules/std_rule_cases/L027.yml\n@@ -221,43 +221,6 @@ test_pass_rowtype_with_join:\n core:\n dialect: hive\n \n-test_fail_column_name_not_found_in_table_aliases_bigquery:\n- # qualified reference should actually exists in table aliases\n- fail_str: |\n- SELECT\n- a.bar,\n- b.foo,\n- this_is.some_struct.id\n- FROM\n- a LEFT JOIN b ON TRUE\n- configs:\n- core:\n- dialect: bigquery\n-\n-test_pass_column_name_is_a_struct_bigquery:\n- # check structs work as expected\n- pass_str: |\n- SELECT\n- a.bar,\n- b.this_is.some_struct.id\n- FROM\n- a LEFT JOIN b ON TRUE\n- configs:\n- core:\n- dialect: bigquery\n-\n-test_pass_column_name_from_unnest_bigquery:\n- # Check that we allow an table alias come from UNNEST statement\n- pass_str: |\n- SELECT\n- a.bar,\n- e.foo\n- FROM\n- a LEFT JOIN UNEST(a.events) AS e\n- configs:\n- core:\n- dialect: bigquery\n-\n test_fail_table_plus_flatten_snowflake_1:\n # FLATTEN() returns a table, thus there are two tables, thus lint failure.\n fail_str: |\n@@ -328,3 +291,48 @@ test_pass_ignore_words_regex_bigquery_declare_example:\n rules:\n L027:\n ignore_words_regex: ^_\n+\n+test_pass_redshift:\n+ # This was failing in issue 3380.\n+ pass_str:\n+ SELECT account.id\n+ FROM salesforce_sd.account\n+ INNER JOIN salesforce_sd.\"user\" ON salesforce_sd.\"user\".id = account.ownerid\n+ configs:\n+ core:\n+ dialect: redshift\n+\n+test_pass_tsql:\n+ # This was failing in issue 3342.\n+ pass_str:\n+ select\n+ psc.col1\n+ from\n+ tbl1 as psc\n+ where\n+ exists\n+ (\n+ select 1 as data\n+ from\n+ tbl2 as pr\n+ join tbl2 as c on c.cid = pr.cid\n+ where\n+ c.col1 = 'x'\n+ and pr.col2 <= convert(date, getdate())\n+ and pr.pid = psc.pid\n+ )\n+ configs:\n+ core:\n+ dialect: tsql\n+\n+test_pass_ansi:\n+ # This was failing in issue 3055.\n+ pass_str: |\n+ SELECT my_col\n+ FROM my_table\n+ WHERE EXISTS (\n+ SELECT 1\n+ FROM other_table\n+ INNER JOIN mapping_table ON (mapping_table.other_fk = other_table.id_pk)\n+ WHERE mapping_table.kind = my_table.kind\n+ )\ndiff --git a/test/rules/std_test.py b/test/rules/std_test.py\n--- a/test/rules/std_test.py\n+++ b/test/rules/std_test.py\n@@ -68,7 +68,7 @@\n ),\n (\"L016\", \"block_comment_errors_2.sql\", [(1, 85), (2, 86)]),\n # Column references\n- (\"L027\", \"column_references.sql\", [(1, 8), (1, 11)]),\n+ (\"L027\", \"column_references.sql\", [(1, 8)]),\n (\"L027\", \"column_references_bare_function.sql\", []),\n (\"L026\", \"column_references.sql\", [(1, 11)]),\n (\"L025\", \"column_references.sql\", [(2, 11)]),\n", "problem_statement": "L027: outer-level table not found in WHERE clause sub-select\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nOuter-level table/view referenced in sub-select inside `WHERE` clause is not being detected.\r\n\r\nThis error seems to only occur when the sub-select contains joins.\r\n\r\n### Expected Behaviour\r\n\r\nNo error\r\n\r\n### Observed Behaviour\r\n\r\n```\r\nL: 7 | P: 32 | L027 | Qualified reference 'my_table.kind' not found in\r\n | available tables/view aliases ['other_table',\r\n | 'mapping_table'] in select with more than one referenced\r\n | table/view.\r\n```\r\n\r\n### How to reproduce\r\n\r\n```sql\r\nSELECT my_col\r\nFROM my_table\r\nWHERE EXISTS (\r\n SELECT 1\r\n FROM other_table\r\n INNER JOIN mapping_table ON (mapping_table.other_fk = other_table.id_pk)\r\n WHERE mapping_table.kind = my_table.kind\r\n);\r\n```\r\n\r\n### Dialect\r\n\r\npostgres\r\n\r\n### Version\r\n\r\nsqlfluff, version 0.12.0\r\n\r\n### Configuration\r\n\r\n```\r\n[sqlfluff]\r\nnocolor = True\r\ndialect = postgres\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [ ] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "Does L027 use `SelectCrawler`? This sounds like an issue where it may be helpful.\r\n\r\nRelated: Rules that use `SelectCrawler` may be good candidates to benefit from setting `recurse_into` to `False`. (Setting the flag is just a start. This also requires reworking the rule code, hopefully no more than 1-2 hours of work.)\nAnswering my own question: It does not seem to use `SelectCrawler`. Rules that currently use it:\r\n* L025\r\n* L026\r\n* L044\r\n* L045\r\n\r\nFrom a quick look at the YML test files for each of these rules, I suggest L044 would be the best one to review in terms of handling similar requirements. Look for test cases that mention \"subquery\".\nI think a very similar fix to that implemented in this [PR for L028](https://github.com/sqlfluff/sqlfluff/pull/3156) will also work here. In particular, notice the code that looks at `query.parent` to find tables that are \"visible\" to a particular query.\r\n\r\nhttps://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/rules/L028.py#L108L114\nRelated to #3380, possibly duplicate", "created_at": "2022-06-07T18:47:03Z", "version": "0.13", "FAIL_TO_PASS": ["test/rules/std_test.py::test__rules__std_file[L027-column_references.sql-violations16]"], "PASS_TO_PASS": ["test/rules/std_test.py::test__rules__std_file[L001-indentation_errors.sql-violations0]", "test/rules/std_test.py::test__rules__std_file[L002-indentation_errors.sql-violations1]", "test/rules/std_test.py::test__rules__std_file[L003-indentation_errors.sql-violations2]", "test/rules/std_test.py::test__rules__std_file[L004-indentation_errors.sql-violations3]", "test/rules/std_test.py::test__rules__std_file[L005-whitespace_errors.sql-violations4]", "test/rules/std_test.py::test__rules__std_file[L019-whitespace_errors.sql-violations5]", "test/rules/std_test.py::test__rules__std_file[L008-whitespace_errors.sql-violations6]", "test/rules/std_test.py::test__rules__std_file[L006-operator_errors.sql-violations7]", "test/rules/std_test.py::test__rules__std_file[L039-operator_errors.sql-violations8]", "test/rules/std_test.py::test__rules__std_file[L007-operator_errors.sql-violations9]", "test/rules/std_test.py::test__rules__std_file[L006-operator_errors_negative.sql-violations10]", "test/rules/std_test.py::test__rules__std_file[L039-operator_errors_negative.sql-violations11]", "test/rules/std_test.py::test__rules__std_file[L003-indentation_error_hard.sql-violations12]", "test/rules/std_test.py::test__rules__std_file[L003-indentation_error_contained.sql-violations13]", "test/rules/std_test.py::test__rules__std_file[L016-block_comment_errors.sql-violations14]", "test/rules/std_test.py::test__rules__std_file[L016-block_comment_errors_2.sql-violations15]", "test/rules/std_test.py::test__rules__std_file[L027-column_references_bare_function.sql-violations17]", "test/rules/std_test.py::test__rules__std_file[L026-column_references.sql-violations18]", "test/rules/std_test.py::test__rules__std_file[L025-column_references.sql-violations19]", "test/rules/std_test.py::test__rules__std_file[L021-select_distinct_group_by.sql-violations20]", "test/rules/std_test.py::test__rules__std_file[L006-operator_errors_ignore.sql-violations21]", "test/rules/std_test.py::test__rules__std_file[L031-aliases_in_join_error.sql-violations22]", "test/rules/std_test.py::test__rules__std_file[L046-heavy_templating.sql-violations23]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict0]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict1]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict2]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict3]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict4]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict5]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict6]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict7]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict8]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict9]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict10]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict11]"], "environment_setup_commit": "6e8ce43a4958dbaa56256365c2a89d8db92e07d6"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3904", "base_commit": "2ac8e125604aa1f19d9811f7dc5bd56eefa654ac", "patch": "diff --git a/src/sqlfluff/cli/click_deprecated_option.py b/src/sqlfluff/cli/click_deprecated_option.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/sqlfluff/cli/click_deprecated_option.py\n@@ -0,0 +1,104 @@\n+\"\"\"Allows to provide deprecated options for click's command.\"\"\"\n+\n+from typing import Any, Callable\n+\n+import click\n+from click import Context, OptionParser, echo, style\n+from click.parser import Option, ParsingState\n+\n+\n+class DeprecatedOption(click.Option):\n+ \"\"\"Allows to provide deprecated options for click's command.\n+\n+ Works with `DeprecatedOptionsCommand` (see below).\n+ Expects to be provided into standard `@click.option` with:\n+ * two parameter declarations arguments - old one (deprecated)\n+ and new one (preferred);\n+ * `cls` parameter (standard click Option) as `cls=DeprecatedOption`;\n+ * `deprecated` parameter - which says which ones are deprecated,\n+ like`deprecated=[\"--disable_progress_bar\"]1.\n+\n+ This is based on\n+ * https://stackoverflow.com/a/50402799/5172513\n+\n+ It's somewhat hackish and may broke when click internals are changed, it is even\n+ mentioned in SO:\n+ > This code reaches into some private structures in the parser, but this is\n+ unlikely to be an issue. This parser code was last changed 4 years ago.\n+ The parser code is unlikely to undergo significant revisions.\n+\n+ Hopefully will be removed when\n+ * https://github.com/pallets/click/issues/2263\n+ is finished.\n+ \"\"\"\n+\n+ def __init__(self, *args, **kwargs):\n+ self.deprecated = kwargs.pop(\"deprecated\", ())\n+ self.preferred = args[0][-1]\n+\n+ super().__init__(*args, **kwargs)\n+\n+\n+class DeprecatedOptionsCommand(click.Command):\n+ \"\"\"Allows to provide deprecated options for click's command.\n+\n+ Works with `DeprecatedOption` (see above).\n+ Expects to be provided into standard `@click.command` as:\n+ * `@cli.command(cls=DeprecatedOptionsCommand)`\n+ \"\"\"\n+\n+ def make_parser(self, ctx: Context) -> OptionParser:\n+ \"\"\"Hook 'make_parser' and during processing check the name.\n+\n+ Used to invoke the option to see if it is preferred.\n+ \"\"\"\n+ parser: OptionParser = super().make_parser(ctx)\n+\n+ # get the parser options\n+ options = set(parser._short_opt.values())\n+ options |= set(parser._long_opt.values())\n+\n+ for option in options:\n+ if not isinstance(option.obj, DeprecatedOption):\n+ continue\n+\n+ option.process = self._make_process(option) # type: ignore\n+\n+ return parser\n+\n+ def _make_process(self, an_option: Option) -> Callable:\n+ \"\"\"Construct a closure to the parser option processor.\"\"\"\n+ orig_process: Callable = an_option.process\n+ deprecated = getattr(an_option.obj, \"deprecated\", None)\n+ preferred = getattr(an_option.obj, \"preferred\", None)\n+\n+ if not deprecated:\n+ raise ValueError(\n+ f\"Expected `deprecated` value for `{an_option.obj.name!r}`\"\n+ )\n+\n+ def process(value: Any, state: ParsingState) -> None:\n+ \"\"\"Custom process method.\n+\n+ The function above us on the stack used 'opt' to\n+ pick option from a dict, see if it is deprecated.\n+ \"\"\"\n+ # reach up the stack and get 'opt'\n+ import inspect\n+\n+ frame = inspect.currentframe()\n+ try:\n+ opt = frame.f_back.f_locals.get(\"opt\") # type: ignore\n+ finally:\n+ del frame\n+\n+ if opt in deprecated: # type: ignore\n+ msg = (\n+ f\"DeprecationWarning: The option {opt!r} is deprecated, \"\n+ f\"use {preferred!r}.\"\n+ )\n+ echo(style(msg, fg=\"red\"), err=True)\n+\n+ return orig_process(value, state)\n+\n+ return process\ndiff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -23,6 +23,10 @@\n from sqlfluff.cli.autocomplete import shell_completion_enabled, dialect_shell_complete\n \n from sqlfluff.cli import EXIT_SUCCESS, EXIT_ERROR, EXIT_FAIL\n+from sqlfluff.cli.click_deprecated_option import (\n+ DeprecatedOption,\n+ DeprecatedOptionsCommand,\n+)\n from sqlfluff.cli.formatters import (\n format_linting_result_header,\n OutputStreamFormatter,\n@@ -455,7 +459,7 @@ def dump_file_payload(filename: Optional[str], payload: str):\n click.echo(payload)\n \n \[email protected]()\[email protected](cls=DeprecatedOptionsCommand)\n @common_options\n @core_options\n @click.option(\n@@ -509,8 +513,11 @@ def dump_file_payload(filename: Optional[str], payload: str):\n )\n @click.option(\n \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n is_flag=True,\n help=\"Disables progress bars.\",\n+ cls=DeprecatedOption,\n+ deprecated=[\"--disable_progress_bar\"],\n )\n @click.argument(\"paths\", nargs=-1, type=click.Path(allow_dash=True))\n def lint(\n@@ -704,7 +711,7 @@ def do_fixes(lnt, result, formatter=None, **kwargs):\n ),\n )\n @click.option(\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n is_flag=True,\n help=\"Disables progress bars.\",\n )\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -112,7 +112,7 @@ def test__cli__command_directed():\n args=[\n lint,\n [\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n \"test/fixtures/linter/indentation_error_simple.sql\",\n ],\n ],\n@@ -1002,7 +1002,7 @@ def test__cli__command_fix_stdin(stdin, rules, stdout):\n result = invoke_assert_code(\n args=[\n fix,\n- (\"-\", \"--rules\", rules, \"--disable_progress_bar\", \"--dialect=ansi\"),\n+ (\"-\", \"--rules\", rules, \"--disable-progress-bar\", \"--dialect=ansi\"),\n ],\n cli_input=stdin,\n )\n@@ -1036,7 +1036,7 @@ def test__cli__command_fix_stdin_safety():\n \n # just prints the very same thing\n result = invoke_assert_code(\n- args=[fix, (\"-\", \"--disable_progress_bar\", \"--dialect=ansi\")],\n+ args=[fix, (\"-\", \"--disable-progress-bar\", \"--dialect=ansi\")],\n cli_input=perfect_sql,\n )\n assert result.output.strip() == perfect_sql\n@@ -1177,7 +1177,7 @@ def test__cli__command_lint_serialize_from_stdin(serialize, sql, expected, exit_\n \"L010\",\n \"--format\",\n serialize,\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n \"--dialect=ansi\",\n ),\n ],\n@@ -1222,7 +1222,7 @@ def test__cli__command_lint_nocolor(isatty, should_strip_ansi, capsys, tmpdir):\n \"--nocolor\",\n \"--dialect\",\n \"ansi\",\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n fpath,\n \"--write-output\",\n output_file,\n@@ -1253,7 +1253,7 @@ def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_\n fpath,\n \"--format\",\n serialize,\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n )\n \n if write_file:\n@@ -1310,7 +1310,7 @@ def test__cli__command_lint_serialize_github_annotation():\n \"github-annotation\",\n \"--annotation-level\",\n \"warning\",\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n ),\n ],\n ret_code=1,\n@@ -1421,7 +1421,7 @@ def test__cli__command_lint_serialize_github_annotation_native():\n \"github-annotation-native\",\n \"--annotation-level\",\n \"error\",\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n ),\n ],\n ret_code=1,\n@@ -1465,7 +1465,7 @@ def test__cli__command_lint_serialize_annotation_level_error_failure_equivalent(\n serialize,\n \"--annotation-level\",\n \"error\",\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n ),\n ],\n ret_code=1,\n@@ -1480,7 +1480,7 @@ def test__cli__command_lint_serialize_annotation_level_error_failure_equivalent(\n serialize,\n \"--annotation-level\",\n \"failure\",\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n ),\n ],\n ret_code=1,\n@@ -1613,6 +1613,25 @@ def test_cli_lint_disabled_progress_bar(\n self, mock_disable_progress_bar: MagicMock\n ) -> None:\n \"\"\"When progress bar is disabled, nothing should be printed into output.\"\"\"\n+ result = invoke_assert_code(\n+ args=[\n+ lint,\n+ [\n+ \"--disable-progress-bar\",\n+ \"test/fixtures/linter/passing.sql\",\n+ ],\n+ ],\n+ )\n+ raw_output = repr(result.output)\n+\n+ assert \"\\rpath test/fixtures/linter/passing.sql:\" not in raw_output\n+ assert \"\\rparsing: 0it\" not in raw_output\n+ assert \"\\r\\rlint by rules:\" not in raw_output\n+\n+ def test_cli_lint_disabled_progress_bar_deprecated_option(\n+ self, mock_disable_progress_bar: MagicMock\n+ ) -> None:\n+ \"\"\"Same as above but checks additionally if deprecation warning is printed.\"\"\"\n result = invoke_assert_code(\n args=[\n lint,\n@@ -1627,6 +1646,10 @@ def test_cli_lint_disabled_progress_bar(\n assert \"\\rpath test/fixtures/linter/passing.sql:\" not in raw_output\n assert \"\\rparsing: 0it\" not in raw_output\n assert \"\\r\\rlint by rules:\" not in raw_output\n+ assert (\n+ \"DeprecationWarning: The option '--disable_progress_bar' is deprecated, \"\n+ \"use '--disable-progress-bar'\"\n+ ) in raw_output\n \n def test_cli_lint_enabled_progress_bar(\n self, mock_disable_progress_bar: MagicMock\n@@ -1709,7 +1732,7 @@ def test__cli__fix_multiple_errors_no_show_errors():\n args=[\n fix,\n [\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n \"test/fixtures/linter/multiple_sql_errors.sql\",\n ],\n ],\n@@ -1729,7 +1752,7 @@ def test__cli__fix_multiple_errors_show_errors():\n args=[\n fix,\n [\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n \"--show-lint-violations\",\n \"test/fixtures/linter/multiple_sql_errors.sql\",\n ],\n@@ -1771,7 +1794,7 @@ def test__cli__multiple_files__fix_multiple_errors_show_errors():\n args=[\n fix,\n [\n- \"--disable_progress_bar\",\n+ \"--disable-progress-bar\",\n \"--show-lint-violations\",\n sql_path,\n indent_path,\ndiff --git a/test/cli/test_click_deprecated_option.py b/test/cli/test_click_deprecated_option.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/cli/test_click_deprecated_option.py\n@@ -0,0 +1,68 @@\n+\"\"\"The Test suite for `DeprecatedOption` - extension for click options.\"\"\"\n+from typing import List\n+\n+import click\n+import pytest\n+\n+from sqlfluff.cli.click_deprecated_option import (\n+ DeprecatedOption,\n+ DeprecatedOptionsCommand,\n+)\n+from test.cli.commands_test import invoke_assert_code\n+\n+\n+class TestClickDeprecatedOption:\n+ \"\"\"Tests for custom click's option `DeprecatedOption`.\"\"\"\n+\n+ @pytest.mark.parametrize(\n+ \"option, expected_output\",\n+ [\n+ ([], \"{'old_option': False}\\n\"),\n+ (\n+ [\"--old_option\"],\n+ \"DeprecationWarning: The option '--old_option' is deprecated, \"\n+ \"use '--new_option'.\\n{'old_option': True}\\n\",\n+ ),\n+ ([\"--new_option\"], \"{'old_option': True}\\n\"),\n+ ],\n+ )\n+ def test_cli_deprecated_option(\n+ self, option: List[str], expected_output: str\n+ ) -> None:\n+ \"\"\"Prepares command with option which has deprecated version and checks it.\"\"\"\n+\n+ @click.command(cls=DeprecatedOptionsCommand)\n+ @click.option(\n+ \"--old_option\",\n+ \"--new_option\",\n+ is_flag=True,\n+ cls=DeprecatedOption,\n+ deprecated=[\"--old_option\"],\n+ )\n+ def some_command(**kwargs):\n+ click.echo(\"{}\".format(kwargs))\n+\n+ result = invoke_assert_code(args=[some_command, option])\n+ raw_output = result.output\n+\n+ assert raw_output == expected_output\n+\n+ def test_cli_deprecated_option_should_fail_when_missing_attr(\n+ self,\n+ ) -> None:\n+ \"\"\"The DeprecatedOption needs to have specified deprecated attr.\"\"\"\n+\n+ @click.command(cls=DeprecatedOptionsCommand)\n+ @click.option(\n+ \"--old_option\",\n+ \"--new_option\",\n+ is_flag=True,\n+ cls=DeprecatedOption,\n+ )\n+ def some_command(**kwargs):\n+ click.echo(\"{}\".format(kwargs))\n+\n+ with pytest.raises(ValueError) as exc:\n+ invoke_assert_code(args=[some_command, [\"--old_option\"]])\n+\n+ assert str(exc.value) == \"Expected `deprecated` value for `'old_option'`\"\n", "problem_statement": "Standardise `--disable_progress_bar` naming\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nAs noted in https://github.com/sqlfluff/sqlfluff/pull/3610#discussion_r926014745 `--disable_progress_bar` is the only command line option using underscores instead of dashes.\r\n\r\nShould we change this?\r\n\r\nThis would be a breaking change, so do we leave until next major release?\r\nOr do we accept both options?\n\n### Expected Behaviour\n\nWe should be standard in out command line option format\n\n### Observed Behaviour\n\n`--disable_progress_bar` is the only non-standard one\n\n### How to reproduce\n\nN/A\n\n### Dialect\n\nN/A\n\n### Version\n\n1.2.1\n\n### Configuration\n\nN/A\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [X] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "I like the idea (of at least as a transition) or accepting both, but then defaulting to the one consistent with the other options.\nSo this is about changing option `--disable_progress_bar` to `--disable-progress-bar`, right? I think I can take care of that, it was me who introduced it here :)\r\n\r\nAdditionally I would make an attempt to have these two options available, but to nicely inform users that one with underscores is deprecated. What do you think @tunetheweb? \r\n\r\nI see I cannot assign myself to that Issue.\r\n\n> So this is about changing option `--disable_progress_bar` to `--disable-progress-bar`, right? I think I can take care of that, it was me who introduced it here :)\r\n\r\nCorrect and thanks for taking on\r\n\r\n> Additionally I would make an attempt to have these two options available, but to nicely inform users that one with underscores is deprecated. What do you think @tunetheweb?\r\n\r\n@alanmcruickshank added some functionality that might help in #3874 but not sure if that applies to command lines options too (I\u2019m having less time to work on SQLFluff lately so not following it as closely as I used to). If not maybe it should?\r\n\r\n> I see I cannot assign myself to that Issue.\r\n\r\nYeah only maintainers can assign, which is a bit of an annoying restriction of GitHub so we tend not to use that field and commenting (like you\u2019ve done here) is sufficient to claim an issue. Please comment again if to \u201cunassign\u201d yourself if it turns out you won\u2019t be able to work on it after all. Though lack of progress is a usually good indicator of that anyway \ud83d\ude04", "created_at": "2022-10-01T22:18:25Z", "version": "1.3", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/test_click_deprecated_option.py::TestClickDeprecatedOption::test_cli_deprecated_option[option0-{'old_option':", "test/cli/test_click_deprecated_option.py::TestClickDeprecatedOption::test_cli_deprecated_option[option1-DeprecationWarning:", "test/cli/test_click_deprecated_option.py::TestClickDeprecatedOption::test_cli_deprecated_option[option2-{'old_option':", "test/cli/test_click_deprecated_option.py::TestClickDeprecatedOption::test_cli_deprecated_option_should_fail_when_missing_attr"], "PASS_TO_PASS": [], "environment_setup_commit": "dc59c2a5672aacedaf91f0e6129b467eefad331b"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4753", "base_commit": "24178a589c279220c6605324c446122d15ebc3fb", "patch": "diff --git a/docs/generate-rule-docs.py b/docs/generate-rule-docs.py\n--- a/docs/generate-rule-docs.py\n+++ b/docs/generate-rule-docs.py\n@@ -41,8 +41,9 @@\n # Set the bundle name to the ref.\n _bundle_name = f\":ref:`bundle_{bundle}`\"\n for idx, rule in enumerate(rule_bundles[bundle]):\n- aliases = \", \".join(rule.aliases[:3]) + (\n- \",\" if len(rule.aliases) > 3 else \"\"\n+ step = 1 # The number of aliases per line.\n+ aliases = \", \".join(rule.aliases[:step]) + (\n+ \",\" if len(rule.aliases) > step else \"\"\n )\n name_ref = f\":sqlfluff:ref:`{rule.name}`\"\n code_ref = f\":sqlfluff:ref:`{rule.code}`\"\n@@ -51,15 +52,16 @@\n f\"| {code_ref : <28} | {aliases : <18} |\\n\"\n )\n \n- j = 3\n+ j = 1\n+\n while True:\n if not rule.aliases[j:]:\n break\n- aliases = \", \".join(rule.aliases[j : j + 3]) + (\n- \",\" if len(rule.aliases[j:]) > 3 else \"\"\n+ aliases = \", \".join(rule.aliases[j : j + step]) + (\n+ \",\" if len(rule.aliases[j:]) > step else \"\"\n )\n f.write(f\"|{' ' * 42}|{' ' * 50}|{' ' * 30}| {aliases : <18} |\\n\")\n- j += 3\n+ j += step\n \n if idx + 1 < len(rule_bundles[bundle]):\n f.write(f\"|{' ' * 42}+{'-' * 50}+{'-' * 30}+{'-' * 20}+\\n\")\ndiff --git a/src/sqlfluff/rules/layout/LT12.py b/src/sqlfluff/rules/layout/LT12.py\n--- a/src/sqlfluff/rules/layout/LT12.py\n+++ b/src/sqlfluff/rules/layout/LT12.py\n@@ -102,8 +102,10 @@ class Rule_LT12(BaseRule):\n \n \"\"\"\n \n- name = \"layout.end-of-file\"\n- aliases = (\"L009\",)\n+ name = \"layout.end_of_file\"\n+ # Between 2.0.0 and 2.0.4 we supported had a kebab-case name for this rule\n+ # so the old name remains here as an alias to enable backward compatibility.\n+ aliases = (\"L009\", \"layout.end-of-file\")\n groups = (\"all\", \"core\", \"layout\")\n \n targets_templated = True\n", "test_patch": "diff --git a/test/api/simple_test.py b/test/api/simple_test.py\n--- a/test/api/simple_test.py\n+++ b/test/api/simple_test.py\n@@ -95,7 +95,7 @@\n \"line_no\": 1,\n \"line_pos\": 41,\n \"description\": \"Files must end with a single trailing newline.\",\n- \"name\": \"layout.end-of-file\",\n+ \"name\": \"layout.end_of_file\",\n },\n ]\n \n", "problem_statement": "layout.end-of-file is the only rule in kebab case\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nOur rules are all in `snake_case`, except for `layout.end-of-file`\n\n### Expected Behaviour\n\nAll rules should be in snake case\n\n### Observed Behaviour\n\nAs above\n\n### How to reproduce\n\n-\n\n### Dialect\n\nNA\n\n### Version\n\nMain\n\n### Configuration\n\nNA\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [X] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "", "created_at": "2023-04-14T12:49:53Z", "version": "1.4", "FAIL_TO_PASS": ["test/api/simple_test.py::test__api__lint_string"], "PASS_TO_PASS": ["test/api/simple_test.py::test__api__lint_string_without_violations", "test/api/simple_test.py::test__api__lint_string_specific", "test/api/simple_test.py::test__api__lint_string_specific_single", "test/api/simple_test.py::test__api__lint_string_specific_exclude", "test/api/simple_test.py::test__api__lint_string_specific_exclude_single", "test/api/simple_test.py::test__api__lint_string_specific_exclude_all_failed_rules", "test/api/simple_test.py::test__api__fix_string", "test/api/simple_test.py::test__api__fix_string_specific", "test/api/simple_test.py::test__api__fix_string_specific_exclude", "test/api/simple_test.py::test__api__fix_string_unparsable", "test/api/simple_test.py::test__api__fix_string_unparsable_fix_even_unparsable", "test/api/simple_test.py::test__api__parse_string", "test/api/simple_test.py::test__api__parse_fail", "test/api/simple_test.py::test__api__config_path", "test/api/simple_test.py::test__api__config_override[kwargs0-expected0]", "test/api/simple_test.py::test__api__config_override[kwargs1-expected1]", "test/api/simple_test.py::test__api__invalid_dialect"], "environment_setup_commit": "d19de0ecd16d298f9e3bfb91da122734c40c01e5"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4778", "base_commit": "e3f77d58f56149f9c8db3b790ef263b9853a9cb5", "patch": "diff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -189,7 +189,7 @@ def _lex_templated_file(\n getattr(elem, \"indent_val\", 0)\n for elem in cast(Tuple[BaseSegment, ...], tokens)\n )\n- if indent_balance != 0:\n+ if indent_balance != 0: # pragma: no cover\n linter_logger.debug(\n \"Indent balance test failed for %r. Template indents will not be \"\n \"linted for this file.\",\n@@ -207,7 +207,7 @@ def _lex_templated_file(\n if token.indent_val != 0:\n # Don't allow it if we're not linting templating block indents.\n if not templating_blocks_indent:\n- continue\n+ continue # pragma: no cover\n new_tokens.append(token)\n \n # Return new buffer\ndiff --git a/src/sqlfluff/core/templaters/slicers/tracer.py b/src/sqlfluff/core/templaters/slicers/tracer.py\n--- a/src/sqlfluff/core/templaters/slicers/tracer.py\n+++ b/src/sqlfluff/core/templaters/slicers/tracer.py\n@@ -524,7 +524,7 @@ def extract_block_type(tag_name, block_subtype):\n # a block, but its behavior is basically syntactic sugar for\n # {{ open(\"somefile).read() }}. Thus, treat it as templated code.\n # It's a similar situation with {% import %} and {% from ... import %}.\n- if tag_name in [\"include\", \"import\", \"from\"]:\n+ if tag_name in [\"include\", \"import\", \"from\", \"do\"]:\n block_type = \"templated\"\n elif tag_name.startswith(\"end\"):\n block_type = \"block_end\"\n", "test_patch": "diff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -1091,6 +1091,23 @@ def _load_result(*args, **kwargs):\n (\"literal\", slice(132, 133, None), slice(34, 35, None)),\n ],\n ),\n+ (\n+ # Tests Jinja \"do\" directive. Should be treated as a\n+ # templated instead of block - issue 4603.\n+ \"\"\"{% do true %}\n+\n+{% if true %}\n+ select 1\n+{% endif %}\"\"\",\n+ None,\n+ [\n+ (\"templated\", slice(0, 13, None), slice(0, 0, None)),\n+ (\"literal\", slice(13, 15, None), slice(0, 2, None)),\n+ (\"block_start\", slice(15, 28, None), slice(2, 2, None)),\n+ (\"literal\", slice(28, 42, None), slice(2, 16, None)),\n+ (\"block_end\", slice(42, 53, None), slice(16, 16, None)),\n+ ],\n+ ),\n (\n # Tests issue 2541, a bug where the {%- endfor %} was causing\n # IndexError: list index out of range.\n", "problem_statement": "2.0.2 - LT02 issues when query contains \"do\" statement.\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nSQLFluff v2.0.2 gives LT02 indentation errors for the Jinja `if`-block when `template_blocks_indent` is set to `True`.\r\nThe example SQL below is a bit contrived, but it's the smallest failing example I could produce based on our real SQL.\r\n\r\nIf I remove the Jinja `do`-expression from the code, the `if` block validates without errors.\r\n\r\n### Expected Behaviour\r\n\r\nI expect the SQL to pass the linting tests.\r\n\r\n### Observed Behaviour\r\n\r\nOutput from SQLFluff v2.0.2:\r\n```\r\nL: 5 | P: 1 | LT02 | Line should not be indented.\r\n | [layout.indent]\r\nL: 6 | P: 1 | LT02 | Line should not be indented.\r\n | [layout.indent]\r\n```\r\n\r\n### How to reproduce\r\n\r\nSQL to reproduce:\r\n```\r\n{% set cols = ['a', 'b'] %}\r\n{% do cols.remove('a') %}\r\n\r\n{% if true %}\r\n select a\r\n from some_table\r\n{% endif %}\r\n```\r\n\r\n### Dialect\r\n\r\n`ansi`\r\n\r\n### Version\r\n\r\n```\r\n> sqlfluff --version\r\nsqlfluff, version 2.0.2\r\n\r\n> python --version\r\nPython 3.9.9\r\n```\r\n\r\n### Configuration\r\n\r\n```\r\n[sqlfluff]\r\ndialect = ansi\r\ntemplater = jinja\r\n\r\n[sqlfluff:indentation]\r\ntemplate_blocks_indent = True\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n2.0.2 - LT02 issues when query contains \"do\" statement.\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nSQLFluff v2.0.2 gives LT02 indentation errors for the Jinja `if`-block when `template_blocks_indent` is set to `True`.\r\nThe example SQL below is a bit contrived, but it's the smallest failing example I could produce based on our real SQL.\r\n\r\nIf I remove the Jinja `do`-expression from the code, the `if` block validates without errors.\r\n\r\n### Expected Behaviour\r\n\r\nI expect the SQL to pass the linting tests.\r\n\r\n### Observed Behaviour\r\n\r\nOutput from SQLFluff v2.0.2:\r\n```\r\nL: 5 | P: 1 | LT02 | Line should not be indented.\r\n | [layout.indent]\r\nL: 6 | P: 1 | LT02 | Line should not be indented.\r\n | [layout.indent]\r\n```\r\n\r\n### How to reproduce\r\n\r\nSQL to reproduce:\r\n```\r\n{% set cols = ['a', 'b'] %}\r\n{% do cols.remove('a') %}\r\n\r\n{% if true %}\r\n select a\r\n from some_table\r\n{% endif %}\r\n```\r\n\r\n### Dialect\r\n\r\n`ansi`\r\n\r\n### Version\r\n\r\n```\r\n> sqlfluff --version\r\nsqlfluff, version 2.0.2\r\n\r\n> python --version\r\nPython 3.9.9\r\n```\r\n\r\n### Configuration\r\n\r\n```\r\n[sqlfluff]\r\ndialect = ansi\r\ntemplater = jinja\r\n\r\n[sqlfluff:indentation]\r\ntemplate_blocks_indent = True\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "I think think this is almost certainly about the `do` statement, hopefully this should be very solvable.\nAny pointers on where I should start looking if I would work on a fix @alanmcruickshank?\n@fredriv - great question. I just had a quick look and this is a very strange bug, but hopefully one with a satisfying solution.\r\n\r\nIf I run `sqlfluff parse` on the file I get this:\r\n\r\n```\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% set cols = ['a', 'b'] %}\"]\r\n[L: 1, P: 28] | newline: '\\n'\r\n[L: 2, P: 1] | [META] placeholder: [Type: 'block_start', Raw: \"{% do cols.remove('a') %}\", Block: '230a18']\r\n[L: 2, P: 26] | newline: '\\n'\r\n[L: 3, P: 1] | newline: '\\n'\r\n[L: 4, P: 1] | [META] placeholder: [Type: 'block_start', Raw: '{% if true %}', Block: 'e33036']\r\n[L: 4, P: 14] | newline: '\\n'\r\n[L: 5, P: 1] | whitespace: ' '\r\n[L: 5, P: 5] | statement:\r\n[L: 5, P: 5] | select_statement:\r\n[L: 5, P: 5] | select_clause:\r\n[L: 5, P: 5] | keyword: 'select'\r\n[L: 5, P: 11] | [META] indent:\r\n[L: 5, P: 11] | whitespace: ' '\r\n[L: 5, P: 12] | select_clause_element:\r\n[L: 5, P: 12] | column_reference:\r\n[L: 5, P: 12] | naked_identifier: 'a'\r\n[L: 5, P: 13] | newline: '\\n'\r\n[L: 6, P: 1] | whitespace: ' '\r\n[L: 6, P: 5] | [META] dedent:\r\n[L: 6, P: 5] | from_clause:\r\n[L: 6, P: 5] | keyword: 'from'\r\n[L: 6, P: 9] | whitespace: ' '\r\n[L: 6, P: 10] | from_expression:\r\n[L: 6, P: 10] | [META] indent:\r\n[L: 6, P: 10] | from_expression_element:\r\n[L: 6, P: 10] | table_expression:\r\n[L: 6, P: 10] | table_reference:\r\n[L: 6, P: 10] | naked_identifier: 'some_table'\r\n[L: 6, P: 20] | [META] dedent:\r\n[L: 6, P: 20] | newline: '\\n'\r\n[L: 7, P: 1] | [META] placeholder: [Type: 'block_end', Raw: '{% endif %}', Block: 'e33036']\r\n[L: 7, P: 12] | [META] end_of_file:\r\n```\r\n\r\nNote the difference between that and the output when I remove the `do` line:\r\n\r\n```\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% set cols = ['a', 'b'] %}\"]\r\n[L: 1, P: 28] | newline: '\\n'\r\n[L: 2, P: 1] | newline: '\\n'\r\n[L: 3, P: 1] | newline: '\\n'\r\n[L: 4, P: 1] | [META] placeholder: [Type: 'block_start', Raw: '{% if true %}', Block: '0d1e98']\r\n[L: 4, P: 14] | [META] indent: [Block: '0d1e98']\r\n[L: 4, P: 14] | newline: '\\n'\r\n[L: 5, P: 1] | whitespace: ' '\r\n[L: 5, P: 5] | statement:\r\n[L: 5, P: 5] | select_statement:\r\n[L: 5, P: 5] | select_clause:\r\n[L: 5, P: 5] | keyword: 'select'\r\n[L: 5, P: 11] | [META] indent:\r\n[L: 5, P: 11] | whitespace: ' '\r\n[L: 5, P: 12] | select_clause_element:\r\n[L: 5, P: 12] | column_reference:\r\n[L: 5, P: 12] | naked_identifier: 'a'\r\n[L: 5, P: 13] | newline: '\\n'\r\n[L: 6, P: 1] | whitespace: ' '\r\n[L: 6, P: 5] | [META] dedent:\r\n[L: 6, P: 5] | from_clause:\r\n[L: 6, P: 5] | keyword: 'from'\r\n[L: 6, P: 9] | whitespace: ' '\r\n[L: 6, P: 10] | from_expression:\r\n[L: 6, P: 10] | [META] indent:\r\n[L: 6, P: 10] | from_expression_element:\r\n[L: 6, P: 10] | table_expression:\r\n[L: 6, P: 10] | table_reference:\r\n[L: 6, P: 10] | naked_identifier: 'some_table'\r\n[L: 6, P: 20] | [META] dedent:\r\n[L: 6, P: 20] | newline: '\\n'\r\n[L: 7, P: 1] | [META] dedent: [Block: '0d1e98']\r\n[L: 7, P: 1] | [META] placeholder: [Type: 'block_end', Raw: '{% endif %}', Block: '0d1e98']\r\n[L: 7, P: 12] | [META] end_of_file:\r\n```\r\n\r\nSee that in the latter example there are `indent` and `dedent` tokens around the `if` clause, but not in the first example. Something about the `do` call is disrupting the positioning of those indent tokens. Those tokens are inserted during `._iter_segments()` in `lexer.py`, and more specifically in `._handle_zero_length_slice()`. That's probably where you'll find the issue. My guess is that something about the `do` block is throwing off the block tracking?\nThanks! I'll see if I can have a look at it tonight.\r\n\r\nCould it have something to do with the `do` block not having a corresponding `block_end`? \ud83e\udd14\nSo perhaps it should be `templated` instead of `block_start`, similar to the `set` above it?\nIf I add `do` to the list of tag names in `extract_block_type` at https://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/core/templaters/slicers/tracer.py#L527 it regards it as a `templated` element instead of `block_start`, and the indent is added where I want it.\r\n\r\nE.g.\r\n```\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% set cols = ['a', 'b'] %}\"]\r\n[L: 1, P: 28] | newline: '\\n'\r\n[L: 2, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% do cols.remove('a') %}\"]\r\n[L: 2, P: 26] | newline: '\\n'\r\n[L: 3, P: 1] | newline: '\\n'\r\n[L: 4, P: 1] | [META] placeholder: [Type: 'block_start', Raw: '{% if true %}', Block: '3e39bd']\r\n[L: 4, P: 14] | [META] indent: [Block: '3e39bd']\r\n[L: 4, P: 14] | newline: '\\n'\r\n[L: 5, P: 1] | whitespace: ' '\r\n[L: 5, P: 5] | statement:\r\n[L: 5, P: 5] | select_statement:\r\n[L: 5, P: 5] | select_clause:\r\n[L: 5, P: 5] | keyword: 'select'\r\n[L: 5, P: 11] | [META] indent:\r\n[L: 5, P: 11] | whitespace: ' '\r\n[L: 5, P: 12] | select_clause_element:\r\n[L: 5, P: 12] | column_reference:\r\n[L: 5, P: 12] | naked_identifier: 'a'\r\n[L: 5, P: 13] | newline: '\\n'\r\n[L: 6, P: 1] | whitespace: ' '\r\n[L: 6, P: 5] | [META] dedent:\r\n[L: 6, P: 5] | from_clause:\r\n[L: 6, P: 5] | keyword: 'from'\r\n[L: 6, P: 9] | whitespace: ' '\r\n[L: 6, P: 10] | from_expression:\r\n[L: 6, P: 10] | [META] indent:\r\n[L: 6, P: 10] | from_expression_element:\r\n[L: 6, P: 10] | table_expression:\r\n[L: 6, P: 10] | table_reference:\r\n[L: 6, P: 10] | naked_identifier: 'some_table'\r\n[L: 6, P: 20] | [META] dedent:\r\n[L: 6, P: 20] | newline: '\\n'\r\n[L: 7, P: 1] | [META] dedent: [Block: '3e39bd']\r\n[L: 7, P: 1] | [META] placeholder: [Type: 'block_end', Raw: '{% endif %}', Block: '3e39bd']\r\n[L: 7, P: 12] | newline: '\\n'\r\n[L: 8, P: 1] | [META] end_of_file:\r\n```\nSimilarly if I instead add `do` to the list of trimmed parts in `update_inside_set_call_macro_or_block` at https://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/core/templaters/slicers/tracer.py#L252-L255\r\n\r\nMaybe a better place to put it? What do you think @alanmcruickshank?\n@fredriv - based on the [docs for jinja](https://jinja.palletsprojects.com/en/3.0.x/extensions/#expression-statement) it looks like we should never get a \"do block\" (i.e. `{% do ... %} ... {% enddo %}`, it's only ever just `{% do ... %}`). That means that treating it like a `templated` section is the right route, i.e. we should add it in `extract_block_type` and not in `update_inside_set_call_macro_or_block`.\r\n\r\nThanks for your research - I think this should be a neat solution! \ud83d\ude80 \n\ud83d\udc4d Ok, I can make a PR :)\nI think think this is almost certainly about the `do` statement, hopefully this should be very solvable.\nAny pointers on where I should start looking if I would work on a fix @alanmcruickshank?\n@fredriv - great question. I just had a quick look and this is a very strange bug, but hopefully one with a satisfying solution.\r\n\r\nIf I run `sqlfluff parse` on the file I get this:\r\n\r\n```\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% set cols = ['a', 'b'] %}\"]\r\n[L: 1, P: 28] | newline: '\\n'\r\n[L: 2, P: 1] | [META] placeholder: [Type: 'block_start', Raw: \"{% do cols.remove('a') %}\", Block: '230a18']\r\n[L: 2, P: 26] | newline: '\\n'\r\n[L: 3, P: 1] | newline: '\\n'\r\n[L: 4, P: 1] | [META] placeholder: [Type: 'block_start', Raw: '{% if true %}', Block: 'e33036']\r\n[L: 4, P: 14] | newline: '\\n'\r\n[L: 5, P: 1] | whitespace: ' '\r\n[L: 5, P: 5] | statement:\r\n[L: 5, P: 5] | select_statement:\r\n[L: 5, P: 5] | select_clause:\r\n[L: 5, P: 5] | keyword: 'select'\r\n[L: 5, P: 11] | [META] indent:\r\n[L: 5, P: 11] | whitespace: ' '\r\n[L: 5, P: 12] | select_clause_element:\r\n[L: 5, P: 12] | column_reference:\r\n[L: 5, P: 12] | naked_identifier: 'a'\r\n[L: 5, P: 13] | newline: '\\n'\r\n[L: 6, P: 1] | whitespace: ' '\r\n[L: 6, P: 5] | [META] dedent:\r\n[L: 6, P: 5] | from_clause:\r\n[L: 6, P: 5] | keyword: 'from'\r\n[L: 6, P: 9] | whitespace: ' '\r\n[L: 6, P: 10] | from_expression:\r\n[L: 6, P: 10] | [META] indent:\r\n[L: 6, P: 10] | from_expression_element:\r\n[L: 6, P: 10] | table_expression:\r\n[L: 6, P: 10] | table_reference:\r\n[L: 6, P: 10] | naked_identifier: 'some_table'\r\n[L: 6, P: 20] | [META] dedent:\r\n[L: 6, P: 20] | newline: '\\n'\r\n[L: 7, P: 1] | [META] placeholder: [Type: 'block_end', Raw: '{% endif %}', Block: 'e33036']\r\n[L: 7, P: 12] | [META] end_of_file:\r\n```\r\n\r\nNote the difference between that and the output when I remove the `do` line:\r\n\r\n```\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% set cols = ['a', 'b'] %}\"]\r\n[L: 1, P: 28] | newline: '\\n'\r\n[L: 2, P: 1] | newline: '\\n'\r\n[L: 3, P: 1] | newline: '\\n'\r\n[L: 4, P: 1] | [META] placeholder: [Type: 'block_start', Raw: '{% if true %}', Block: '0d1e98']\r\n[L: 4, P: 14] | [META] indent: [Block: '0d1e98']\r\n[L: 4, P: 14] | newline: '\\n'\r\n[L: 5, P: 1] | whitespace: ' '\r\n[L: 5, P: 5] | statement:\r\n[L: 5, P: 5] | select_statement:\r\n[L: 5, P: 5] | select_clause:\r\n[L: 5, P: 5] | keyword: 'select'\r\n[L: 5, P: 11] | [META] indent:\r\n[L: 5, P: 11] | whitespace: ' '\r\n[L: 5, P: 12] | select_clause_element:\r\n[L: 5, P: 12] | column_reference:\r\n[L: 5, P: 12] | naked_identifier: 'a'\r\n[L: 5, P: 13] | newline: '\\n'\r\n[L: 6, P: 1] | whitespace: ' '\r\n[L: 6, P: 5] | [META] dedent:\r\n[L: 6, P: 5] | from_clause:\r\n[L: 6, P: 5] | keyword: 'from'\r\n[L: 6, P: 9] | whitespace: ' '\r\n[L: 6, P: 10] | from_expression:\r\n[L: 6, P: 10] | [META] indent:\r\n[L: 6, P: 10] | from_expression_element:\r\n[L: 6, P: 10] | table_expression:\r\n[L: 6, P: 10] | table_reference:\r\n[L: 6, P: 10] | naked_identifier: 'some_table'\r\n[L: 6, P: 20] | [META] dedent:\r\n[L: 6, P: 20] | newline: '\\n'\r\n[L: 7, P: 1] | [META] dedent: [Block: '0d1e98']\r\n[L: 7, P: 1] | [META] placeholder: [Type: 'block_end', Raw: '{% endif %}', Block: '0d1e98']\r\n[L: 7, P: 12] | [META] end_of_file:\r\n```\r\n\r\nSee that in the latter example there are `indent` and `dedent` tokens around the `if` clause, but not in the first example. Something about the `do` call is disrupting the positioning of those indent tokens. Those tokens are inserted during `._iter_segments()` in `lexer.py`, and more specifically in `._handle_zero_length_slice()`. That's probably where you'll find the issue. My guess is that something about the `do` block is throwing off the block tracking?\nThanks! I'll see if I can have a look at it tonight.\r\n\r\nCould it have something to do with the `do` block not having a corresponding `block_end`? \ud83e\udd14\nSo perhaps it should be `templated` instead of `block_start`, similar to the `set` above it?\nIf I add `do` to the list of tag names in `extract_block_type` at https://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/core/templaters/slicers/tracer.py#L527 it regards it as a `templated` element instead of `block_start`, and the indent is added where I want it.\r\n\r\nE.g.\r\n```\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% set cols = ['a', 'b'] %}\"]\r\n[L: 1, P: 28] | newline: '\\n'\r\n[L: 2, P: 1] | [META] placeholder: [Type: 'templated', Raw: \"{% do cols.remove('a') %}\"]\r\n[L: 2, P: 26] | newline: '\\n'\r\n[L: 3, P: 1] | newline: '\\n'\r\n[L: 4, P: 1] | [META] placeholder: [Type: 'block_start', Raw: '{% if true %}', Block: '3e39bd']\r\n[L: 4, P: 14] | [META] indent: [Block: '3e39bd']\r\n[L: 4, P: 14] | newline: '\\n'\r\n[L: 5, P: 1] | whitespace: ' '\r\n[L: 5, P: 5] | statement:\r\n[L: 5, P: 5] | select_statement:\r\n[L: 5, P: 5] | select_clause:\r\n[L: 5, P: 5] | keyword: 'select'\r\n[L: 5, P: 11] | [META] indent:\r\n[L: 5, P: 11] | whitespace: ' '\r\n[L: 5, P: 12] | select_clause_element:\r\n[L: 5, P: 12] | column_reference:\r\n[L: 5, P: 12] | naked_identifier: 'a'\r\n[L: 5, P: 13] | newline: '\\n'\r\n[L: 6, P: 1] | whitespace: ' '\r\n[L: 6, P: 5] | [META] dedent:\r\n[L: 6, P: 5] | from_clause:\r\n[L: 6, P: 5] | keyword: 'from'\r\n[L: 6, P: 9] | whitespace: ' '\r\n[L: 6, P: 10] | from_expression:\r\n[L: 6, P: 10] | [META] indent:\r\n[L: 6, P: 10] | from_expression_element:\r\n[L: 6, P: 10] | table_expression:\r\n[L: 6, P: 10] | table_reference:\r\n[L: 6, P: 10] | naked_identifier: 'some_table'\r\n[L: 6, P: 20] | [META] dedent:\r\n[L: 6, P: 20] | newline: '\\n'\r\n[L: 7, P: 1] | [META] dedent: [Block: '3e39bd']\r\n[L: 7, P: 1] | [META] placeholder: [Type: 'block_end', Raw: '{% endif %}', Block: '3e39bd']\r\n[L: 7, P: 12] | newline: '\\n'\r\n[L: 8, P: 1] | [META] end_of_file:\r\n```\nSimilarly if I instead add `do` to the list of trimmed parts in `update_inside_set_call_macro_or_block` at https://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/core/templaters/slicers/tracer.py#L252-L255\r\n\r\nMaybe a better place to put it? What do you think @alanmcruickshank?\n@fredriv - based on the [docs for jinja](https://jinja.palletsprojects.com/en/3.0.x/extensions/#expression-statement) it looks like we should never get a \"do block\" (i.e. `{% do ... %} ... {% enddo %}`, it's only ever just `{% do ... %}`). That means that treating it like a `templated` section is the right route, i.e. we should add it in `extract_block_type` and not in `update_inside_set_call_macro_or_block`.\r\n\r\nThanks for your research - I think this should be a neat solution! \ud83d\ude80 \n\ud83d\udc4d Ok, I can make a PR :)", "created_at": "2023-04-18T04:35:29Z", "version": "1.4", "FAIL_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%"], "PASS_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_and_templated_whitespace]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block_hard]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[set_multiple_variables_and_define_macro]", "test/core/templaters/jinja_test.py::test_templater_set_block_handling", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_dynamic_variable_no_violations", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_config-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_is_incremental-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_ref-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_source-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_this-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_test-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/003-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/004-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/005-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/006-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/007-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/008-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/009-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_o_config_override_dbt_builtins/override_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_p_disable_dbt_builtins/disable_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_q_multiple_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_block_matching", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_large_file_check", "test/core/templaters/jinja_test.py::test_jinja_undefined_callable[-expected_violation0]", "test/core/templaters/jinja_test.py::test_jinja_undefined_callable[templating-None]", "test/core/templaters/jinja_test.py::test_dummy_undefined_fail_with_undefined_error", "test/core/templaters/jinja_test.py::test_undefined_magic_methods"], "environment_setup_commit": "d19de0ecd16d298f9e3bfb91da122734c40c01e5"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2907", "base_commit": "305159ea643baf6b4744b98c3566613754b2f659", "patch": "diff --git a/src/sqlfluff/core/templaters/jinja.py b/src/sqlfluff/core/templaters/jinja.py\n--- a/src/sqlfluff/core/templaters/jinja.py\n+++ b/src/sqlfluff/core/templaters/jinja.py\n@@ -343,20 +343,33 @@ def process(\n # first Exception which serves only to catch catastrophic errors.\n try:\n syntax_tree = env.parse(in_str)\n- undefined_variables = meta.find_undeclared_variables(syntax_tree)\n+ potentially_undefined_variables = meta.find_undeclared_variables(\n+ syntax_tree\n+ )\n except Exception as err: # pragma: no cover\n # TODO: Add a url here so people can get more help.\n raise SQLTemplaterError(f\"Failure in identifying Jinja variables: {err}.\")\n \n- # Get rid of any that *are* actually defined.\n- for val in live_context:\n- if val in undefined_variables:\n- undefined_variables.remove(val)\n+ undefined_variables = set()\n+\n+ class Undefined:\n+ \"\"\"Similar to jinja2.StrictUndefined, but remembers, not fails.\"\"\"\n+\n+ def __init__(self, name):\n+ self.name = name\n+\n+ def __str__(self):\n+ \"\"\"Treat undefined vars as empty, but remember for later.\"\"\"\n+ undefined_variables.add(self.name)\n+ return \"\"\n+\n+ def __getattr__(self, item):\n+ undefined_variables.add(self.name)\n+ return Undefined(f\"{self.name}.{item}\")\n \n- if undefined_variables:\n- # Lets go through and find out where they are:\n- for val in self._crawl_tree(syntax_tree, undefined_variables, in_str):\n- violations.append(val)\n+ for val in potentially_undefined_variables:\n+ if val not in live_context:\n+ live_context[val] = Undefined(name=val)\n \n try:\n # NB: Passing no context. Everything is loaded when the template is loaded.\n@@ -368,6 +381,10 @@ def process(\n config=config,\n make_template=make_template,\n )\n+ if undefined_variables:\n+ # Lets go through and find out where they are:\n+ for val in self._crawl_tree(syntax_tree, undefined_variables, in_str):\n+ violations.append(val)\n return (\n TemplatedFile(\n source_str=in_str,\n", "test_patch": "diff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -411,6 +411,20 @@ def test__templater_jinja_error_variable():\n assert any(v.rule_code() == \"TMP\" and v.line_no == 1 for v in vs)\n \n \n+def test__templater_jinja_dynamic_variable_no_violations():\n+ \"\"\"Test no templater violation for variable defined within template.\"\"\"\n+ t = JinjaTemplater(override_context=dict(blah=\"foo\"))\n+ instr = \"\"\"{% if True %}\n+ {% set some_var %}1{% endset %}\n+ SELECT {{some_var}}\n+{% endif %}\n+\"\"\"\n+ outstr, vs = t.process(in_str=instr, fname=\"test\", config=FluffConfig())\n+ assert str(outstr) == \"\\n \\n SELECT 1\\n\\n\"\n+ # Check we have no violations.\n+ assert len(vs) == 0\n+\n+\n def test__templater_jinja_error_syntax():\n \"\"\"Test syntax problems in the jinja templater.\"\"\"\n t = JinjaTemplater()\n", "problem_statement": "sqlfluff doesn't recognise a jinja variable set inside of \"if\" statement\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nWhen I try to define a jinja variable using \"set\" jinja directive inside of an \"if\" jinja statement, sqlfluff complains: \r\n\"Undefined jinja template variable\".\n\n### Expected Behaviour\n\nto not have a linting issue\n\n### Observed Behaviour\n\nsqlfluff lint gives an error:\r\n\"Undefined jinja template variable\"\n\n### How to reproduce\n\ntry to create a \"temp.sql\" file with the following content\r\n\r\n```\r\n{% if True %}\r\n {% set some_var %}1{% endset %}\r\n SELECT {{some_var}}\r\n{% endif %}\r\n```\r\n\r\nand run:\r\n```\r\nsqlfluff lint ./temp.sql\r\n```\r\n\r\nYou will get the following error:\r\n```\r\n== [./temp.sql] FAIL \r\nL: 2 | P: 12 | TMP | Undefined jinja template variable: 'some_var'\r\nL: 3 | P: 14 | TMP | Undefined jinja template variable: 'some_var'\r\n```\n\n### Dialect\n\ntested on 'snowflake' dialect\n\n### Version\n\nsqlfluff, version 0.11.1\r\nPython 3.8.12\n\n### Configuration\n\n[sqlfluff]\r\nverbose = 1\r\ndialect = snowflake\r\ntemplater = jinja\r\nexclude_rules = L027,L031,L032,L036,L044,L046,L034,L050\r\noutput_line_length = 121\r\nsql_file_exts=.sql\r\n\r\n[sqlfluff:rules]\r\ntab_space_size = 4\r\nmax_line_length = 250\r\nindent_unit = space\r\ncomma_style = trailing\r\nallow_scalar = True\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = aliases\r\n\r\n[sqlfluff:rules:L042]\r\nforbid_subquery_in = both\r\n\r\n[sqlfluff:rules:L010] # Keywords\r\ncapitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L014]\r\nextended_capitalisation_policy = lower\r\n\r\n[sqlfluff:rules:L030] # function names\r\nextended_capitalisation_policy = upper\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "Does Jinja support this? I don't see how this could be a SQLFluff issue.\nYour example does work on this website. I wonder if there's a Jinja runtime setting that affects whether this works.\r\n\r\nhttp://jinja.quantprogramming.com/\nIt also works with `j2cli` on my local machine. Seems like this _has_ to be a Jinja runtime setting...\r\n\r\nhttps://github.com/kolypto/j2cli\nIt was added in Jinja 2.8: https://jinja.palletsprojects.com/en/3.0.x/templates/#block-assignments\r\n\r\nNot sure what version we pull in depending on our other dependencies?\r\n\nI'm digging into this more. SQLFluff contains some additional code that attempts to detect undeclared Jinja variables and provide better error handling. The \"issue\" is being detected and reported by that code, not by Jinja itself. So we should be able to fix this. Need to do this carefully so we don't break error reporting for real errors. \nI think I have a fix. Just need to make the undefined variable check more sophisticated.", "created_at": "2022-03-23T21:32:13Z", "version": "0.10", "FAIL_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja_dynamic_variable_no_violations"], "PASS_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test_templater_set_block_handling", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n"], "environment_setup_commit": "3d52e8270d82aeccf4c516d059a80a6947919aea"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4051", "base_commit": "c3defb095b1aa7fe23c4bd430fdff2ce6ed6161d", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -137,24 +137,14 @@ def red_log_filter(record: logging.LogRecord) -> bool:\n class PathAndUserErrorHandler:\n \"\"\"Make an API call but with error handling for the CLI.\"\"\"\n \n- def __init__(self, formatter, paths):\n+ def __init__(self, formatter):\n self.formatter = formatter\n- self.paths = paths\n \n def __enter__(self):\n return self\n \n def __exit__(self, exc_type, exc_val, exc_tb):\n- if exc_type is OSError:\n- click.echo(\n- self.formatter.colorize(\n- f\"The path(s) { self.paths } could not be \"\n- \"accessed. Check it/they exist(s).\",\n- Color.red,\n- )\n- )\n- sys.exit(EXIT_ERROR)\n- elif exc_type is SQLFluffUserError:\n+ if exc_type is SQLFluffUserError:\n click.echo(\n \"\\nUser Error: \"\n + self.formatter.colorize(\n@@ -584,7 +574,7 @@ def lint(\n if verbose >= 1:\n click.echo(format_linting_result_header())\n \n- with PathAndUserErrorHandler(formatter, paths):\n+ with PathAndUserErrorHandler(formatter):\n # add stdin if specified via lone '-'\n if (\"-\",) == paths:\n result = lnt.lint_string_wrapped(sys.stdin.read(), fname=\"stdin\")\n@@ -833,7 +823,7 @@ def fix(\n # Lint the paths (not with the fix argument at this stage), outputting as we go.\n click.echo(\"==== finding fixable violations ====\")\n \n- with PathAndUserErrorHandler(formatter, paths):\n+ with PathAndUserErrorHandler(formatter):\n result = lnt.lint_paths(\n paths,\n fix=True,\n@@ -1051,7 +1041,7 @@ def parse(\n t0 = time.monotonic()\n \n # handle stdin if specified via lone '-'\n- with PathAndUserErrorHandler(formatter, path):\n+ with PathAndUserErrorHandler(formatter):\n if \"-\" == path:\n parsed_strings = [\n lnt.parse_string(\n@@ -1156,7 +1146,7 @@ def render(\n )\n \n # handle stdin if specified via lone '-'\n- with PathAndUserErrorHandler(formatter, path):\n+ with PathAndUserErrorHandler(formatter):\n if \"-\" == path:\n raw_sql = sys.stdin.read()\n fname = \"stdin\"\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -27,6 +27,7 @@\n SQLLintError,\n SQLParseError,\n SQLFluffSkipFile,\n+ SQLFluffUserError,\n )\n from sqlfluff.core.parser import Lexer, Parser, RegexLexer\n from sqlfluff.core.file_helpers import get_encoding\n@@ -969,7 +970,9 @@ def paths_from_path(\n if ignore_non_existent_files:\n return []\n else:\n- raise OSError(\"Specified path does not exist\")\n+ raise SQLFluffUserError(\n+ f\"Specified path does not exist. Check it/they exist(s): {path}.\"\n+ )\n \n # Files referred to exactly are also ignored if\n # matched, but we warn the users when that happens\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -1203,7 +1203,10 @@ def test__cli__command_lint_serialize_from_stdin(serialize, sql, expected, exit_\n def test__cli__command_fail_nice_not_found(command):\n \"\"\"Check commands fail as expected when then don't find files.\"\"\"\n result = invoke_assert_code(args=command, ret_code=2)\n- assert \"could not be accessed\" in result.output\n+ assert (\n+ \"User Error: Specified path does not exist. Check it/they \"\n+ \"exist(s): this_file_does_not_exist.sql\"\n+ ) in result.output\n \n \n @patch(\"click.utils.should_strip_ansi\")\ndiff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -16,6 +16,7 @@\n SQLBaseError,\n SQLLintError,\n SQLParseError,\n+ SQLFluffUserError,\n )\n from sqlfluff.cli.formatters import OutputStreamFormatter\n from sqlfluff.cli.outputstream import make_output_stream\n@@ -120,9 +121,9 @@ def test__linter__skip_large_bytes(filesize, raises_skip):\n \n \n def test__linter__path_from_paths__not_exist():\n- \"\"\"Test extracting paths from a file path.\"\"\"\n+ \"\"\"Test that the right errors are raise when a file doesn't exist.\"\"\"\n lntr = Linter()\n- with pytest.raises(IOError):\n+ with pytest.raises(SQLFluffUserError):\n lntr.paths_from_path(\"asflekjfhsakuefhse\")\n \n \n", "problem_statement": "Misleading path does not exist message\nIt looks like if _at least one_ of the paths provided to sqlfluff do not exist, it will display an error message implying that _all_ of the supplied paths do not exist:\r\n\r\n```bash\r\ndbt@b54bee9ced88:/workspaces/dbt-dutchie$ sqlfluff fix models/shared/dispensaries.sql models/shares/dispensary_chains.sql\r\n==== finding fixable violations ====\r\n=== [dbt templater] Compiling dbt project...\r\n== [models/shared/dispensaries.sql] FAIL\r\nL: 6 | P: 2 | L003 | Indentation not consistent with line #376\r\nL: 8 | P: 2 | L003 | Indentation not consistent with line #376\r\nL: 9 | P: 3 | L003 | Line over-indented compared to line #376\r\nL: 10 | P: 2 | L003 | Indentation not consistent with line #376\r\nL: 12 | P: 2 | L003 | Indentation not consistent with line #376\r\nL: 13 | P: 3 | L003 | Line over-indented compared to line #376\r\nL: 14 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 15 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 16 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 17 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 18 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 19 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 20 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 21 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 22 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 23 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 24 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 25 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 26 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 27 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 28 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 29 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 30 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 31 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 32 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 33 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 34 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 58 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 35 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 36 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 37 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 38 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 39 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 40 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 41 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 42 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 43 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 44 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 45 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 46 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 47 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 48 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 49 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 50 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 51 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 52 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 53 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 54 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 55 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 56 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 57 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 58 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 59 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 60 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 61 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 62 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 63 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 64 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 65 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 66 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 67 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 68 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 69 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 70 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 71 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 72 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 73 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 74 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 75 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 76 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 77 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 78 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 79 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 80 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 81 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 82 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 83 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 84 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 85 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 86 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 87 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 88 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 89 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 90 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 91 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 92 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 92 | P: 44 | L001 | Unnecessary trailing whitespace.\r\nL: 93 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 94 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 95 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 96 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 97 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 98 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 99 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 100 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 101 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 102 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 103 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 104 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 105 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 106 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 107 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 108 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 109 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 110 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 111 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 112 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 113 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 114 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 115 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 116 | P: 3 | L003 | Line over-indented compared to line #376\r\nL: 235 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 117 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 118 | P: 3 | L003 | Line over-indented compared to line #376\r\nL: 119 | P: 4 | L003 | Line over-indented compared to line #376\r\nL: 120 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 121 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 122 | P: 2 | L003 | Indentation not consistent with line #376\r\nL: 339 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 343 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 347 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 351 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 355 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 358 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 361 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 364 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 367 | P: 1 | L004 | Incorrect indentation type found in file.\r\nL: 370 | P: 1 | L004 | Incorrect indentation type found in file.\r\nThe path(s) ('models/shared/dispensaries.sql', 'models/shares/dispensary_chains.sql') could not be accessed. Check it/they exist(s).\r\n```\r\n\r\n## Expected Behaviour\r\nI would expect only the unaccessible paths to be included in the error message.\r\n\r\n## Observed Behaviour\r\nSee above\r\n\r\n## Version\r\n```bash\r\ndbt@b54bee9ced88:/workspaces/dbt-dutchie$ sqlfluff --version\r\nsqlfluff, version 0.5.2\r\n```\r\n\r\n```bash\r\ndbt@b54bee9ced88:/workspaces/dbt-dutchie$ python --version\r\nPython 3.8.6\r\n```\r\n\r\n## Configuration\r\n```\r\n[sqlfluff]\r\ndialect = snowflake\r\ntemplater = dbt\r\nrules = L001,L002,L003,L004,L005,L006\r\nignore = parsing,templating\r\n\r\n[sqlfluff:rules]\r\nmax_line_length = 120\r\ncomma_style = trailing\r\n\r\n[sqlfluff:rules:L010]\r\ncapitalisation_policy = upper\r\n```\r\n\n", "hints_text": "", "created_at": "2022-11-09T18:11:06Z", "version": "1.3", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/core/linter_test.py::test__linter__path_from_paths__not_exist"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass", "test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__skip_large_bytes[0-False]", "test/core/linter_test.py::test__linter__skip_large_bytes[5-True]", "test/core/linter_test.py::test__linter__skip_large_bytes[2000-False]", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__sqlfluffignore_current_directory", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__get_runner_processes[512-1-1]", "test/core/linter_test.py::test__linter__get_runner_processes[512-0-512]", "test/core/linter_test.py::test__linter__get_runner_processes[512--12-500]", "test/core/linter_test.py::test__linter__get_runner_processes[512-5-5]", "test/core/linter_test.py::test__linter__get_runner_processes[1--1-1]", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_parse_noqa[Inline", "test/core/linter_test.py::test_parse_noqa_no_dups", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[2_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_glob_ignore]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_linter_noqa_template_errors", "test/core/linter_test.py::test_linter_noqa_prs", "test/core/linter_test.py::test_linter_noqa_tmp", "test/core/linter_test.py::test_linter_noqa_disable", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]", "test/core/linter_test.py::test_advanced_api_methods", "test/core/linter_test.py::test_normalise_newlines", "test/core/linter_test.py::test_require_match_parse_grammar"], "environment_setup_commit": "dc59c2a5672aacedaf91f0e6129b467eefad331b"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-905", "base_commit": "62e8dc3a148c40c0c28f62b23e943692a3198846", "patch": "diff --git a/src/sqlfluff/core/rules/std/L036.py b/src/sqlfluff/core/rules/std/L036.py\n--- a/src/sqlfluff/core/rules/std/L036.py\n+++ b/src/sqlfluff/core/rules/std/L036.py\n@@ -90,21 +90,26 @@ def _get_indexes(segment):\n )\n \n def _eval_multiple_select_target_elements(self, select_targets_info, segment):\n- if select_targets_info.first_new_line_idx == -1:\n- # there are multiple select targets but no new lines\n-\n- # Find and delete any whitespace between \"SELECT\" and its targets.\n- ws_to_delete = segment.select_children(\n- start_seg=segment.segments[select_targets_info.select_idx],\n- select_if=lambda s: s.is_type(\"whitespace\"),\n- loop_while=lambda s: s.is_type(\"whitespace\") or s.is_meta,\n+ \"\"\"Multiple select targets. Ensure each is on a separate line.\"\"\"\n+ # Insert newline before every select target.\n+ fixes = []\n+ for i, select_target in enumerate(select_targets_info.select_targets):\n+ base_segment = (\n+ segment if not i else select_targets_info.select_targets[i - 1]\n )\n- fixes = [LintFix(\"delete\", ws) for ws in ws_to_delete]\n- # Insert newline before the first select target.\n- ins = self.make_newline(\n- pos_marker=segment.pos_marker.advance_by(segment.raw)\n- )\n- fixes.append(LintFix(\"create\", select_targets_info.select_targets[0], ins))\n+ if base_segment.pos_marker.line_no == select_target.pos_marker.line_no:\n+ # Find and delete any whitespace before the select target.\n+ ws_to_delete = segment.select_children(\n+ start_seg=segment.segments[select_targets_info.select_idx]\n+ if not i\n+ else select_targets_info.select_targets[i - 1],\n+ select_if=lambda s: s.is_type(\"whitespace\"),\n+ loop_while=lambda s: s.is_type(\"whitespace\", \"comma\") or s.is_meta,\n+ )\n+ fixes += [LintFix(\"delete\", ws) for ws in ws_to_delete]\n+ ins = self.make_newline(pos_marker=select_target.pos_marker)\n+ fixes.append(LintFix(\"create\", select_target, ins))\n+ if fixes:\n return LintResult(anchor=segment, fixes=fixes)\n \n def _eval_single_select_target_element(\n", "test_patch": "diff --git a/test/api/simple_test.py b/test/api/simple_test.py\n--- a/test/api/simple_test.py\n+++ b/test/api/simple_test.py\n@@ -121,7 +121,14 @@ def test__api__fix_string():\n # Check return types.\n assert isinstance(result, str)\n # Check actual result\n- assert result == \"SELECT\\n *, 1, blah AS foo FROM mytable\\n\"\n+ assert (\n+ result\n+ == \"\"\"SELECT\n+ *,\n+ 1,\n+ blah AS foo FROM mytable\n+\"\"\"\n+ )\n \n \n def test__api__fix_string_specific():\ndiff --git a/test/fixtures/rules/std_rule_cases/L036.yml b/test/fixtures/rules/std_rule_cases/L036.yml\n--- a/test/fixtures/rules/std_rule_cases/L036.yml\n+++ b/test/fixtures/rules/std_rule_cases/L036.yml\n@@ -37,7 +37,7 @@ test_multiple_select_targets_all_on_the_same_line:\n fail_str: |\n select a, b, c\n from x\n- fix_str: \"select\\na, b, c\\nfrom x\\n\"\n+ fix_str: \"select\\na,\\nb,\\nc\\nfrom x\\n\"\n \n test_multiple_select_targets_trailing_whitespace_after_select:\n # TRICKY: Use explicit newlines to preserve the trailing space after \"SELECT\".\n@@ -57,3 +57,47 @@ test_comment_between_select_and_single_select_target:\n -- This is the user's ID.\n FROM\n safe_user\n+\n+test_multiple_select_targets_some_newlines_missing_1:\n+ fail_str: |\n+ select\n+ a, b, c,\n+ d, e, f, g,\n+ h\n+ from x\n+ # The spaces before a, d, and h look odd, but these are places where the\n+ # select targets were already on a separate line, and the rule made no\n+ # changes.\n+ fix_str: |\n+ select\n+ a,\n+ b,\n+ c,\n+ d,\n+ e,\n+ f,\n+ g,\n+ h\n+ from x\n+\n+\n+test_multiple_select_targets_some_newlines_missing_2:\n+ fail_str: |\n+ select a, b, c,\n+ d, e, f, g,\n+ h\n+ from x\n+ # The spaces before d, and h look odd, but these are places where the\n+ # select targets were already on a separate line, and the rule made no\n+ # changes.\n+ fix_str: |\n+ select\n+ a,\n+ b,\n+ c,\n+ d,\n+ e,\n+ f,\n+ g,\n+ h\n+ from x\n", "problem_statement": "Enhance rule L036 to put all columns on separate lines if any of them are\nThe current description is ambiguous, but after discussion, we decided to update the rule and keep the description at least _similar_ to what it is currently.. See discussion on #769.\n", "hints_text": "FWIW I'm a +1 for this...", "created_at": "2021-03-28T21:22:12Z", "version": "0.4", "FAIL_TO_PASS": ["test/api/simple_test.py::test__api__fix_string"], "PASS_TO_PASS": ["test/api/simple_test.py::test__api__lint_string_without_violations", "test/api/simple_test.py::test__api__lint_string", "test/api/simple_test.py::test__api__lint_file", "test/api/simple_test.py::test__api__lint_string_specific", "test/api/simple_test.py::test__api__fix_string_specific", "test/api/simple_test.py::test__api__parse_string"], "environment_setup_commit": "cbdcfb09feb4883de91de142956c3be6ac7f827d"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-1625", "base_commit": "14e1a23a3166b9a645a16de96f694c77a5d4abb7", "patch": "diff --git a/src/sqlfluff/rules/L031.py b/src/sqlfluff/rules/L031.py\n--- a/src/sqlfluff/rules/L031.py\n+++ b/src/sqlfluff/rules/L031.py\n@@ -211,7 +211,7 @@ def _lint_aliases_in_join(\n violation_buff.append(\n LintResult(\n anchor=alias_info.alias_identifier_ref,\n- description=\"Avoid using aliases in join condition\",\n+ description=\"Avoid aliases in from clauses and join conditions.\",\n fixes=fixes,\n )\n )\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -49,7 +49,7 @@ def invoke_assert_code(\n expected_output = \"\"\"== [test/fixtures/linter/indentation_error_simple.sql] FAIL\n L: 2 | P: 4 | L003 | Indentation not hanging or a multiple of 4 spaces\n L: 5 | P: 10 | L010 | Keywords must be consistently upper case.\n-L: 5 | P: 13 | L031 | Avoid using aliases in join condition\n+L: 5 | P: 13 | L031 | Avoid aliases in from clauses and join conditions.\n \"\"\"\n \n \n", "problem_statement": "TSQL - L031 incorrectly triggers \"Avoid using aliases in join condition\" when no join present\n## Expected Behaviour\r\n\r\nBoth of these queries should pass, the only difference is the addition of a table alias 'a':\r\n\r\n1/ no alias\r\n\r\n```\r\nSELECT [hello]\r\nFROM\r\n mytable\r\n```\r\n\r\n2/ same query with alias\r\n\r\n```\r\nSELECT a.[hello]\r\nFROM\r\n mytable AS a\r\n```\r\n\r\n## Observed Behaviour\r\n\r\n1/ passes\r\n2/ fails with: L031: Avoid using aliases in join condition.\r\n\r\nBut there is no join condition :-)\r\n\r\n## Steps to Reproduce\r\n\r\nLint queries above\r\n\r\n## Dialect\r\n\r\nTSQL\r\n\r\n## Version\r\n\r\nsqlfluff 0.6.9\r\nPython 3.6.9\r\n\r\n## Configuration\r\n\r\nN/A\n", "hints_text": "Actually, re-reading the docs I think this is the intended behaviour... closing", "created_at": "2021-10-13T11:35:29Z", "version": "0.6", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-65-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]"], "environment_setup_commit": "67023b85c41d23d6c6d69812a41b207c4f8a9331"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2326", "base_commit": "38cff664d9505999fb7473a4a7b29ba36aba7883", "patch": "diff --git a/src/sqlfluff/core/parser/__init__.py b/src/sqlfluff/core/parser/__init__.py\n--- a/src/sqlfluff/core/parser/__init__.py\n+++ b/src/sqlfluff/core/parser/__init__.py\n@@ -23,6 +23,7 @@\n Delimited,\n Bracketed,\n AnyNumberOf,\n+ AnySetOf,\n Ref,\n Anything,\n Nothing,\n@@ -56,6 +57,7 @@\n \"Delimited\",\n \"Bracketed\",\n \"AnyNumberOf\",\n+ \"AnySetOf\",\n \"Ref\",\n \"Anything\",\n \"Nothing\",\ndiff --git a/src/sqlfluff/core/parser/grammar/__init__.py b/src/sqlfluff/core/parser/grammar/__init__.py\n--- a/src/sqlfluff/core/parser/grammar/__init__.py\n+++ b/src/sqlfluff/core/parser/grammar/__init__.py\n@@ -1,7 +1,12 @@\n \"\"\"Definitions of grammars.\"\"\"\n \n from sqlfluff.core.parser.grammar.base import Ref, Anything, Nothing\n-from sqlfluff.core.parser.grammar.anyof import AnyNumberOf, OneOf, OptionallyBracketed\n+from sqlfluff.core.parser.grammar.anyof import (\n+ AnyNumberOf,\n+ AnySetOf,\n+ OneOf,\n+ OptionallyBracketed,\n+)\n from sqlfluff.core.parser.grammar.delimited import Delimited\n from sqlfluff.core.parser.grammar.greedy import GreedyUntil, StartsWith\n from sqlfluff.core.parser.grammar.sequence import Sequence, Bracketed\n@@ -12,6 +17,7 @@\n \"Anything\",\n \"Nothing\",\n \"AnyNumberOf\",\n+ \"AnySetOf\",\n \"OneOf\",\n \"OptionallyBracketed\",\n \"Delimited\",\ndiff --git a/src/sqlfluff/core/parser/grammar/anyof.py b/src/sqlfluff/core/parser/grammar/anyof.py\n--- a/src/sqlfluff/core/parser/grammar/anyof.py\n+++ b/src/sqlfluff/core/parser/grammar/anyof.py\n@@ -22,6 +22,7 @@ class AnyNumberOf(BaseGrammar):\n def __init__(self, *args, **kwargs):\n self.max_times = kwargs.pop(\"max_times\", None)\n self.min_times = kwargs.pop(\"min_times\", 0)\n+ self.max_times_per_element = kwargs.pop(\"max_times_per_element\", None)\n # Any patterns to _prevent_ a match.\n self.exclude = kwargs.pop(\"exclude\", None)\n super().__init__(*args, **kwargs)\n@@ -121,7 +122,7 @@ def _prune_options(\n \n def _match_once(\n self, segments: Tuple[BaseSegment, ...], parse_context: ParseContext\n- ) -> MatchResult:\n+ ) -> Tuple[MatchResult, Optional[\"MatchableType\"]]:\n \"\"\"Match the forward segments against the available elements once.\n \n This serves as the main body of OneOf, but also a building block\n@@ -141,14 +142,14 @@ def _match_once(\n return MatchResult.from_unmatched(segments)\n \n with parse_context.deeper_match() as ctx:\n- match, _ = self._longest_trimmed_match(\n+ match, matched_option = self._longest_trimmed_match(\n segments,\n available_options,\n parse_context=ctx,\n trim_noncode=False,\n )\n \n- return match\n+ return match, matched_option\n \n @match_wrapper()\n @allow_ephemeral\n@@ -171,6 +172,13 @@ def match(\n matched_segments: MatchResult = MatchResult.from_empty()\n unmatched_segments: Tuple[BaseSegment, ...] = segments\n n_matches = 0\n+\n+ # Keep track of the number of times each option has been matched.\n+ available_options, _ = self._prune_options(\n+ segments, parse_context=parse_context\n+ )\n+ available_option_counter = {str(o): 0 for o in available_options}\n+\n while True:\n if self.max_times and n_matches >= self.max_times:\n # We've matched as many times as we can\n@@ -197,7 +205,23 @@ def match(\n else:\n pre_seg = () # empty tuple\n \n- match = self._match_once(unmatched_segments, parse_context=parse_context)\n+ match, matched_option = self._match_once(\n+ unmatched_segments, parse_context=parse_context\n+ )\n+\n+ # Increment counter for matched option.\n+ if matched_option and (str(matched_option) in available_option_counter):\n+ available_option_counter[str(matched_option)] += 1\n+ # Check if we have matched an option too many times.\n+ if (\n+ self.max_times_per_element\n+ and available_option_counter[str(matched_option)]\n+ > self.max_times_per_element\n+ ):\n+ return MatchResult(\n+ matched_segments.matched_segments, unmatched_segments\n+ )\n+\n if match:\n matched_segments += pre_seg + match.matched_segments\n unmatched_segments = match.unmatched_segments\n@@ -240,3 +264,10 @@ def __init__(self, *args, **kwargs):\n args[0] if len(args) == 1 else Sequence(*args),\n **kwargs,\n )\n+\n+\n+class AnySetOf(AnyNumberOf):\n+ \"\"\"Match any number of the elements but each element can only be matched once.\"\"\"\n+\n+ def __init__(self, *args, **kwargs):\n+ super().__init__(*args, max_times_per_element=1, **kwargs)\ndiff --git a/src/sqlfluff/dialects/dialect_ansi.py b/src/sqlfluff/dialects/dialect_ansi.py\n--- a/src/sqlfluff/dialects/dialect_ansi.py\n+++ b/src/sqlfluff/dialects/dialect_ansi.py\n@@ -19,6 +19,7 @@\n from sqlfluff.core.dialects.common import AliasInfo, ColumnAliasInfo\n from sqlfluff.core.parser import (\n AnyNumberOf,\n+ AnySetOf,\n Anything,\n BaseFileSegment,\n BaseSegment,\n@@ -515,7 +516,7 @@\n ),\n optional=True,\n ),\n- AnyNumberOf(\n+ AnySetOf(\n # ON DELETE clause, e.g. ON DELETE NO ACTION\n Sequence(\n \"ON\",\n", "test_patch": "diff --git a/test/core/parser/grammar_test.py b/test/core/parser/grammar_test.py\n--- a/test/core/parser/grammar_test.py\n+++ b/test/core/parser/grammar_test.py\n@@ -12,6 +12,7 @@\n Indent,\n )\n from sqlfluff.core.parser.context import RootParseContext\n+from sqlfluff.core.parser.grammar.anyof import AnySetOf\n from sqlfluff.core.parser.segments import EphemeralSegment, BaseSegment\n from sqlfluff.core.parser.grammar.base import BaseGrammar\n from sqlfluff.core.parser.grammar.noncode import NonCodeMatcher\n@@ -678,3 +679,22 @@ def test__parser__grammar_noncode(seg_list, fresh_ansi_dialect):\n m = NonCodeMatcher().match(seg_list[1:], parse_context=ctx)\n # We should match one and only one segment\n assert len(m) == 1\n+\n+\n+def test__parser__grammar_anysetof(generate_test_segments):\n+ \"\"\"Test the AnySetOf grammar.\"\"\"\n+ token_list = [\"bar\", \" \\t \", \"foo\", \" \\t \", \"bar\"]\n+ seg_list = generate_test_segments(token_list)\n+\n+ bs = StringParser(\"bar\", KeywordSegment)\n+ fs = StringParser(\"foo\", KeywordSegment)\n+ g = AnySetOf(fs, bs)\n+ with RootParseContext(dialect=None) as ctx:\n+ # Check directly\n+ assert g.match(seg_list, parse_context=ctx).matched_segments == (\n+ KeywordSegment(\"bar\", seg_list[0].pos_marker),\n+ WhitespaceSegment(\" \\t \", seg_list[1].pos_marker),\n+ KeywordSegment(\"foo\", seg_list[2].pos_marker),\n+ )\n+ # Check with a bit of whitespace\n+ assert not g.match(seg_list[1:], parse_context=ctx)\n", "problem_statement": "`AnySetOf` grammar\n<!--Note: This is for general enhancements to the project. Please use the Bug report template instead to raise parsing/linting/syntax issues for existing supported dialects-->\r\nI know this has been talked about before in PRs so making an issue to formally track.\r\n\r\nIn many grammars there's a common situation where we have to denote several options that can be specified in any order but they cannot be specified more than once.\r\n\r\nOur general approach to this in the project has been denote this using `AnyNumberOf` as this allows for the different orderings:\r\n```python\r\nAnyNumberOf(\r\n <option_1_grammar>,\r\n <option_2_grammar>,\r\n ...\r\n)\r\n```\r\nHowever, the issue with this is that it places no limit on how many times each option can be specified.\r\n\r\nThis means that sqlfluff allows certain invalid statements to parse e.g.\r\n```sql\r\nCREATE TABLE ktw_account_binding (\r\n ktw_id VARCHAR(32) NOT NULL REFERENCES ref_table(bla)\r\n ON DELETE RESTRICT ON DELETE CASCADE ON DELETE CASCADE ON DELETE CASCADE\r\n);\r\n```\r\nhttps://github.com/sqlfluff/sqlfluff/pull/2315#issuecomment-1013847846\r\n\r\nWe've accepted this limitation for the time being as it's more important to get the statements parsing for linting/formatting purposes rather than exactly reflecting the grammar (we'd expect a general degree of common sense when it comes to repeating these options).\r\n\r\nThat being said it would be nice to address this to refine our grammar and reduce dealing with contributor confusion.\r\n\r\n`AnySetOf` would essentially allow all of it's grammar arguments to be parsed in any order a maximum of 1 time each. Hopefully we can inherit from `AnyNumberOf` to simplify this.\n", "hints_text": "", "created_at": "2022-01-16T22:52:45Z", "version": "0.8", "FAIL_TO_PASS": ["test/core/parser/grammar_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice0-matcher_keywords0-False-result_slice0]", "test/core/parser/grammar_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice1-matcher_keywords1-True-result_slice1]", "test/core/parser/grammar_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice2-matcher_keywords2-False-None]", "test/core/parser/grammar_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice3-matcher_keywords3-True-result_slice3]", "test/core/parser/grammar_test.py::test__parser__grammar__base__longest_trimmed_match__adv", "test/core/parser/grammar_test.py::test__parser__grammar__base__look_ahead_match[seg_list_slice0-matcher_keywords0-result_slice0-bar-None]", "test/core/parser/grammar_test.py::test__parser__grammar__base__look_ahead_match[seg_list_slice1-matcher_keywords1-result_slice1-foo-pre_match_slice1]", "test/core/parser/grammar_test.py::test__parser__grammar__base__ephemeral_segment", "test/core/parser/grammar_test.py::test__parser__grammar__oneof__ephemeral_segment", "test/core/parser/grammar_test.py::test__parser__grammar__base__bracket_sensitive_look_ahead_match", "test/core/parser/grammar_test.py::test__parser__grammar__base__bracket_fail_with_open_paren_close_square_mismatch", "test/core/parser/grammar_test.py::test__parser__grammar__base__bracket_fail_with_unexpected_end_bracket", "test/core/parser/grammar_test.py::test__parser__grammar__ref_eq", "test/core/parser/grammar_test.py::test__parser__grammar__oneof__copy", "test/core/parser/grammar_test.py::test__parser__grammar_oneof[True]", "test/core/parser/grammar_test.py::test__parser__grammar_oneof[False]", "test/core/parser/grammar_test.py::test__parser__grammar_oneof_templated", "test/core/parser/grammar_test.py::test__parser__grammar_oneof_exclude", "test/core/parser/grammar_test.py::test__parser__grammar_oneof_take_longest_match", "test/core/parser/grammar_test.py::test__parser__grammar_oneof_take_first", "test/core/parser/grammar_test.py::test__parser__grammar_startswith_a[baar-False]", "test/core/parser/grammar_test.py::test__parser__grammar_startswith_a[bar-True]", "test/core/parser/grammar_test.py::test__parser__grammar_startswith_b[False-3]", "test/core/parser/grammar_test.py::test__parser__grammar_startswith_b[True-4]", "test/core/parser/grammar_test.py::test__parser__grammar_sequence", "test/core/parser/grammar_test.py::test__parser__grammar_sequence_nested", "test/core/parser/grammar_test.py::test__parser__grammar_sequence_indent", "test/core/parser/grammar_test.py::test__parser__grammar_sequence_indent_conditional", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list0-None-True-False-5]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list1-None-True-False-6]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list2-None-True-False-0]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list3-None-True-True-3]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list4-0-True-False-5]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list5-0-False-False-1]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list6-1-True-False-5]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list7-1-False-False-0]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list8-None-True-False-3]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list9-None-False-False-3]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list10-1-True-False-3]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list11-1-False-False-3]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list12-1-False-False-3]", "test/core/parser/grammar_test.py::test__parser__grammar_delimited[token_list13-2-True-False-0]", "test/core/parser/grammar_test.py::test__parser__grammar_greedyuntil[foo-False-1]", "test/core/parser/grammar_test.py::test__parser__grammar_greedyuntil[bar-False-0]", "test/core/parser/grammar_test.py::test__parser__grammar_greedyuntil[baar-False-3]", "test/core/parser/grammar_test.py::test__parser__grammar_greedyuntil[baar-True-6]", "test/core/parser/grammar_test.py::test__parser__grammar_greedyuntil_bracketed", "test/core/parser/grammar_test.py::test__parser__grammar_anything", "test/core/parser/grammar_test.py::test__parser__grammar_nothing", "test/core/parser/grammar_test.py::test__parser__grammar_noncode", "test/core/parser/grammar_test.py::test__parser__grammar_anysetof"], "PASS_TO_PASS": [], "environment_setup_commit": "a5c4eae4e3e419fe95460c9afd9cf39a35a470c4"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3220", "base_commit": "262010b91cf5616de242dad504c788e9cd33ac58", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -674,6 +674,7 @@ def do_fixes(lnt, result, formatter=None, **kwargs):\n @click.option(\n \"--FIX-EVEN-UNPARSABLE\",\n is_flag=True,\n+ default=None,\n help=(\n \"Enables fixing of files that have templating or parse errors. \"\n \"Note that the similar-sounding '--ignore' or 'noqa' features merely \"\n@@ -750,7 +751,7 @@ def fix(\n )\n click.echo(\n colorize(\n- \"Use --fix-even-unparsable' to attempt to fix the SQL anyway.\",\n+ \"Use --FIX-EVEN-UNPARSABLE' to attempt to fix the SQL anyway.\",\n Color.red,\n ),\n err=True,\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -687,6 +687,70 @@ def test__cli__fix_error_handling_behavior(sql, fix_args, fixed, exit_code, tmpd\n assert not fixed_path.is_file()\n \n \[email protected](\n+ \"method,fix_even_unparsable\",\n+ [\n+ (\"command-line\", False),\n+ (\"command-line\", True),\n+ (\"config-file\", False),\n+ (\"config-file\", True),\n+ ],\n+)\n+def test_cli_fix_even_unparsable(\n+ method: str, fix_even_unparsable: bool, monkeypatch, tmpdir\n+):\n+ \"\"\"Test the fix_even_unparsable option works from cmd line and config.\"\"\"\n+ sql_filename = \"fix_even_unparsable.sql\"\n+ sql_path = str(tmpdir / sql_filename)\n+ with open(sql_path, \"w\") as f:\n+ print(\n+ \"\"\"SELECT my_col\n+FROM my_schema.my_table\n+where processdate ! 3\n+\"\"\",\n+ file=f,\n+ )\n+ options = [\n+ \"--dialect\",\n+ \"ansi\",\n+ \"-f\",\n+ \"--fixed-suffix=FIXED\",\n+ sql_path,\n+ ]\n+ if method == \"command-line\":\n+ if fix_even_unparsable:\n+ options.append(\"--FIX-EVEN-UNPARSABLE\")\n+ else:\n+ assert method == \"config-file\"\n+ with open(str(tmpdir / \".sqlfluff\"), \"w\") as f:\n+ print(f\"[sqlfluff]\\nfix_even_unparsable = {fix_even_unparsable}\", file=f)\n+ # TRICKY: Switch current directory to the one with the SQL file. Otherwise,\n+ # the setting doesn't work. That's because SQLFluff reads it in\n+ # sqlfluff.cli.commands.fix(), prior to reading any file-specific settings\n+ # (down in sqlfluff.core.linter.Linter._load_raw_file_and_config()).\n+ monkeypatch.chdir(str(tmpdir))\n+ invoke_assert_code(\n+ ret_code=0 if fix_even_unparsable else 1,\n+ args=[\n+ fix,\n+ options,\n+ ],\n+ )\n+ fixed_path = str(tmpdir / \"fix_even_unparsableFIXED.sql\")\n+ if fix_even_unparsable:\n+ with open(fixed_path, \"r\") as f:\n+ fixed_sql = f.read()\n+ assert (\n+ fixed_sql\n+ == \"\"\"SELECT my_col\n+FROM my_schema.my_table\n+WHERE processdate ! 3\n+\"\"\"\n+ )\n+ else:\n+ assert not os.path.isfile(fixed_path)\n+\n+\n _old_eval = BaseRule._eval\n _fix_counter = 0\n \n", "problem_statement": "Config for fix_even_unparsable not being applied\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nWhen setting the any config file to `fix_even_unparsable = True` the config get's overriden by the default (or lack thereof) on the @click.option decorator for the fix command.\r\n\r\n### Expected Behaviour\r\n\r\nWhen setting the config `fix_even_unparsable` it should be captured by the fix command as well.\r\n\r\n### Observed Behaviour\r\n\r\nThe `fix_even_unparsable` command is not being captured by the fix command\r\n\r\n### How to reproduce\r\n\r\nCreate a config file and include `fix_even_unparsable`\r\nRun `sqlfluff fix`\r\nNote that `fix_even_unparsable` is set to False at runtime\r\n\r\n### Dialect\r\n\r\nAny\r\n\r\n### Version\r\n\r\n0.13.0\r\n\r\n### Configuration\r\n\r\n`pyproject.toml`\r\n\r\n```\r\n[tool.sqlfluff.core]\r\nverbose = 2\r\ndialect = \"snowflake\"\r\nfix_even_unparsable = true\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "I believe the fix would be to just add a `default=None,` to the @click.option decorator.\r\nThis is simple enough for me to create a PR but I don't know how to create tests (or if just adding it is enough) for it as required on the PR template.\n> I believe the fix would be to just add a `default=None,` to the @click.option decorator.\r\nConfirmed that worked\r\n\r\n> This is simple enough for me to create a PR but I don't know how to create tests (or if just adding it is enough) for it as required on the PR template.\r\n\r\nIt would be good to have a test. If you look at `test/fixtures/linter/autofix/snowflake/001_semi_structured` you can see a similar test that uses a .sqlfluff config file for the test run.\nI'm happy to take this unless you want to do it, @pekapa. I fixed a very similar issue with the `--encoding` option a few weeks ago.", "created_at": "2022-04-28T19:13:54Z", "version": "0.12", "FAIL_TO_PASS": ["test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-65-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files"], "environment_setup_commit": "8f6fd1d8a8d69b2c463fbcf5bd1131c47f12ad88"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2419", "base_commit": "f1dba0e1dd764ae72d67c3d5e1471cf14d3db030", "patch": "diff --git a/src/sqlfluff/rules/L060.py b/src/sqlfluff/rules/L060.py\n--- a/src/sqlfluff/rules/L060.py\n+++ b/src/sqlfluff/rules/L060.py\n@@ -59,4 +59,8 @@ def _eval(self, context: RuleContext) -> Optional[LintResult]:\n ],\n )\n \n- return LintResult(context.segment, [fix])\n+ return LintResult(\n+ anchor=context.segment,\n+ fixes=[fix],\n+ description=f\"Use 'COALESCE' instead of '{context.segment.raw_upper}'.\",\n+ )\n", "test_patch": "diff --git a/test/rules/std_L060_test.py b/test/rules/std_L060_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/rules/std_L060_test.py\n@@ -0,0 +1,12 @@\n+\"\"\"Tests the python routines within L060.\"\"\"\n+import sqlfluff\n+\n+\n+def test__rules__std_L060_raised() -> None:\n+ \"\"\"L060 is raised for use of ``IFNULL`` or ``NVL``.\"\"\"\n+ sql = \"SELECT\\n\\tIFNULL(NULL, 100),\\n\\tNVL(NULL,100);\"\n+ result = sqlfluff.lint(sql, rules=[\"L060\"])\n+\n+ assert len(result) == 2\n+ assert result[0][\"description\"] == \"Use 'COALESCE' instead of 'IFNULL'.\"\n+ assert result[1][\"description\"] == \"Use 'COALESCE' instead of 'NVL'.\"\n", "problem_statement": "Rule L060 could give a specific error message\nAt the moment rule L060 flags something like this:\r\n\r\n```\r\nL: 21 | P: 9 | L060 | Use 'COALESCE' instead of 'IFNULL' or 'NVL'.\r\n```\r\n\r\nSince we likely know the wrong word, it might be nice to actually flag that instead of both `IFNULL` and `NVL` - like most of the other rules do.\r\n\r\nThat is it should flag this:\r\n\r\n```\r\nL: 21 | P: 9 | L060 | Use 'COALESCE' instead of 'IFNULL'.\r\n```\r\n Or this:\r\n\r\n```\r\nL: 21 | P: 9 | L060 | Use 'COALESCE' instead of 'NVL'.\r\n```\r\n\r\nAs appropriate.\r\n\r\nWhat do you think @jpy-git ?\r\n\n", "hints_text": "@tunetheweb Yeah definitely, should be a pretty quick change \ud83d\ude0a", "created_at": "2022-01-22T12:21:52Z", "version": "0.8", "FAIL_TO_PASS": ["test/rules/std_L060_test.py::test__rules__std_L060_raised"], "PASS_TO_PASS": [], "environment_setup_commit": "a5c4eae4e3e419fe95460c9afd9cf39a35a470c4"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3170", "base_commit": "6c026c76aa8b13eae54cd7e18d62b0a57fc71dce", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -247,7 +247,7 @@ def core_options(f: Callable) -> Callable:\n )(f)\n f = click.option(\n \"--encoding\",\n- default=\"autodetect\",\n+ default=None,\n help=(\n \"Specify encoding to use when reading and writing files. Defaults to \"\n \"autodetect.\"\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -1256,44 +1256,40 @@ def test_encoding(encoding_in, encoding_out):\n )\n \n \n-def test_cli_pass_on_correct_encoding_argument():\[email protected](\n+ \"encoding,method,expect_success\",\n+ [\n+ (\"utf-8\", \"command-line\", False),\n+ (\"utf-8-SIG\", \"command-line\", True),\n+ (\"utf-8\", \"config-file\", False),\n+ (\"utf-8-SIG\", \"config-file\", True),\n+ ],\n+)\n+def test_cli_encoding(encoding, method, expect_success, tmpdir):\n \"\"\"Try loading a utf-8-SIG encoded file using the correct encoding via the cli.\"\"\"\n+ sql_path = \"test/fixtures/cli/encoding_test.sql\"\n+ if method == \"command-line\":\n+ options = [sql_path, \"--encoding\", encoding]\n+ else:\n+ assert method == \"config-file\"\n+ with open(str(tmpdir / \".sqlfluff\"), \"w\") as f:\n+ print(f\"[sqlfluff]\\ndialect=ansi\\nencoding = {encoding}\", file=f)\n+ shutil.copy(sql_path, tmpdir)\n+ options = [str(tmpdir / \"encoding_test.sql\")]\n result = invoke_assert_code(\n ret_code=65,\n args=[\n lint,\n- [\n- \"test/fixtures/cli/encoding_test.sql\",\n- \"--encoding\",\n- \"utf-8-SIG\",\n- ],\n- ],\n- )\n- raw_output = repr(result.output)\n-\n- # Incorrect encoding raises paring and lexer errors.\n- assert r\"L: 1 | P: 1 | LXR |\" not in raw_output\n- assert r\"L: 1 | P: 1 | PRS |\" not in raw_output\n-\n-\n-def test_cli_fail_on_wrong_encoding_argument():\n- \"\"\"Try loading a utf-8-SIG encoded file using the wrong encoding via the cli.\"\"\"\n- result = invoke_assert_code(\n- ret_code=65,\n- args=[\n- lint,\n- [\n- \"test/fixtures/cli/encoding_test.sql\",\n- \"--encoding\",\n- \"utf-8\",\n- ],\n+ options,\n ],\n )\n raw_output = repr(result.output)\n \n- # Incorrect encoding raises paring and lexer errors.\n- assert r\"L: 1 | P: 1 | LXR |\" in raw_output\n- assert r\"L: 1 | P: 1 | PRS |\" in raw_output\n+ # Incorrect encoding raises parsing and lexer errors.\n+ success1 = r\"L: 1 | P: 1 | LXR |\" not in raw_output\n+ success2 = r\"L: 1 | P: 1 | PRS |\" not in raw_output\n+ assert success1 == expect_success\n+ assert success2 == expect_success\n \n \n def test_cli_no_disable_noqa_flag():\n", "problem_statement": "Commented dash character converted to non utf-8 character\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nUpon fixing a query containing a multi-line comment, SQLFluff attempts to fix a commented line.\r\n\r\nThis:\r\n```sql\r\n/*\r\nTODO\r\n - tariff scenario \u2014> dm_tariff_scenario\r\n*/\r\n```\r\n\r\nBecame:\r\n```sql\r\n/*\r\nTODO\r\n - tariff scenario \u0097> dm_tariff_scenario\r\n*/\r\n``` \r\nThis in an invisible char represented as `<97>`\r\n\r\nThis causes an issue with dbt which can not compile with this char present\r\n\r\nNote this comment comes at the end of the file.\r\n\r\n### Expected Behaviour\r\n\r\nDoes not replace/fix anything that is commented\r\n\r\n### Observed Behaviour\r\n\r\n```bash\r\n $ sqlfluff fix dbt/models/marts/core/f_utility_statements.sql \r\n==== finding fixable violations ==== \r\n=== [dbt templater] Sorting Nodes... \r\n=== [dbt templater] Compiling dbt project... \r\n=== [dbt templater] Project Compiled. \r\n== [dbt/models/marts/core/f_utility_statements.sql] FAIL \r\nL: 1 | P: 5 | L001 | Unnecessary trailing whitespace. \r\nL: 2 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01] \r\nL: 3 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01] \r\nL: 4 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01] \r\nL: 4 | P: 6 | L019 | Found trailing comma. Expected only leading. \r\nL: 6 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01] \r\nL: 7 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01] \r\nL: 8 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01] \r\nL: 8 | P: 6 | L019 | Found trailing comma. Expected only leading. \r\nL: 10 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01] \r\nL: 11 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01] \r\nL: 12 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01] \r\nL: 12 | P: 6 | L019 | Found trailing comma. Expected only leading. \r\nL: 15 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01] \r\nL: 16 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01] [0/47960]\r\nL: 17 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 18 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 19 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 20 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 20 | P: 36 | L031 | Avoid aliases in from clauses and join conditions.\r\nL: 21 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 21 | P: 32 | L031 | Avoid aliases in from clauses and join conditions.\r\nL: 22 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01]\r\nL: 22 | P: 6 | L019 | Found trailing comma. Expected only leading.\r\nL: 24 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01]\r\nL: 26 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 26 | P: 15 | L001 | Unnecessary trailing whitespace.\r\nL: 27 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 28 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 29 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 30 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 31 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 32 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 32 | P: 24 | L011 | Implicit/explicit aliasing of table.\r\nL: 32 | P: 24 | L031 | Avoid aliases in from clauses and join conditions.\r\nL: 33 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 33 | P: 49 | L011 | Implicit/explicit aliasing of table.\r\nL: 33 | P: 49 | L031 | Avoid aliases in from clauses and join conditions.\r\nL: 33 | P: 52 | L001 | Unnecessary trailing whitespace.\r\nL: 34 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 36 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 37 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01]\r\nL: 37 | P: 6 | L019 | Found trailing comma. Expected only leading.\r\nL: 39 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01]\r\nL: 41 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 41 | P: 9 | L034 | Select wildcards then simple targets before calculations\r\n | and aggregates.\r\nL: 43 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 46 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 47 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 48 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 51 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 52 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 53 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 54 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 57 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 58 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 61 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 62 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 64 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 65 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 68 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 69 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 70 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 71 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 73 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 73 | P: 36 | L031 | Avoid aliases in from clauses and join conditions.\r\nL: 74 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 74 | P: 56 | L031 | Avoid aliases in from clauses and join conditions.\r\nL: 75 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 76 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 76 | P: 28 | L001 | Unnecessary trailing whitespace.\r\nL: 77 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 80 | P: 9 | L003 | Expected 0 indentations, found 2 [compared to line 01]\r\nL: 81 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 83 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 84 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01]\r\nL: 94 | P: 1 | L009 | Files must end with a single trailing newline.\r\n```\r\n\r\n### How to reproduce\r\n\r\n`sqlfluff fix` with provided `.sqlfluff` configuration\r\n\r\nSQL contains proprietary code and I am, likely, unable to provide a full snippet of the SQL \r\n\r\n### Dialect\r\n\r\nSnowflake\r\n\r\n### Version\r\n\r\n0.13.0 and 0.11.1\r\n\r\n### Configuration\r\n\r\n`.sqlfluff`:\r\n```\r\n[sqlfluff]\r\ntemplater = dbt\r\ndialect = snowflake\r\n\r\n[sqlfluff:templater:dbt]\r\nproject_dir = dbt/\r\n\r\n# Defaults on anything not specified explicitly: https://docs.sqlfluff.com/en/stable/configuration.html#default-configuration\r\n[sqlfluff:rules]\r\nmax_line_length = 120\r\ncomma_style = leading\r\n\r\n# Keyword capitalisation\r\n[sqlfluff:rules:L010]\r\ncapitalisation_policy = lower\r\n\r\n# TODO: this supports pascal but not snake\r\n# TODO: this inherits throwing violation on all unquoted identifiers... we can limit to aliases or column aliases\r\n# [sqlfluff:rules:L014]\r\n# extended_capitalisation_policy = pascal\r\n\r\n# TODO: not 100% certain that this default is correct\r\n# [sqlfluff:rules:L029]\r\n## Keywords should not be used as identifiers.\r\n# unquoted_identifiers_policy = aliases\r\n# quoted_identifiers_policy = none\r\n## Comma separated list of words to ignore for this rule\r\n# ignore_words = None\r\n\r\n# Function name capitalisation\r\n[sqlfluff:rules:L030]\r\nextended_capitalisation_policy = lower\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "I can't reproduce this, but this usually happens when the file itself is in some other format, rather than UTF-8, to begin with. Can you confirm it's definitely UTF-8 encoded? some tips here on how to check this: https://stackoverflow.com/questions/6947749/how-to-check-if-a-txt-file-is-in-ascii-or-utf-8-format-in-windows-environment\nYou'll probably need to explicitly set the encoding. SQLFluff defaults to using `autodetect`, which is implemented by the third-party `chardet` package, but it's not guaranteed to always do the right thing. If it misbehaves, we (SQLFluff) can't do anything about it.\r\n\r\n```\r\n# can either be autodetect or a valid encoding e.g. utf-8, utf-8-sig\r\nencoding = autodetect\r\n```\r\n\r\nWe'd like to hear back from you, but this issue is likely to be closed as \"won't fix\"/\"can't fix\"\nI have confirmed that the file is indeed utf-8 encoded and I have explicitly set the encoding to utf-8 and retested with the same result.\r\n\r\nAfter running `sqlfluff fix` I have seen the encoding change from utf-8 to western (Windows 1252)\r\n\r\nEDIT: If i manually force the file to be utf-8 AFTER `sqlfluff fix`, it resolves the issue. Good to know, but not a sustainable solution\nDid you set the encoding property in `.sqlfluff`? It does not appear in the `.sqlfluff` file you provided above.\r\n\r\nAlso, please provide a test SQL file. You only provided a comment, not a complete file. When I run `sqlfluff fix` on the file, I get:\r\n```\r\n(sqlfluff-3.9.1) \u279c sqlfluff git:(main) \u2717 sqlfluff fix test.sql\r\n==== finding fixable violations ====\r\n==== no fixable linting violations found ====\r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n```\nI did. The config file I provided does not contain it but I retested using your suggestion and had the same result\nI tried the above on my Mac. The resulting file looked okay to me:\r\n```\r\n - tariff scenario \u2014> dm_tariff_scenario\r\n```\r\n\r\nWhat operating system are using? Windows? Mac? Linux?\nI am on an intel mac with Montery 12.3.1\r\n\r\nAre you able to run sqlfluff fix twice in succession? The first run is fine, its the second run that fails\r\n\r\n(Depending on my editor, it may or may not show the offending character. ie vim shows it, sublime does not)\r\n\nYes, I can run it twice in succession. The first time, it fixes a bunch of things. The second time, no issues found. Partial output below.\r\n```\r\nL: 83 | P: 13 | L003 | Expected 0 indentations, found 3 [compared to line 01]\r\nL: 84 | P: 5 | L003 | Expected 0 indentations, found 1 [compared to line 01]\r\n==== fixing violations ====\r\n72 fixable linting violations found\r\nAre you sure you wish to attempt to fix these? [Y/n] ...\r\nAttempting fixes...\r\nPersisting Changes...\r\n== [test.sql] PASS\r\nDone. Please check your files to confirm.\r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n [3 unfixable linting violations found]\r\n(sqlfluff-3.9.1) \u279c sqlfluff git:(main) \u2717 sqlfluff fix test.sql\r\n==== finding fixable violations ====\r\n==== no fixable linting violations found ====\r\nAll Finished \ud83d\udcdc \ud83c\udf89!\r\n [2 unfixable linting violations found]\r\n```\r\n\r\nI'm on an M1 Mac with Big Sur (11.5.2).\r\n\r\nVery strange behavior:\r\n* That I can't reproduce it on a similar machine\r\n* That setting `encoding = utf-8` in `.sqlfluff` doesn't fix it.\r\n\r\nNote that AFAIK, \"encoding\" is not a real property of most files file. It's a guess made when reading the file. Some file formats let you specify the encoding, but SQL is not one of them. Hence the need to use a package like `chardet`.\r\n\r\nE.g. Python lets you do it with a special comment: https://stackoverflow.com/questions/6289474/working-with-utf-8-encoding-in-python-source\nI just noticed interesting behavior. I ran with `-vv` to ensure my config and although I am specifying `encoding = utf-8`, the -vv output seems to suggest `autodetect`. It is honoring other config (like `dbt`). Attempting to see where I have gone wrong on my side\r\n\r\nEDIT: for context on directory structure: \r\n```\r\n.sqlfluff\r\n./dbt/models/marts/core/file.sql\r\n```\r\nI am running sqlfluff from the same directory as the `.sqlfluff` file ie `sqlfluff fix dbt/models/marts/core/file.sql`\nI've heard the behavior can become tricky if you have multiple .sqlfluff files in subdirectories, etc. Are you certain you added the setting in the correct section of the file? If you put it in the wrong place, it'll be ignored, and it'll use the default setting instead, which is autodetect.\nit is at the top level \r\n```\r\n[sqlfluff]\r\ntemplater = dbt\r\ndialect = snowflake\r\nencoding = utf-8\r\n\r\n...\r\n```\r\nas per your default configuration docs. There are no .sqlfluff files in sub folders in that directory\n@barrywhart Okay... so if I specify `--encoding utf-8` as a CLI command I am able to fix the file with no issue!! Thank you for helping with that!\r\n\r\nI am unsure why it is not honoring that config however. Is there a way you would recommend debugging this issue from my side? We use this both as a CLI tool and as a pre-commit - so we are able to use the `--encoding` option explicitly, but it provides peace of mind to know why it _seems_ to not honor specific configs\r\n\r\nI have changed other configs (ie adding an `excluded_rule`) and it IS honoring that (with no other changes to how i am running it)\r\n\r\nAlso super appreciate all the help :) \nLet me look into it later (probably in the next day or two). Not many people use this option, so I'd like to double check that it's being read correctly from config.\nawesome! I appreciate it @barrywhart (and @tunetheweb )!\r\n\r\nWe, as an organization, are investing in SQLFluff as our production linter and we appreciate your support!\nThanks for the kind words. It's exciting to us seeing the project catching on. I've been involved with the project since late 2019, and I'm proud of the progress it's made. It seems to be becoming pretty mainstream now. One reason I've stayed involved is, how often do you get to help invent a fundamental new industry tool? \ud83d\ude0a\r\n\r\nBTW, feel free to delete your example SQL from the issue. It seems like we may not need it anymore?\nExactly! I have been loosely following this project for the past year and have been pushing to use it widely for a while! We adopted DBT and, since SQLFluff interacts well with DBT, we got the buy-in to invest :)\r\n\r\nAnd yes I will delete the SQL!\r\n\r\nPlease let me know what you find relating to the encoding configuration! I am continuing to fiddle from my side!\nI'm seeing the same issue -- seems that the `encoding` setting in `.sqlfluff` is not being read correctly:\r\n```\r\n[sqlfluff]\r\nencoding = utf-8\r\n```\r\n\r\nWe have automated tests for encoding, but they are lower-level tests (i.e. they exercise internal code directly, not reading encoding from `.sqlfluff`).\r\n\r\nI'll take a closer look. Presumably, this should be easy to fix.", "created_at": "2022-04-24T21:45:11Z", "version": "0.12", "FAIL_TO_PASS": ["test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-65-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files"], "environment_setup_commit": "8f6fd1d8a8d69b2c463fbcf5bd1131c47f12ad88"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2846", "base_commit": "f37dc1410cefc4e08ed8110f820c9071bc4b0c7d", "patch": "diff --git a/src/sqlfluff/core/templaters/slicers/tracer.py b/src/sqlfluff/core/templaters/slicers/tracer.py\n--- a/src/sqlfluff/core/templaters/slicers/tracer.py\n+++ b/src/sqlfluff/core/templaters/slicers/tracer.py\n@@ -185,6 +185,23 @@ def next_slice_id(self) -> str:\n self.slice_id += 1\n return result\n \n+ def slice_info_for_literal(self, length, prefix=\"\") -> RawSliceInfo:\n+ \"\"\"Returns a RawSliceInfo for a literal.\n+\n+ In the alternate template, literals are replaced with a uniquely\n+ numbered, easily-to-parse literal. JinjaTracer uses this output as\n+ a \"breadcrumb trail\" to deduce the execution path through the template.\n+\n+ This is important even if the original literal (i.e. in the raw SQL\n+ file) was empty, as is the case when Jinja whitespace control is used\n+ (e.g. \"{%- endif -%}\"), because fewer breadcrumbs means JinjaTracer has\n+ to *guess* the path, in which case it assumes simple, straight-line\n+ execution, which can easily be wrong with loops and conditionals.\n+ \"\"\"\n+ unique_alternate_id = self.next_slice_id()\n+ alternate_code = f\"\\0{prefix}{unique_alternate_id}_{length}\"\n+ return RawSliceInfo(unique_alternate_id, alternate_code, [])\n+\n def _slice_template(self) -> List[RawFileSlice]:\n \"\"\"Slice template in jinja.\n \n@@ -217,12 +234,6 @@ def _slice_template(self) -> List[RawFileSlice]:\n for _, elem_type, raw in self.env.lex(self.raw_str):\n # Replace literal text with a unique ID.\n if elem_type == \"data\":\n- if set_idx is None:\n- unique_alternate_id = self.next_slice_id()\n- alternate_code = f\"\\0{unique_alternate_id}_{len(raw)}\"\n- else:\n- unique_alternate_id = self.next_slice_id()\n- alternate_code = f\"\\0set{unique_alternate_id}_{len(raw)}\"\n result.append(\n RawFileSlice(\n raw,\n@@ -230,8 +241,8 @@ def _slice_template(self) -> List[RawFileSlice]:\n idx,\n )\n )\n- self.raw_slice_info[result[-1]] = RawSliceInfo(\n- unique_alternate_id, alternate_code, []\n+ self.raw_slice_info[result[-1]] = self.slice_info_for_literal(\n+ len(raw), \"\" if set_idx is None else \"set\"\n )\n idx += len(raw)\n continue\n@@ -274,7 +285,7 @@ def _slice_template(self) -> List[RawFileSlice]:\n )\n # Treat the skipped whitespace as a literal.\n result.append(RawFileSlice(skipped_str, \"literal\", idx))\n- self.raw_slice_info[result[-1]] = RawSliceInfo(\"\", \"\", [])\n+ self.raw_slice_info[result[-1]] = self.slice_info_for_literal(0)\n idx += num_chars_skipped\n \n # raw_end and raw_begin behave a little differently in\n@@ -354,10 +365,6 @@ def _slice_template(self) -> List[RawFileSlice]:\n # returns, it has simply grouped them differently than we\n # want.\n trailing_chars = len(m.group(0))\n- if block_type.startswith(\"block_\"):\n- alternate_code = self._remove_block_whitespace_control(\n- str_buff[:-trailing_chars]\n- )\n result.append(\n RawFileSlice(\n str_buff[:-trailing_chars],\n@@ -378,11 +385,9 @@ def _slice_template(self) -> List[RawFileSlice]:\n idx,\n )\n )\n- self.raw_slice_info[result[-1]] = RawSliceInfo(\"\", \"\", [])\n+ self.raw_slice_info[result[-1]] = self.slice_info_for_literal(0)\n idx += trailing_chars\n else:\n- if block_type.startswith(\"block_\"):\n- alternate_code = self._remove_block_whitespace_control(str_buff)\n result.append(\n RawFileSlice(\n str_buff,\n@@ -424,17 +429,3 @@ def _slice_template(self) -> List[RawFileSlice]:\n stack.pop()\n str_buff = \"\"\n return result\n-\n- @classmethod\n- def _remove_block_whitespace_control(cls, in_str: str) -> Optional[str]:\n- \"\"\"Removes whitespace control from a Jinja block start or end.\n-\n- Use of Jinja whitespace stripping (e.g. `{%-` or `-%}`) causes the\n- template to produce less output. This makes JinjaTracer's job harder,\n- because it uses the \"bread crumb trail\" of output to deduce the\n- execution path through the template. This change has no impact on the\n- actual Jinja output, which uses the original, unmodified code.\n- \"\"\"\n- result = regex.sub(r\"^{%-\", \"{%\", in_str)\n- result = regex.sub(r\"-%}$\", \"%}\", result)\n- return result if result != in_str else None\n", "test_patch": "diff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -756,7 +756,6 @@ def test__templater_jinja_slice_template(test, result):\n (\"block_start\", slice(0, 25, None), slice(0, 0, None)),\n (\"literal\", slice(25, 30, None), slice(0, 5, None)),\n (\"block_start\", slice(30, 47, None), slice(5, 5, None)),\n- (\"literal\", slice(47, 67, None), slice(5, 5, None)),\n (\"block_end\", slice(67, 78, None), slice(5, 5, None)),\n (\"literal\", slice(78, 79, None), slice(5, 5, None)),\n (\"block_end\", slice(79, 92, None), slice(5, 5, None)),\n@@ -796,6 +795,57 @@ def test__templater_jinja_slice_template(test, result):\n (\"literal\", slice(46, 57, None), slice(11, 22, None)),\n ],\n ),\n+ (\n+ # Test for issue 2786. Also lots of whitespace control. In this\n+ # case, removing whitespace control alone wasn't enough. In order\n+ # to get a good trace, JinjaTracer had to be updated so the\n+ # alternate template included output for the discarded whitespace.\n+ \"\"\"select\n+ id,\n+ {%- for features in [\"value4\", \"value5\"] %}\n+ {%- if features in [\"value7\"] %}\n+ {{features}}\n+ {%- if not loop.last -%},{% endif %}\n+ {%- else -%}\n+ {{features}}\n+ {%- if not loop.last -%},{% endif %}\n+ {%- endif -%}\n+ {%- endfor %}\n+from my_table\n+\"\"\",\n+ None,\n+ [\n+ (\"literal\", slice(0, 14, None), slice(0, 14, None)),\n+ (\"literal\", slice(14, 19, None), slice(14, 14, None)),\n+ (\"block_start\", slice(19, 62, None), slice(14, 14, None)),\n+ (\"literal\", slice(62, 71, None), slice(14, 14, None)),\n+ (\"block_start\", slice(71, 103, None), slice(14, 14, None)),\n+ (\"block_mid\", slice(186, 198, None), slice(14, 14, None)),\n+ (\"literal\", slice(198, 211, None), slice(14, 14, None)),\n+ (\"templated\", slice(211, 223, None), slice(14, 20, None)),\n+ (\"literal\", slice(223, 236, None), slice(20, 20, None)),\n+ (\"block_start\", slice(236, 260, None), slice(20, 20, None)),\n+ (\"literal\", slice(260, 261, None), slice(20, 21, None)),\n+ (\"block_end\", slice(261, 272, None), slice(21, 21, None)),\n+ (\"literal\", slice(272, 281, None), slice(21, 21, None)),\n+ (\"block_end\", slice(281, 294, None), slice(21, 21, None)),\n+ (\"literal\", slice(294, 299, None), slice(21, 21, None)),\n+ (\"block_end\", slice(299, 312, None), slice(21, 21, None)),\n+ (\"literal\", slice(62, 71, None), slice(21, 21, None)),\n+ (\"block_start\", slice(71, 103, None), slice(21, 21, None)),\n+ (\"block_mid\", slice(186, 198, None), slice(21, 21, None)),\n+ (\"literal\", slice(198, 211, None), slice(21, 21, None)),\n+ (\"templated\", slice(211, 223, None), slice(21, 27, None)),\n+ (\"literal\", slice(223, 236, None), slice(27, 27, None)),\n+ (\"block_start\", slice(236, 260, None), slice(27, 27, None)),\n+ (\"block_end\", slice(261, 272, None), slice(27, 27, None)),\n+ (\"literal\", slice(272, 281, None), slice(27, 27, None)),\n+ (\"block_end\", slice(281, 294, None), slice(27, 27, None)),\n+ (\"literal\", slice(294, 299, None), slice(27, 27, None)),\n+ (\"block_end\", slice(299, 312, None), slice(27, 27, None)),\n+ (\"literal\", slice(312, 327, None), slice(27, 42, None)),\n+ ],\n+ ),\n ],\n )\n def test__templater_jinja_slice_file(raw_file, override_context, result, caplog):\n", "problem_statement": "ValueError: Position Not Found for lint/parse/fix, not clear why\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nI have admittedly messy dbt sql model that gets the following error when I try to lint, parse or fix it with sqlfluff - every other model can be processed using the same settings, but this one throws the same error below even if I only run a single rule e.g. L009.\r\n\r\nUnfortunately I cannot share the model itself but I can describe some notable features:\r\n- begins with a dbt incremental config\r\n- then sets three variables, each a list of strings\r\n- Has two `for` loops with nested `if` conditions\r\n- Has one very long line doing arithmetic operations involving both hardcoded values and columns from a two joined CTEs\r\n\r\n### Expected Behaviour\r\n\r\nNot the above error\r\n\r\n### Observed Behaviour\r\n\r\n```\r\nWARNING Unable to lint models/ltv_prediction_model/ltv_prediction.sql due to an internal error. Please report this as an issue w\r\nith your query's contents and stacktrace below!\r\nTo hide this warning, add the failing file to .sqlfluffignore\r\nTraceback (most recent call last):\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/linter/runner.py\", line 103, in run\r\n yield partial()\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 666, in lint_rendered\r\n parsed = cls.parse_rendered(rendered)\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 352, in parse_rendere\r\n\r\nd\r\n tokens, lvs, config = cls._lex_templated_file(\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 139, in _lex_template\r\nd_file\r\n tokens, lex_vs = lexer.lex(templated_file)\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/parser/lexer.py\", line 321, in lex\r\n segments: Tuple[RawSegment, ...] = self.elements_to_segments(\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/parser/lexer.py\", line 348, in elements_to_se\r\ngments\r\n source_slice = templated_file.templated_slice_to_source_slice(\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/templaters/base.py\", line 294, in templated_s\r\nlice_to_source_slice\r\n ts_stop_sf_start, ts_stop_sf_stop = self._find_slice_indices_of_templated_pos(\r\n File \"/Users/dlyons/.pyenv/versions/3.9.4/lib/python3.9/site-packages/sqlfluff/core/templaters/base.py\", line 180, in _find_slice\r\n_indices_of_templated_pos\r\n raise ValueError(\"Position Not Found\")\r\nValueError: Position Not Found\r\n```\r\n\r\n### How to reproduce\r\n\r\n```\r\n{{\r\n config(\r\n materialized='incremental',\r\n unique_key='md5_surrogate_key_main'\r\n )\r\n}}\r\n\r\n{%- set first_list = [\"value1\", \"value2\", \"value3\"] -%}\r\n{%- set second_list = [\"value4\", \"value5\", \"value6\"] -%}\r\n{%- set third_list = [\"value7\", \"value8\", \"value9\"] -%}\r\n\r\nwith fill_na_values as (\r\n select\r\n id,\r\n run_date,\r\n md5_surrogate_key_main,\r\n {%- for features in second_list %}\r\n {%- if features in third_list %}\r\n coalesce({{features}}, (select feature_mode from {{ ref('second_list') }} where features = '{{features}}')) as {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- else -%}\r\n coalesce({{features}}, (select feature_mean from {{ ref('second_list') }} where features = '{{features}}')) as {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endif -%}\r\n {%- endfor %}\r\n from {{ ref('training_dataset') }}\r\n {%- if is_incremental() %}\r\n where current_date >= (select max(run_date) from {{ this }})\r\n {%- else %}\r\n where run_date >= '2021-01-01'\r\n {%- endif %}\r\n),\r\n\r\nwinsorize_data as (\r\n select\r\n md5_surrogate_key_main,\r\n {%- for features in second_list %}\r\n {%- if features in first_list %}\r\n case\r\n when {{features}} < (select fifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n then (select fifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n when {{features}} > (select ninetyfifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n then (select ninetyfifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n else {{features}}\r\n end as {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- else %}\r\n {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endif %}\r\n {%- endfor %}\r\n from fill_na_values\r\n),\r\n\r\nscaling_data as (\r\n select\r\n md5_surrogate_key_main,\r\n {%- for features in second_list %}\r\n ({{features}} - (select feature_mean from {{ ref('second_list') }} where features = '{{features}}'))/(select feature_std from {{ ref('second_list') }} where features = '{{features}}') as {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endfor %}\r\n from winsorize_data\r\n),\r\n\r\napply_ceofficients as (\r\n select\r\n md5_surrogate_key_main,\r\n {%- for features in second_list %}\r\n {{features}} * (select coefficients from {{ ref('second_list') }} where features = '{{features}}') as {{features}}_coef\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endfor %}\r\n from scaling_data\r\n),\r\n\r\nlogistic_prediction as (\r\n select\r\n fan.*,\r\n 1/(1+EXP(-(0.24602303+coef1+coef2+coef3+coef4+coef5+coef6+coef7+coef8+coef9+available_balance_coef+coef10+coef11+coef12+coef13+coef14))) as prediction_probability,\r\n case when prediction_probability < .5 then 0 else 1 end as prediction_class\r\n from apply_ceofficients ac\r\n inner join fill_na_values fan\r\n on ac.md5_surrogate_key_main = fan.md5_surrogate_key_main\r\n)\r\n\r\nselect * from logistic_prediction\r\n```\r\n\r\n### Dialect\r\n\r\nSnowflake\r\n\r\n### Version\r\n\r\n0.10.1\r\n\r\n### Configuration\r\n\r\n```\r\n[sqlfluff]\r\n# verbose is an integer (0-2) indicating the level of log output\r\nverbose = 0\r\n# Turn off color formatting of output\r\nnocolor = False\r\ndialect = snowflake\r\ntemplater = jinja\r\n# Comma separated list of rules to check, or None for all\r\nrules = L001,L002,L003,L004,L005,L009,L010,L013,L014,L015,L017,L018,L019,L020,L021,L022,L023,L024,L026,L027,L028,L030,L036,L037,L038,L039,L040,L044,L045,L046,L050,L051,L058,L061\r\n# Comma separated list of rules to exclude, or None\r\nexclude_rules = L006,L008,L011,L012,L025,L029,L031,L034,L035,L041,L042,L043,L052\r\n# The depth to recursively parse to (0 for unlimited)\r\nrecurse = 0\r\n# Below controls SQLFluff output, see max_line_length for SQL output\r\noutput_line_length = 80\r\n# Number of passes to run before admitting defeat\r\nrunaway_limit = 10\r\n# Ignore errors by category (one or more of the following, separated by commas: lexing,linting,parsing,templating)\r\nignore = None\r\n# Ignore linting errors found within sections of code coming directly from\r\n# templated code (e.g. from within Jinja curly braces. Note that it does not\r\n# ignore errors from literal code found within template loops.\r\nignore_templated_areas = True\r\n# can either be autodetect or a valid encoding e.g. utf-8, utf-8-sig\r\nencoding = autodetect\r\n# Ignore inline overrides (e.g. to test if still required)\r\ndisable_noqa = False\r\n# Comma separated list of file extensions to lint\r\n# NB: This config will only apply in the root folder\r\nsql_file_exts = .sql,.sql.j2,.dml,.ddl\r\n# Allow fix to run on files, even if they contain parsing errors\r\n# Note altering this is NOT RECOMMENDED as can corrupt SQL\r\nfix_even_unparsable = False\r\n\r\n[sqlfluff:indentation]\r\n# See https://docs.sqlfluff.com/en/stable/indentation.html\r\nindented_joins = False\r\nindented_ctes = False\r\nindented_using_on = True\r\ntemplate_blocks_indent = True\r\n\r\n[sqlfluff:templater]\r\nunwrap_wrapped_queries = True\r\n\r\n[sqlfluff:templater:jinja]\r\napply_dbt_builtins = True\r\n\r\n[sqlfluff:templater:jinja:macros]\r\n# Macros provided as builtins for dbt projects\r\ndbt_ref = {% macro ref(model_ref) %}{{model_ref}}{% endmacro %}\r\ndbt_source = {% macro source(source_name, table) %}{{source_name}}_{{table}}{% endmacro %}\r\ndbt_config = {% macro config() %}{% for k in kwargs %}{% endfor %}{% endmacro %}\r\ndbt_var = {% macro var(variable, default='') %}item{% endmacro %}\r\ndbt_is_incremental = {% macro is_incremental() %}True{% endmacro %}\r\n\r\n# Some rules can be configured directly from the config common to other rules\r\n[sqlfluff:rules]\r\ntab_space_size = 4\r\nmax_line_length = 80\r\nindent_unit = space\r\ncomma_style = trailing\r\nallow_scalar = True\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = all\r\n\r\n# Some rules have their own specific config\r\n[sqlfluff:rules:L007]\r\noperator_new_lines = after\r\n\r\n[sqlfluff:rules:L010]\r\n# Keywords\r\ncapitalisation_policy = consistent\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\n\r\n[sqlfluff:rules:L011]\r\n# Aliasing preference for tables\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:L012]\r\n# Aliasing preference for columns\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:L014]\r\n# Unquoted identifiers\r\nextended_capitalisation_policy = consistent\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\n\r\n[sqlfluff:rules:L016]\r\n# Line length\r\nignore_comment_lines = False\r\nignore_comment_clauses = False\r\n\r\n[sqlfluff:rules:L026]\r\n# References must be in FROM clause\r\n# Disabled for some dialects (e.g. bigquery)\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L028]\r\n# References must be consistently used\r\n# Disabled for some dialects (e.g. bigquery)\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L029]\r\n# Keywords should not be used as identifiers.\r\nunquoted_identifiers_policy = aliases\r\nquoted_identifiers_policy = none\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\n\r\n[sqlfluff:rules:L030]\r\n# Function names\r\ncapitalisation_policy = consistent\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\n\r\n[sqlfluff:rules:L038]\r\n# Trailing commas\r\nselect_clause_trailing_comma = forbid\r\n\r\n[sqlfluff:rules:L040]\r\n# Null & Boolean Literals\r\ncapitalisation_policy = consistent\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\n\r\n[sqlfluff:rules:L042]\r\n# By default, allow subqueries in from clauses, but not join clauses\r\nforbid_subquery_in = join\r\n\r\n[sqlfluff:rules:L047]\r\n# Consistent syntax to count all rows\r\nprefer_count_1 = False\r\nprefer_count_0 = False\r\n\r\n[sqlfluff:rules:L052]\r\n# Semi-colon formatting approach\r\nmultiline_newline = False\r\nrequire_final_semicolon = False\r\n\r\n[sqlfluff:rules:L054]\r\n# GROUP BY/ORDER BY column references\r\ngroup_by_and_order_by_style = consistent\r\n\r\n[sqlfluff:rules:L057]\r\n# Special characters in identifiers\r\nunquoted_identifiers_policy = all\r\nquoted_identifiers_policy = all\r\nallow_space_in_identifier = False\r\nadditional_allowed_characters = \"\"\r\n\r\n[sqlfluff:rules:L059]\r\n# Policy on quoted and unquoted identifiers\r\nprefer_quoted_identifiers = False\r\n\r\n[sqlfluff:rules:L062]\r\n# Comma separated list of blocked words that should not be used\r\nblocked_words = None\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n```\n", "hints_text": "> Proprietary concerns prevent me from sharing the query itself, I could try to boil it down to a mock version that replicates the error.\r\n\r\nThis would be needed before we can make any progress on this I'm afraid. The stack trace is good, and will help us identify the area of code, but without the SQL we can't know why and this issue will need to be closed.\n@tunetheweb fair play, let me try to create a stripped down representation.\n@tunetheweb there you go!\nI managed to reproduce this in the latest `main`. Taking a quick look...\nIt fails when looking for templated position 198. The highest-numbered position in the `sliced_file` collection is 190. \r\n```\r\n(Pdb) templated_pos\r\n198\r\n(Pdb) pp self.sliced_file\r\n[TemplatedFileSlice(slice_type='templated', source_slice=slice(0, 103, None), templated_slice=slice(0, 0, None)),\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(103, 105, None), templated_slice=slice(0, 0, None)),\r\n TemplatedFileSlice(slice_type='block_start', source_slice=slice(105, 160, None), templated_slice=slice(0, 0, None)),\r\n...\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(2822, 2823, None), templated_slice=slice(190, 190, None)),\r\n TemplatedFileSlice(slice_type='block_end', source_slice=slice(2823, 2834, None), templated_slice=slice(190, 190, None)),\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(2834, 2843, None), templated_slice=slice(190, 190, None)),\r\n TemplatedFileSlice(slice_type='block_end', source_slice=slice(2843, 2856, None), templated_slice=slice(190, 190, None)),\r\n TemplatedFileSlice(slice_type='literal', source_slice=slice(2856, 3358, None), templated_slice=slice(190, 190, None))]\r\n(Pdb) \r\n```\r\n\r\nThe `sliced_file` is clearly wrong, because the rendered SQL is 2,083 characters long:\r\n```\r\n(Pdb) len(str(self))\r\n2083\r\n```\nThe templater is losing track of things at line 19 of the input file:\r\n```\r\n coalesce({{features}}, (select feature_mode from {{ ref('second_list') }} where features = '{{features}}')) as {{features}}\r\n```\r\n\r\nPosition 198 is where the code `{{features}}` renders, just after `coalesce(`.\nThe following simpler SQL can be used to reproduce the same issue:\r\n```\r\nselect\r\n {%- for features in [\"value4\", \"value5\"] %}\r\n {%- if features in [\"value7\"] %}\r\n {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- else -%}\r\n {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endif -%}\r\n {%- endfor %}\r\nfrom my_table\r\n```\r\n\r\nThis is another test case I extracted (may be the same bug, not sure):\r\n```\r\n{%- set first_list = [\"value1\", \"value2\", \"value3\"] -%}\r\n{%- set second_list = [\"value4\", \"value5\", \"value6\"] -%}\r\n\r\nwith winsorize_data as (\r\n select\r\n md5_surrogate_key_main,\r\n {%- for features in second_list %}\r\n {%- if features in first_list %}\r\n case\r\n when {{features}} < (select fifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n then (select fifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n when {{features}} > (select ninetyfifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n then (select ninetyfifth_percentile from {{ ref('first_list') }} where winsorize_column = '{{features}}')\r\n else {{features}}\r\n end as {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- else %}\r\n {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endif %}\r\n {%- endfor %}\r\n from ref('training_dataset')\r\n),\r\n\r\nscaling_data as (\r\n select\r\n md5_surrogate_key_main,\r\n {%- for features in second_list %}\r\n ({{features}} - (select feature_mean from {{ ref('second_list') }} where features = '{{features}}'))/(select feature_std from {{ ref('second_list') }} where features = '{{features}}') as {{features}}\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endfor %}\r\n from winsorize_data\r\n),\r\n\r\napply_ceofficients as (\r\n select\r\n md5_surrogate_key_main,\r\n {%- for features in second_list %}\r\n {{features}} * (select coefficients from {{ ref('second_list') }} where features = '{{features}}') as {{features}}_coef\r\n {%- if not loop.last -%},{% endif %}\r\n {%- endfor %}\r\n from scaling_data\r\n),\r\n\r\nlogistic_prediction as (\r\n select\r\n fan.*,\r\n 1/(1+EXP(-(0.24602303+coef1+coef2+coef3+coef4+coef5+coef6+coef7+coef8+coef9+available_balance_coef+coef10+coef11+coef12+coef13+coef14))) as prediction_probability,\r\n case when prediction_probability < .5 then 0 else 1 end as prediction_class\r\n from apply_ceofficients ac\r\n inner join fill_na_values fan\r\n on ac.md5_surrogate_key_main = fan.md5_surrogate_key_main\r\n)\r\n\r\nselect * from logistic_prediction\r\n```\n@davesgonechina: I found a workaround if you want to try it. Don't use Jinja whitespace control. In other words, replace all occurrences of `{%-` with `{%` and all occurrences of `-%}` with `%}`.\r\n\r\nI'll keep looking to see if I can find a fix. SQLFluff has had some past bugs involving whitespace control. Basically, it makes SQLFluff's job more challenging, when it tries to \"map\" the input SQL (before running Jinja) to the output file (after running Jinja).\nIn the file `src/sqlfluff/core/templaters/slicers/tracer.py`, I thought that the recently added function `_remove_block_whitespace_control` would eliminate any issues with whitespace control. It was added to fix _some_ issues like this. Perhaps this is a more complex situation?\r\n\r\nGenerally, avoiding whitespace control in the \"alternate\" template results in template output with more \"breadcrumbs\", making it easier for the tracer to deduce the execution path of the template. The issue we saw before (which may be happening here) is that the tracer loses track of the execution path and \"drops\" off the end of the template at some point. Should be fairly easy to find where (and why) this is happening. May be harder to fix. We shall see...", "created_at": "2022-03-11T21:52:54Z", "version": "0.10", "FAIL_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n"], "PASS_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-"], "environment_setup_commit": "3d52e8270d82aeccf4c516d059a80a6947919aea"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3662", "base_commit": "f9a3fe8f639d279226f16bdc51326dfa5c142c3e", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -486,8 +486,12 @@ def dump_file_payload(filename: Optional[str], payload: str):\n \"-p\",\n \"--processes\",\n type=int,\n- default=1,\n- help=\"The number of parallel processes to run.\",\n+ default=None,\n+ help=(\n+ \"The number of parallel processes to run. Positive numbers work as \"\n+ \"expected. Zero and negative numbers will work as number_of_cpus - \"\n+ \"number. e.g -1 means all cpus except one. 0 means all cpus.\"\n+ ),\n )\n @click.option(\n \"--disable_progress_bar\",\n@@ -497,7 +501,6 @@ def dump_file_payload(filename: Optional[str], payload: str):\n @click.argument(\"paths\", nargs=-1, type=click.Path(allow_dash=True))\n def lint(\n paths: Tuple[str],\n- processes: int,\n format: str,\n write_output: Optional[str],\n annotation_level: str,\n@@ -505,6 +508,7 @@ def lint(\n disregard_sqlfluffignores: bool,\n logger: Optional[logging.Logger] = None,\n bench: bool = False,\n+ processes: Optional[int] = None,\n disable_progress_bar: Optional[bool] = False,\n extra_config_path: Optional[str] = None,\n ignore_local_config: bool = False,\n@@ -675,8 +679,12 @@ def do_fixes(lnt, result, formatter=None, **kwargs):\n \"-p\",\n \"--processes\",\n type=int,\n- default=1,\n- help=\"The number of parallel processes to run.\",\n+ default=None,\n+ help=(\n+ \"The number of parallel processes to run. Positive numbers work as \"\n+ \"expected. Zero and negative numbers will work as number_of_cpus - \"\n+ \"number. e.g -1 means all cpus except one. 0 means all cpus.\"\n+ ),\n )\n @click.option(\n \"--disable_progress_bar\",\n@@ -705,10 +713,10 @@ def do_fixes(lnt, result, formatter=None, **kwargs):\n def fix(\n force: bool,\n paths: Tuple[str],\n- processes: int,\n bench: bool = False,\n fixed_suffix: str = \"\",\n logger: Optional[logging.Logger] = None,\n+ processes: Optional[int] = None,\n disable_progress_bar: Optional[bool] = False,\n extra_config_path: Optional[str] = None,\n ignore_local_config: bool = False,\ndiff --git a/src/sqlfluff/cli/formatters.py b/src/sqlfluff/cli/formatters.py\n--- a/src/sqlfluff/cli/formatters.py\n+++ b/src/sqlfluff/cli/formatters.py\n@@ -181,6 +181,14 @@ def dispatch_compilation_header(self, templater, message):\n f\"=== [{self.colorize(templater, Color.lightgrey)}] {message}\"\n ) # pragma: no cover\n \n+ def dispatch_processing_header(self, processes: int) -> None:\n+ \"\"\"Dispatch the header displayed before linting.\"\"\"\n+ if self._verbosity > 0:\n+ self._dispatch( # pragma: no cover\n+ f\"{self.colorize('effective configured processes: ', Color.lightgrey)} \"\n+ f\"{processes}\"\n+ )\n+\n def dispatch_dialect_warning(self, dialect) -> None:\n \"\"\"Dispatch a warning for dialects.\"\"\"\n self._dispatch(self.format_dialect_warning(dialect)) # pragma: no cover\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -1066,7 +1066,7 @@ def lint_path(\n fix: bool = False,\n ignore_non_existent_files: bool = False,\n ignore_files: bool = True,\n- processes: int = 1,\n+ processes: Optional[int] = None,\n ) -> LintedDir:\n \"\"\"Lint a path.\"\"\"\n linted_path = LintedDir(path)\n@@ -1080,16 +1080,22 @@ def lint_path(\n )\n )\n \n+ if processes is None:\n+ processes = self.config.get(\"processes\", default=1)\n+\n # to avoid circular import\n from sqlfluff.core.linter.runner import get_runner\n \n- runner = get_runner(\n+ runner, effective_processes = get_runner(\n self,\n self.config,\n processes=processes,\n allow_process_parallelism=self.allow_process_parallelism,\n )\n \n+ if self.formatter and effective_processes != 1:\n+ self.formatter.dispatch_processing_header(effective_processes)\n+\n # Show files progress bar only when there is more than one.\n files_count = len(fnames)\n progress_bar_files = tqdm(\n@@ -1124,7 +1130,7 @@ def lint_paths(\n fix: bool = False,\n ignore_non_existent_files: bool = False,\n ignore_files: bool = True,\n- processes: int = 1,\n+ processes: Optional[int] = None,\n ) -> LintingResult:\n \"\"\"Lint an iterable of paths.\"\"\"\n paths_count = len(paths)\ndiff --git a/src/sqlfluff/core/linter/runner.py b/src/sqlfluff/core/linter/runner.py\n--- a/src/sqlfluff/core/linter/runner.py\n+++ b/src/sqlfluff/core/linter/runner.py\n@@ -10,6 +10,7 @@\n import bdb\n import functools\n import logging\n+import multiprocessing\n import multiprocessing.dummy\n import signal\n import sys\n@@ -227,15 +228,29 @@ def get_runner(\n config: FluffConfig,\n processes: int,\n allow_process_parallelism: bool = True,\n-) -> BaseRunner:\n- \"\"\"Generate a runner instance based on parallel and system configuration.\"\"\"\n+) -> Tuple[BaseRunner, int]:\n+ \"\"\"Generate a runner instance based on parallel and system configuration.\n+\n+ The processes argument can be positive or negative.\n+ - If positive, the integer is interpreted as the number of processes.\n+ - If negative or zero, the integer is interpreted as number_of_cpus - processes.\n+\n+ e.g.\n+ -1 = all cpus but one.\n+ 0 = all cpus\n+ 1 = 1 cpu\n+\n+ \"\"\"\n+ if processes <= 0:\n+ processes = max(multiprocessing.cpu_count() + processes, 1)\n+\n if processes > 1:\n # Process parallelism isn't really supported during testing\n # so this flag allows us to fall back to a threaded runner\n # in those cases.\n if allow_process_parallelism:\n- return MultiProcessRunner(linter, config, processes=processes)\n+ return MultiProcessRunner(linter, config, processes=processes), processes\n else:\n- return MultiThreadRunner(linter, config, processes=processes)\n+ return MultiThreadRunner(linter, config, processes=processes), processes\n else:\n- return SequentialRunner(linter, config)\n+ return SequentialRunner(linter, config), processes\n", "test_patch": "diff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -14,6 +14,7 @@\n from sqlfluff.cli.formatters import OutputStreamFormatter\n from sqlfluff.cli.outputstream import make_output_stream\n from sqlfluff.core.linter import LintingResult, NoQaDirective\n+from sqlfluff.core.linter.runner import get_runner\n import sqlfluff.core.linter as linter\n from sqlfluff.core.parser import GreedyUntil, Ref\n from sqlfluff.core.templaters import TemplatedFile\n@@ -289,6 +290,36 @@ def test_lint_path_parallel_wrapper_exception(patched_lint):\n result.reraise()\n \n \[email protected](\n+ \"mock_cpu,in_processes,exp_processes\",\n+ [\n+ # Make the mocked cpu count a really high value which is\n+ # unlikely to collide with the real value. We can then\n+ # test all the different combos.\n+ (512, 1, 1),\n+ (512, 0, 512),\n+ (512, -12, 500),\n+ (512, 5, 5),\n+ # Check that we can't go lower than 1 in a 1 cpu case\n+ (1, -1, 1),\n+ ],\n+)\n+@patch(\"multiprocessing.cpu_count\")\n+def test__linter__get_runner_processes(\n+ patched_cpu_count, mock_cpu, in_processes, exp_processes\n+):\n+ \"\"\"Test that get_runner handles processes correctly.\"\"\"\n+ # Make the mocked cpu count a really high value which is\n+ # unlikely to collide with the real value.\n+ patched_cpu_count.return_value = mock_cpu\n+ _, return_processes = get_runner(\n+ linter=Linter(),\n+ config=FluffConfig(overrides={\"dialect\": \"ansi\"}),\n+ processes=in_processes,\n+ )\n+ assert return_processes == exp_processes\n+\n+\n @patch(\"sqlfluff.core.linter.runner.linter_logger\")\n @patch(\"sqlfluff.core.linter.Linter.lint_rendered\")\n def test__linter__linting_unexpected_error_handled_gracefully(\n", "problem_statement": "Number of processes configurable in .sqlfluff\nBeing able to set the number of processes to run with in .sqlfluff might be useful to avoid having to pass it in the CLI every time.\n", "hints_text": "One thought on this: The same `.sqlfluff` file will sometimes be used on different machines (e.g. various development machines, CI server). We should allow the setting to be somewhat \"context sensitive\" if desired. Proposal:\r\n* Positive values indicate the number of processes to create\r\n* Zero or negative values are interpreted as `number_of_cpus - specified_number`. Thus, a value of `0` means \"use all processors\" and `-1` means \"use all processors except one\".\nIs there a standard way in python to detect the effective available cpus?\n@alanmcruickshank: Yes. Use [`multiprocessing.cpu_count()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count).\nI'm happy to pick this one up. This actually fits with a small reorg of how I think threads should be configured. I think it fits better if the thread argument is passed in to the `Linter` object on instantiation, rather than when calling `lint_paths`. @barrywhart - does that sit well with you? I realise that changes a little of the structure you originally envisaged.\nSounds good -- no concerns from me.", "created_at": "2022-07-25T09:10:25Z", "version": "1.2", "FAIL_TO_PASS": ["test/core/linter_test.py::test__linter__get_runner_processes[512-1-1]", "test/core/linter_test.py::test__linter__get_runner_processes[512-0-512]", "test/core/linter_test.py::test__linter__get_runner_processes[512--12-500]", "test/core/linter_test.py::test__linter__get_runner_processes[512-5-5]", "test/core/linter_test.py::test__linter__get_runner_processes[1--1-1]"], "PASS_TO_PASS": ["test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__sqlfluffignore_current_directory", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_parse_noqa[Inline", "test/core/linter_test.py::test_parse_noqa_no_dups", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[2_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_glob_ignore]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_linter_noqa_template_errors", "test/core/linter_test.py::test_linter_noqa_prs", "test/core/linter_test.py::test_linter_noqa_tmp", "test/core/linter_test.py::test_linter_noqa_disable", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]", "test/core/linter_test.py::test_advanced_api_methods", "test/core/linter_test.py::test_normalise_newlines", "test/core/linter_test.py::test_require_match_parse_grammar"], "environment_setup_commit": "388dd01e05c7dcb880165c7241ed4027d9d0171e"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4997", "base_commit": "50bbffd4672aa17af2651f40d533cf55048b7524", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -1356,7 +1356,7 @@ def render(\n fname = path\n \n # Get file specific config\n- file_config.process_raw_file_for_config(raw_sql)\n+ file_config.process_raw_file_for_config(raw_sql, fname)\n rendered = lnt.render_string(raw_sql, fname, file_config, \"utf8\")\n \n if rendered.templater_violations:\ndiff --git a/src/sqlfluff/core/config.py b/src/sqlfluff/core/config.py\n--- a/src/sqlfluff/core/config.py\n+++ b/src/sqlfluff/core/config.py\n@@ -34,6 +34,16 @@\n ConfigElemType = Tuple[Tuple[str, ...], Any]\n \n \n+ALLOWABLE_LAYOUT_CONFIG_KEYS = (\n+ \"spacing_before\",\n+ \"spacing_after\",\n+ \"spacing_within\",\n+ \"line_position\",\n+ \"align_within\",\n+ \"align_scope\",\n+)\n+\n+\n @dataclass\n class _RemovedConfig:\n old_path: Tuple[str, ...]\n@@ -501,13 +511,19 @@ def _incorporate_vals(ctx: dict, vals: List[ConfigElemType]) -> dict:\n def _validate_configs(\n configs: Iterable[ConfigElemType], file_path\n ) -> List[ConfigElemType]:\n- \"\"\"Validate config elements against removed list.\"\"\"\n+ \"\"\"Validate config elements.\n+\n+ We validate in two ways:\n+ 1. Are these config settings removed or deprecated.\n+ 2. Are these config elements in the layout section _valid_.\n+ \"\"\"\n config_map = {cfg.old_path: cfg for cfg in REMOVED_CONFIGS}\n # Materialise the configs into a list to we can iterate twice.\n new_configs = list(configs)\n defined_keys = {k for k, _ in new_configs}\n validated_configs = []\n for k, v in new_configs:\n+ # First validate against the removed option list.\n if k in config_map.keys():\n formatted_key = \":\".join(k)\n removed_option = config_map[k]\n@@ -549,12 +565,37 @@ def _validate_configs(\n else:\n # Raise an error.\n raise SQLFluffUserError(\n- f\"Config file {file_path} set an outdated config \"\n+ f\"Config file {file_path!r} set an outdated config \"\n f\"value {formatted_key}.\\n\\n{removed_option.warning}\\n\\n\"\n \"See https://docs.sqlfluff.com/en/stable/configuration.html\"\n \" for more details.\"\n )\n \n+ # Second validate any layout configs for validity.\n+ # NOTE: For now we don't check that the \"type\" is a valid one\n+ # to reference, or that the values are valid. For the values,\n+ # these are likely to be rejected by the layout routines at\n+ # runtime. The last risk area is validating that the type is\n+ # a valid one.\n+ if k and k[0] == \"layout\":\n+ # Check for:\n+ # - Key length\n+ # - Key values\n+ if (\n+ # Key length must be 4\n+ (len(k) != 4)\n+ # Second value must (currently) be \"type\"\n+ or (k[1] != \"type\")\n+ # Last key value must be one of the allowable options.\n+ or (k[3] not in ALLOWABLE_LAYOUT_CONFIG_KEYS)\n+ ):\n+ raise SQLFluffUserError(\n+ f\"Config file {file_path!r} set an invalid `layout` option \"\n+ f\"value {':'.join(k)}.\\n\"\n+ \"See https://docs.sqlfluff.com/en/stable/layout.html\"\n+ \"#configuring-layout for more details.\"\n+ )\n+\n validated_configs.append((k, v))\n return validated_configs\n \n@@ -1094,7 +1135,7 @@ def iter_vals(self, cfg: Optional[dict] = None) -> Iterable[tuple]:\n for idnt, key, val in self.iter_vals(cfg=cfg[k]):\n yield (idnt + 1, key, val)\n \n- def process_inline_config(self, config_line: str):\n+ def process_inline_config(self, config_line: str, fname: str):\n \"\"\"Process an inline config command and update self.\"\"\"\n # Strip preceding comment marks\n if config_line.startswith(\"--\"):\n@@ -1108,19 +1149,23 @@ def process_inline_config(self, config_line: str):\n config_line = config_line[9:].strip()\n # Divide on colons\n config_path = [elem.strip() for elem in config_line.split(\":\")]\n+ config_val = (tuple(config_path[:-1]), config_path[-1])\n+ # Validate the value\n+ ConfigLoader._validate_configs([config_val], fname)\n # Set the value\n- self.set_value(config_path[:-1], config_path[-1])\n+ self.set_value(*config_val)\n # If the config is for dialect, initialise the dialect\n if config_path[:-1] == [\"dialect\"]:\n self._initialise_dialect(config_path[-1])\n \n- def process_raw_file_for_config(self, raw_str: str):\n+ def process_raw_file_for_config(self, raw_str: str, fname: str):\n \"\"\"Process a full raw file for inline config and update self.\"\"\"\n # Scan the raw file for config commands.\n for raw_line in raw_str.splitlines():\n- if raw_line.startswith(\"-- sqlfluff\"):\n+ # With or without a space.\n+ if raw_line.startswith((\"-- sqlfluff\", \"--sqlfluff\")):\n # Found a in-file config command\n- self.process_inline_config(raw_line)\n+ self.process_inline_config(raw_line, fname)\n \n \n class ProgressBarConfiguration:\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -141,7 +141,7 @@ def load_raw_file_and_config(\n with open(fname, encoding=encoding, errors=\"backslashreplace\") as target_file:\n raw_file = target_file.read()\n # Scan the raw file for config commands.\n- file_config.process_raw_file_for_config(raw_file)\n+ file_config.process_raw_file_for_config(raw_file, fname)\n # Return the raw file and config\n return raw_file, file_config, encoding\n \n@@ -897,7 +897,7 @@ def parse_string(\n config = config or self.config\n \n # Scan the raw file for config commands.\n- config.process_raw_file_for_config(in_str)\n+ config.process_raw_file_for_config(in_str, fname)\n rendered = self.render_string(in_str, fname, config, encoding)\n violations += rendered.templater_violations\n \n", "test_patch": "diff --git a/test/core/config_test.py b/test/core/config_test.py\n--- a/test/core/config_test.py\n+++ b/test/core/config_test.py\n@@ -459,6 +459,50 @@ def test__config__validate_configs_indirect():\n )\n \n \[email protected](\n+ \"raw_sql\",\n+ [\n+ (\n+ # \"types\" not \"type\"\n+ \"-- sqlfluff:layout:types:comma:line_position:leading\\n\"\n+ \"SELECT 1\"\n+ ),\n+ (\n+ # Unsupported layout config length\n+ \"-- sqlfluff:layout:foo\\n\"\n+ \"SELECT 1\"\n+ ),\n+ (\n+ # Unsupported layout config length\n+ \"-- sqlfluff:layout:type:comma:bar\\n\"\n+ \"SELECT 1\"\n+ ),\n+ (\n+ # Unsupported layout config key (\"foo\")\n+ \"-- sqlfluff:layout:type:comma:foo:bar\\n\"\n+ \"SELECT 1\"\n+ ),\n+ (\n+ # Unsupported layout config key (\"foo\") [no space]\n+ \"--sqlfluff:layout:type:comma:foo:bar\\n\"\n+ \"SELECT 1\"\n+ ),\n+ ],\n+)\n+def test__config__validate_configs_inline_layout(raw_sql):\n+ \"\"\"Test _validate_configs method of FluffConfig when used on a file.\n+\n+ This test covers both the validation of inline config\n+ directives but also the validation of layout configs.\n+ \"\"\"\n+ # Instantiate config object.\n+ cfg = FluffConfig(configs={\"core\": {\"dialect\": \"ansi\"}})\n+\n+ # Try to process an invalid inline config. Make sure we get an error.\n+ with pytest.raises(SQLFluffUserError):\n+ cfg.process_raw_file_for_config(raw_sql, \"test.sql\")\n+\n+\n def test__config__validate_configs_precedence_same_file():\n \"\"\"Test _validate_configs method of FluffConfig where there's a conflict.\"\"\"\n # Check with a known conflicted value\n@@ -528,19 +572,19 @@ def test__process_inline_config():\n cfg = FluffConfig(config_b)\n assert cfg.get(\"rules\") == \"LT03\"\n \n- cfg.process_inline_config(\"-- sqlfluff:rules:LT02\")\n+ cfg.process_inline_config(\"-- sqlfluff:rules:LT02\", \"test.sql\")\n assert cfg.get(\"rules\") == \"LT02\"\n \n assert cfg.get(\"tab_space_size\", section=\"indentation\") == 4\n- cfg.process_inline_config(\"-- sqlfluff:indentation:tab_space_size:20\")\n+ cfg.process_inline_config(\"-- sqlfluff:indentation:tab_space_size:20\", \"test.sql\")\n assert cfg.get(\"tab_space_size\", section=\"indentation\") == 20\n \n assert cfg.get(\"dialect\") == \"ansi\"\n assert cfg.get(\"dialect_obj\").name == \"ansi\"\n- cfg.process_inline_config(\"-- sqlfluff:dialect:postgres\")\n+ cfg.process_inline_config(\"-- sqlfluff:dialect:postgres\", \"test.sql\")\n assert cfg.get(\"dialect\") == \"postgres\"\n assert cfg.get(\"dialect_obj\").name == \"postgres\"\n \n assert cfg.get(\"rulez\") is None\n- cfg.process_inline_config(\"-- sqlfluff:rulez:LT06\")\n+ cfg.process_inline_config(\"-- sqlfluff:rulez:LT06\", \"test.sql\")\n assert cfg.get(\"rulez\") == \"LT06\"\n", "problem_statement": "Validate layout configurations on load\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nAs raised in this comment: https://github.com/sqlfluff/sqlfluff/pull/4558#discussion_r1142745101\r\n\r\nAt the moment, the layout configs are being validated _on use_ which is potentially flaky and convoluted. Better would be to validate configs _on load_.\n\n### Use case\n\n_No response_\n\n### Dialect\n\nall\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [X] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "", "created_at": "2023-07-24T14:00:41Z", "version": "2.0", "FAIL_TO_PASS": ["test/core/config_test.py::test__config__validate_configs_inline_layout[--", "test/core/config_test.py::test__config__validate_configs_inline_layout[--sqlfluff:layout:type:comma:foo:bar\\nSELECT", "test/core/config_test.py::test__process_inline_config"], "PASS_TO_PASS": ["test/core/config_test.py::test__config__nested_combine", "test/core/config_test.py::test__config__dict_diff", "test/core/config_test.py::test__config__load_file_dir", "test/core/config_test.py::test__config__load_file_f", "test/core/config_test.py::test__config__load_nested", "test/core/config_test.py::test__config__iter_config_elems_from_dict", "test/core/config_test.py::test__config__load_toml", "test/core/config_test.py::test__config__load_placeholder_cfg", "test/core/config_test.py::test__config__iter_config_paths_right_order", "test/core/config_test.py::test__config__find_sqlfluffignore_in_same_directory", "test/core/config_test.py::test__config__nested_config_tests", "test/core/config_test.py::test__config__load_user_appdir_config", "test/core/config_test.py::test__config__split_comma_separated_string[AL01,LT08,AL07-expected0]", "test/core/config_test.py::test__config__split_comma_separated_string[\\nAL01,\\nLT08,\\nAL07,-expected1]", "test/core/config_test.py::test__config__split_comma_separated_string[raw_str2-expected2]", "test/core/config_test.py::test__config__split_comma_separated_string_correct_type", "test/core/config_test.py::test__config__templater_selection", "test/core/config_test.py::test__config__glob_exclude_config_tests", "test/core/config_test.py::test__config__glob_include_config_tests", "test/core/config_test.py::test__config__rules_set_to_none", "test/core/config_test.py::test__config__rules_group_with_exclude", "test/core/config_test.py::test__config__get_section", "test/core/config_test.py::test__config__get", "test/core/config_test.py::test__config__from_kwargs", "test/core/config_test.py::test__config_missing_dialect", "test/core/config_test.py::test__config__validate_configs_direct", "test/core/config_test.py::test__config__validate_configs_indirect", "test/core/config_test.py::test__config__validate_configs_precedence_same_file", "test/core/config_test.py::test__config__toml_list_config", "test/core/config_test.py::test__config__warn_unknown_rule"], "environment_setup_commit": "3629c3e702939c07264cc5ea903566ddc9ea2bb0"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2998", "base_commit": "47c8bb29104761474e455ef2e6fdaa7a8cc20a56", "patch": "diff --git a/src/sqlfluff/rules/L027.py b/src/sqlfluff/rules/L027.py\n--- a/src/sqlfluff/rules/L027.py\n+++ b/src/sqlfluff/rules/L027.py\n@@ -73,4 +73,21 @@ def _lint_references_and_aliases(\n )\n )\n \n+ all_table_aliases = [t.ref_str for t in table_aliases] + standalone_aliases\n+\n+ # For qualified references, we want to check that the alias is actually\n+ # valid\n+ if (\n+ this_ref_type == \"qualified\"\n+ and list(r.iter_raw_references())[0].part not in all_table_aliases\n+ ):\n+ violation_buff.append(\n+ LintResult(\n+ anchor=r,\n+ description=f\"Qualified reference {r.raw!r} not found in \"\n+ f\"available tables/view aliases {all_table_aliases} in select \"\n+ \"with more than one referenced table/view.\",\n+ )\n+ )\n+\n return violation_buff or None\n", "test_patch": "diff --git a/test/fixtures/rules/std_rule_cases/L027.yml b/test/fixtures/rules/std_rule_cases/L027.yml\n--- a/test/fixtures/rules/std_rule_cases/L027.yml\n+++ b/test/fixtures/rules/std_rule_cases/L027.yml\n@@ -220,3 +220,40 @@ test_pass_rowtype_with_join:\n configs:\n core:\n dialect: hive\n+\n+test_fail_column_name_not_found_in_table_aliases_bigquery:\n+ # qualified reference should actually exists in table aliases\n+ fail_str: |\n+ SELECT\n+ a.bar,\n+ b.foo,\n+ this_is.some_struct.id\n+ FROM\n+ a LEFT JOIN b ON TRUE\n+ configs:\n+ core:\n+ dialect: bigquery\n+\n+test_pass_column_name_is_a_struct_bigquery:\n+ # check structs work as expected\n+ pass_str: |\n+ SELECT\n+ a.bar,\n+ b.this_is.some_struct.id\n+ FROM\n+ a LEFT JOIN b ON TRUE\n+ configs:\n+ core:\n+ dialect: bigquery\n+\n+test_pass_column_name_from_unnest_bigquery:\n+ # Check that we allow an table alias come from UNNEST statement\n+ pass_str: |\n+ SELECT\n+ a.bar,\n+ e.foo\n+ FROM\n+ a LEFT JOIN UNEST(a.events) AS e\n+ configs:\n+ core:\n+ dialect: bigquery\ndiff --git a/test/rules/std_test.py b/test/rules/std_test.py\n--- a/test/rules/std_test.py\n+++ b/test/rules/std_test.py\n@@ -68,7 +68,7 @@\n ),\n (\"L016\", \"block_comment_errors_2.sql\", [(1, 85), (2, 86)]),\n # Column references\n- (\"L027\", \"column_references.sql\", [(1, 8)]),\n+ (\"L027\", \"column_references.sql\", [(1, 8), (1, 11)]),\n (\"L027\", \"column_references_bare_function.sql\", []),\n (\"L026\", \"column_references.sql\", [(1, 11)]),\n (\"L025\", \"column_references.sql\", [(2, 11)]),\n", "problem_statement": "BigQuery: Accessing `STRUCT` elements evades triggering L027\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nAccessing unreferenced `STRUCT` elements using BigQuery dot notation in a multi table query does not trigger L027.\n\n### Expected Behaviour\n\nL027 gets triggered.\n\n### Observed Behaviour\n\nL027 does not get triggered.\n\n### How to reproduce\n\n```sql\r\nSELECT\r\n t1.col1,\r\n t2.col2,\r\n events.id\r\nFROM t_table1 AS t1\r\nLEFT JOIN t_table2 AS t2\r\n ON TRUE\r\n```\n\n### Dialect\n\nBigQUery\n\n### Version\n\n`0.11.2` using online.sqlfluff.com\n\n### Configuration\n\nN/A\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "This is tricky.\r\n\r\nBasicaly L026 works to make sure qualified columns only use tables in the from clause. This doesn\u2019t really work for `STRUCT`s as impossible to know if it\u2019s a qualified column or a `STRUCT`, so is off by default for languages that support them - like BigQuery.\r\n\r\nL027 works to make sure columns are qualified for multi-table joins (i.e. have at least one dot). But it doesn\u2019t check the qualifiers are valid - that\u2019s L026\u2019s job, which as I say is off by default for BigQuery.", "created_at": "2022-04-04T20:29:42Z", "version": "0.11", "FAIL_TO_PASS": ["test/rules/std_test.py::test__rules__std_file[L027-column_references.sql-violations16]"], "PASS_TO_PASS": ["test/rules/std_test.py::test__rules__std_file[L001-indentation_errors.sql-violations0]", "test/rules/std_test.py::test__rules__std_file[L002-indentation_errors.sql-violations1]", "test/rules/std_test.py::test__rules__std_file[L003-indentation_errors.sql-violations2]", "test/rules/std_test.py::test__rules__std_file[L004-indentation_errors.sql-violations3]", "test/rules/std_test.py::test__rules__std_file[L005-whitespace_errors.sql-violations4]", "test/rules/std_test.py::test__rules__std_file[L019-whitespace_errors.sql-violations5]", "test/rules/std_test.py::test__rules__std_file[L008-whitespace_errors.sql-violations6]", "test/rules/std_test.py::test__rules__std_file[L006-operator_errors.sql-violations7]", "test/rules/std_test.py::test__rules__std_file[L039-operator_errors.sql-violations8]", "test/rules/std_test.py::test__rules__std_file[L007-operator_errors.sql-violations9]", "test/rules/std_test.py::test__rules__std_file[L006-operator_errors_negative.sql-violations10]", "test/rules/std_test.py::test__rules__std_file[L039-operator_errors_negative.sql-violations11]", "test/rules/std_test.py::test__rules__std_file[L003-indentation_error_hard.sql-violations12]", "test/rules/std_test.py::test__rules__std_file[L003-indentation_error_contained.sql-violations13]", "test/rules/std_test.py::test__rules__std_file[L016-block_comment_errors.sql-violations14]", "test/rules/std_test.py::test__rules__std_file[L016-block_comment_errors_2.sql-violations15]", "test/rules/std_test.py::test__rules__std_file[L027-column_references_bare_function.sql-violations17]", "test/rules/std_test.py::test__rules__std_file[L026-column_references.sql-violations18]", "test/rules/std_test.py::test__rules__std_file[L025-column_references.sql-violations19]", "test/rules/std_test.py::test__rules__std_file[L021-select_distinct_group_by.sql-violations20]", "test/rules/std_test.py::test__rules__std_file[L006-operator_errors_ignore.sql-violations21]", "test/rules/std_test.py::test__rules__std_file[L031-aliases_in_join_error.sql-violations22]", "test/rules/std_test.py::test__rules__std_file[L046-heavy_templating.sql-violations23]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict0]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict1]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict2]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict3]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict4]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict5]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict6]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict7]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict8]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict9]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict10]", "test/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict11]"], "environment_setup_commit": "2bdeb9354d33e3fb4dfd6782e1e1921939ecb55a"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-1733", "base_commit": "a1579a16b1d8913d9d7c7d12add374a290bcc78c", "patch": "diff --git a/src/sqlfluff/rules/L039.py b/src/sqlfluff/rules/L039.py\n--- a/src/sqlfluff/rules/L039.py\n+++ b/src/sqlfluff/rules/L039.py\n@@ -44,7 +44,9 @@ def _eval(self, context: RuleContext) -> Optional[List[LintResult]]:\n # This is to avoid indents\n if not prev_newline:\n prev_whitespace = seg\n- prev_newline = False\n+ # We won't set prev_newline to False, just for whitespace\n+ # in case there's multiple indents, inserted by other rule\n+ # fixes (see #1713)\n elif seg.is_type(\"comment\"):\n prev_newline = False\n prev_whitespace = None\n", "test_patch": "diff --git a/test/rules/std_L003_L036_L039_combo_test.py b/test/rules/std_L003_L036_L039_combo_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/rules/std_L003_L036_L039_combo_test.py\n@@ -0,0 +1,36 @@\n+\"\"\"Tests issue #1373 doesn't reoccur.\n+\n+The combination of L003 (incorrect indentation), L036 (select targets),\n+and L039 (unnecessary white space) can result in incorrect indentation.\n+\"\"\"\n+\n+import sqlfluff\n+\n+\n+def test__rules__std_L003_L036_L039():\n+ \"\"\"Verify that double indents don't flag L039.\"\"\"\n+ sql = \"\"\"\n+ WITH example AS (\n+ SELECT my_id,\n+ other_thing,\n+ one_more\n+ FROM\n+ my_table\n+ )\n+\n+ SELECT *\n+ FROM example\\n\"\"\"\n+ fixed_sql = \"\"\"\n+ WITH example AS (\n+ SELECT\n+ my_id,\n+ other_thing,\n+ one_more\n+ FROM\n+ my_table\n+ )\n+\n+ SELECT *\n+ FROM example\\n\"\"\"\n+ result = sqlfluff.fix(sql)\n+ assert result == fixed_sql\ndiff --git a/test/rules/std_L016_L36_combo.py b/test/rules/std_L016_L36_combo_test.py\nsimilarity index 100%\nrename from test/rules/std_L016_L36_combo.py\nrename to test/rules/std_L016_L36_combo_test.py\n", "problem_statement": "Extra space when first field moved to new line in a WITH statement\nNote, the query below uses a `WITH` statement. If I just try to fix the SQL within the CTE, this works fine.\r\n\r\nGiven the following SQL:\r\n\r\n```sql\r\nWITH example AS (\r\n SELECT my_id,\r\n other_thing,\r\n one_more\r\n FROM\r\n my_table\r\n)\r\n\r\nSELECT *\r\nFROM example\r\n```\r\n\r\n## Expected Behaviour\r\n\r\nafter running `sqlfluff fix` I'd expect (`my_id` gets moved down and indented properly):\r\n\r\n```sql\r\nWITH example AS (\r\n SELECT\r\n my_id,\r\n other_thing,\r\n one_more\r\n FROM\r\n my_table\r\n)\r\n\r\nSELECT *\r\nFROM example\r\n```\r\n\r\n## Observed Behaviour\r\n\r\nafter running `sqlfluff fix` we get (notice that `my_id` is indented one extra space)\r\n\r\n```sql\r\nWITH example AS (\r\n SELECT\r\n my_id,\r\n other_thing,\r\n one_more\r\n FROM\r\n my_table\r\n)\r\n\r\nSELECT *\r\nFROM example\r\n```\r\n\r\n## Steps to Reproduce\r\n\r\nNoted above. Create a file with the initial SQL and fun `sqfluff fix` on it.\r\n\r\n## Dialect\r\n\r\nRunning with default config.\r\n\r\n## Version\r\nInclude the output of `sqlfluff --version` along with your Python version\r\n\r\nsqlfluff, version 0.7.0\r\nPython 3.7.5\r\n\r\n## Configuration\r\n\r\nDefault config.\r\n\n", "hints_text": "Does running `sqlfluff fix` again correct the SQL?\n@tunetheweb yes, yes it does. Is that something that the user is supposed to do (run it multiple times) or is this indeed a bug?\nIdeally not, but there are some circumstances where it\u2019s understandable that would happen. This however seems an easy enough example where it should not happen.\nThis appears to be a combination of rules L036, L003, and L039 not playing nicely together.\r\n\r\nThe original error is rule L036 and it produces this:\r\n\r\n```sql\r\nWITH example AS (\r\n SELECT\r\nmy_id,\r\n other_thing,\r\n one_more\r\n FROM\r\n my_table\r\n)\r\n\r\nSELECT *\r\nFROM example\r\n```\r\n\r\nThat is, it moves the `my_id` down to the newline but does not even try to fix the indentation.\r\n\r\nThen we have another run through and L003 spots the lack of indentation and fixes it by adding the first set of whitespace:\r\n\r\n```sql\r\nWITH example AS (\r\n SELECT\r\n my_id,\r\n other_thing,\r\n one_more\r\n FROM\r\n my_table\r\n)\r\n\r\nSELECT *\r\nFROM example\r\n```\r\n\r\nThen we have another run through and L003 spots that there still isn't enough indentation and fixes it by adding the second set of whitespace:\r\n\r\n```sql\r\nWITH example AS (\r\n SELECT\r\n my_id,\r\n other_thing,\r\n one_more\r\n FROM\r\n my_table\r\n)\r\n\r\nSELECT *\r\nFROM example\r\n```\r\n\r\nAt this point we're all good.\r\n\r\nHowever then L039 has a look. It never expects two sets of whitespace following a new line and is specifically coded to only assume one set of spaces (which it normally would be if the other rules hadn't interfered as it would be parsed as one big space), so it think's the second set is too much indentation, so it replaces it with a single space.\r\n\r\nThen another run and L003 and the whitespace back in so we end up with two indents, and a single space.\r\n\r\nLuckily the fix is easier than that explanation. PR coming up...\r\n\r\n", "created_at": "2021-10-22T18:23:33Z", "version": "0.6", "FAIL_TO_PASS": ["test/rules/std_L003_L036_L039_combo_test.py::test__rules__std_L003_L036_L039"], "PASS_TO_PASS": ["test/rules/std_L016_L36_combo_test.py::test__rules__std_L016_L036_long_line_lint", "test/rules/std_L016_L36_combo_test.py::test__rules__std_L016_L036_long_line_fix", "test/rules/std_L016_L36_combo_test.py::test__rules__std_L016_L036_long_line_fix2"], "environment_setup_commit": "67023b85c41d23d6c6d69812a41b207c4f8a9331"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3648", "base_commit": "e56fc6002dac0fb7eb446d58bd8aa7a839908535", "patch": "diff --git a/src/sqlfluff/core/templaters/slicers/tracer.py b/src/sqlfluff/core/templaters/slicers/tracer.py\n--- a/src/sqlfluff/core/templaters/slicers/tracer.py\n+++ b/src/sqlfluff/core/templaters/slicers/tracer.py\n@@ -206,7 +206,8 @@ def __init__(self, raw_str: str, env: Environment):\n \n # Internal bookkeeping\n self.slice_id: int = 0\n- self.inside_set_or_macro: bool = False # {% set %} or {% macro %}\n+ # {% set %} or {% macro %} or {% call %}\n+ self.inside_set_macro_or_call: bool = False\n self.inside_block = False # {% block %}\n self.stack: List[int] = []\n self.idx_raw: int = 0\n@@ -236,12 +237,18 @@ def slice_info_for_literal(self, length, prefix=\"\") -> RawSliceInfo:\n unique_alternate_id, alternate_code, inside_block=self.inside_block\n )\n \n- def update_inside_set_or_macro_or_block(\n- self, block_type: str, trimmed_parts: List[str]\n- ) -> None:\n- \"\"\"Based on block tag, update whether we're in a set/macro section.\"\"\"\n+ def update_inside_set_call_macro_or_block(\n+ self,\n+ block_type: str,\n+ trimmed_parts: List[str],\n+ m_open: Optional[regex.Match],\n+ m_close: Optional[regex.Match],\n+ tag_contents: List[str],\n+ ) -> Optional[RawSliceInfo]:\n+ \"\"\"Based on block tag, update whether in a set/call/macro/block section.\"\"\"\n if block_type == \"block_start\" and trimmed_parts[0] in (\n \"block\",\n+ \"call\",\n \"macro\",\n \"set\",\n ):\n@@ -274,16 +281,22 @@ def update_inside_set_or_macro_or_block(\n if trimmed_parts[0] == \"block\":\n self.inside_block = True\n else:\n- self.inside_set_or_macro = True\n+ result = None\n+ if trimmed_parts[0] == \"call\":\n+ assert m_open and m_close\n+ result = self.track_call(m_open, m_close, tag_contents)\n+ self.inside_set_macro_or_call = True\n+ return result\n else:\n raise # pragma: no cover\n elif block_type == \"block_end\":\n- if trimmed_parts[0] in (\"endmacro\", \"endset\"):\n- # Exiting a set or macro.\n- self.inside_set_or_macro = False\n+ if trimmed_parts[0] in (\"endcall\", \"endmacro\", \"endset\"):\n+ # Exiting a set or macro or block.\n+ self.inside_set_macro_or_call = False\n elif trimmed_parts[0] == \"endblock\":\n # Exiting a {% block %} block.\n self.inside_block = False\n+ return None\n \n def make_raw_slice_info(\n self,\n@@ -292,7 +305,7 @@ def make_raw_slice_info(\n inside_block: bool = False,\n ) -> RawSliceInfo:\n \"\"\"Create RawSliceInfo as given, or \"empty\" if in set/macro block.\"\"\"\n- if not self.inside_set_or_macro:\n+ if not self.inside_set_macro_or_call:\n return RawSliceInfo(unique_alternate_id, alternate_code, [], inside_block)\n else:\n return RawSliceInfo(None, None, [], False)\n@@ -355,6 +368,8 @@ def analyze(self, make_template: Callable[[str], Template]) -> JinjaTracer:\n # raw_end and raw_begin behave a little differently in\n # that the whole tag shows up in one go rather than getting\n # parts of the tag at a time.\n+ m_open = None\n+ m_close = None\n if elem_type.endswith(\"_end\") or elem_type == \"raw_begin\":\n block_type = self.block_types[elem_type]\n block_subtype = None\n@@ -376,7 +391,11 @@ def analyze(self, make_template: Callable[[str], Template]) -> JinjaTracer:\n raw_slice_info = self.track_templated(\n m_open, m_close, tag_contents\n )\n- self.update_inside_set_or_macro_or_block(block_type, tag_contents)\n+ raw_slice_info_temp = self.update_inside_set_call_macro_or_block(\n+ block_type, tag_contents, m_open, m_close, tag_contents\n+ )\n+ if raw_slice_info_temp:\n+ raw_slice_info = raw_slice_info_temp\n m_strip_right = regex.search(\n r\"\\s+$\", raw, regex.MULTILINE | regex.DOTALL\n )\n@@ -428,6 +447,7 @@ def analyze(self, make_template: Callable[[str], Template]) -> JinjaTracer:\n slice_idx = len(self.raw_sliced) - 1\n self.idx_raw += len(str_buff)\n if block_type.startswith(\"block\"):\n+ self.track_block_start(block_type, tag_contents[0])\n self.track_block_end(block_type, tag_contents[0])\n self.update_next_slice_indices(\n slice_idx, block_type, tag_contents[0]\n@@ -457,6 +477,21 @@ def track_templated(\n )\n return self.make_raw_slice_info(unique_alternate_id, alternate_code)\n \n+ def track_call(\n+ self, m_open: regex.Match, m_close: regex.Match, tag_contents: List[str]\n+ ):\n+ \"\"\"Set up tracking for \"{% call ... %}\".\"\"\"\n+ unique_alternate_id = self.next_slice_id()\n+ open_ = m_open.group(1)\n+ close_ = m_close.group(1)\n+ # Here, we still need to evaluate the original tag contents, e.g. in\n+ # case it has intentional side effects, but also return a slice ID\n+ # for tracking.\n+ alternate_code = (\n+ f\"\\0{unique_alternate_id} {open_} \" f\"{''.join(tag_contents)} {close_}\"\n+ )\n+ return self.make_raw_slice_info(unique_alternate_id, alternate_code)\n+\n def track_literal(self, raw: str, block_idx: int) -> None:\n \"\"\"Set up tracking for a Jinja literal.\"\"\"\n self.raw_sliced.append(\n@@ -517,6 +552,20 @@ def extract_tag_contents(\n trimmed_parts = trimmed_content.split()\n return trimmed_parts\n \n+ def track_block_start(self, block_type: str, tag_name: str) -> None:\n+ \"\"\"On starting a 'call' block, set slice_type to \"templated\".\"\"\"\n+ if block_type == \"block_start\" and tag_name == \"call\":\n+ # Replace RawSliceInfo for this slice with one that has block_type\n+ # \"templated\".\n+ old_raw_file_slice = self.raw_sliced[-1]\n+ self.raw_sliced[-1] = old_raw_file_slice._replace(slice_type=\"templated\")\n+\n+ # Move existing raw_slice_info entry since it's keyed by RawFileSlice.\n+ self.raw_slice_info[self.raw_sliced[-1]] = self.raw_slice_info[\n+ old_raw_file_slice\n+ ]\n+ del self.raw_slice_info[old_raw_file_slice]\n+\n def track_block_end(self, block_type: str, tag_name: str) -> None:\n \"\"\"On ending a 'for' or 'if' block, set up tracking.\"\"\"\n if block_type == \"block_end\" and tag_name in (\n@@ -553,7 +602,7 @@ def update_next_slice_indices(\n \"endfor\",\n \"endif\",\n ):\n- if not self.inside_set_or_macro:\n+ if not self.inside_set_macro_or_call:\n # Record potential forward jump over this block.\n self.raw_slice_info[\n self.raw_sliced[self.stack[-1]]\n", "test_patch": "diff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -697,6 +697,14 @@ def test__templater_jinja_slice_template(test, result):\n ] == result\n \n \n+def _statement(*args, **kwargs):\n+ return \"_statement\"\n+\n+\n+def _load_result(*args, **kwargs):\n+ return \"_load_result\"\n+\n+\n @pytest.mark.parametrize(\n \"raw_file,override_context,result\",\n [\n@@ -1118,6 +1126,32 @@ def test__templater_jinja_slice_template(test, result):\n (\"literal\", slice(131, 132, None), slice(88, 89, None)),\n ],\n ),\n+ (\n+ \"\"\"{{ statement('variables', fetch_result=true) }}\n+\"\"\",\n+ dict(\n+ statement=_statement,\n+ load_result=_load_result,\n+ ),\n+ [\n+ (\"templated\", slice(0, 47, None), slice(0, 10, None)),\n+ (\"literal\", slice(47, 48, None), slice(10, 11, None)),\n+ ],\n+ ),\n+ (\n+ \"\"\"{% call statement('variables', fetch_result=true) %}select 1 as test{% endcall %}\n+\"\"\",\n+ dict(\n+ statement=_statement,\n+ load_result=_load_result,\n+ ),\n+ [\n+ (\"templated\", slice(0, 52, None), slice(0, 10, None)),\n+ (\"literal\", slice(52, 68, None), slice(10, 10, None)),\n+ (\"block_end\", slice(68, 81, None), slice(10, 10, None)),\n+ (\"literal\", slice(81, 82, None), slice(10, 11, None)),\n+ ],\n+ ),\n ],\n )\n def test__templater_jinja_slice_file(raw_file, override_context, result, caplog):\n", "problem_statement": "dbt & JinjaTracer results in passing invalid query to database (was: DBT Call statement() block causes invalid query generated)\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nWhen using the call statement() to run a query during compile time, the query generated is garbled causing the following sql error:\r\n```\r\n{% call statement('variables', fetch_result=true) %}\r\n\r\nselect 1 as test;\r\n\r\n{% endcall %}\r\n\r\n{% set test = load_result('variables')['table'].columns.TEST.values()[0] %}\r\n```\r\n\r\nThis results in the following error:\r\n\r\ndbt.exceptions.DatabaseException: Database Error\r\n 001003 (42000): SQL compilation error:\r\n syntax error line 1 at position 0 unexpected '0'.\r\n\r\nThe query ran looks like this when looking at the query runner history in snowflake:\r\n\r\n```\r\n\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a_0\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a_8\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a\u263a_0\r\n```\r\n\r\nWhereas it should show:\r\n```\r\nselect 1 as test;\r\n```\n\n### Expected Behaviour\n\nExpected that the query runs properly.\n\n### Observed Behaviour\n\n```\r\n=== [dbt templater] Compiling dbt project...\r\n=== [dbt templater] Project Compiled.\r\nTraceback (most recent call last):\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/adapters/snowflake/connections.py\", line 219, in exception_handler\r\n yield\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/adapters/sql/connections.py\", line 70, in add_query\r\n cursor.execute(sql, bindings)\r\n File \"/usr/local/lib/python3.9/site-packages/snowflake/connector/cursor.py\", line 794, in execute\r\n Error.errorhandler_wrapper(self.connection, self, error_class, errvalue)\r\n File \"/usr/local/lib/python3.9/site-packages/snowflake/connector/errors.py\", line 273, in errorhandler_wrapper\r\n handed_over = Error.hand_to_other_handler(\r\n File \"/usr/local/lib/python3.9/site-packages/snowflake/connector/errors.py\", line 328, in hand_to_other_handler\r\n cursor.errorhandler(connection, cursor, error_class, error_value)\r\n File \"/usr/local/lib/python3.9/site-packages/snowflake/connector/errors.py\", line 207, in default_errorhandler\r\n raise error_class(\r\nsnowflake.connector.errors.ProgrammingError: 001003 (42000): SQL compilation error:\r\nsyntax error line 1 at position 0 unexpected '0'.\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/usr/local/bin/sqlfluff\", line 8, in <module>\r\n sys.exit(cli())\r\n File \"/usr/local/lib/python3.9/site-packages/click/core.py\", line 1130, in __call__\r\n return self.main(*args, **kwargs)\r\n File \"/usr/local/lib/python3.9/site-packages/click/core.py\", line 1055, in main\r\n rv = self.invoke(ctx)\r\n File \"/usr/local/lib/python3.9/site-packages/click/core.py\", line 1657, in invoke\r\n return _process_result(sub_ctx.command.invoke(sub_ctx))\r\n File \"/usr/local/lib/python3.9/site-packages/click/core.py\", line 1404, in invoke\r\n return ctx.invoke(self.callback, **ctx.params)\r\n File \"/usr/local/lib/python3.9/site-packages/click/core.py\", line 760, in invoke\r\n return __callback(*args, **kwargs)\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff/cli/commands.py\", line 1008, in parse\r\n parsed_strings = list(\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 1171, in parse_path\r\n yield self.parse_string(\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 835, in parse_string\r\n rendered = self.render_string(in_str, fname, config, encoding)\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff/core/linter/linter.py\", line 784, in render_string\r\n templated_file, templater_violations = self.templater.process(\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff/core/templaters/base.py\", line 47, in _wrapped\r\n return func(self, in_str=in_str, fname=fname, config=config, **kwargs)\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff_templater_dbt/templater.py\", line 331, in process\r\n processed_result = self._unsafe_process(fname_absolute_path, in_str, config)\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff_templater_dbt/templater.py\", line 552, in _unsafe_process\r\n raw_sliced, sliced_file, templated_sql = self.slice_file(\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff/core/templaters/jinja.py\", line 462, in slice_file\r\n trace = tracer.trace(append_to_templated=kwargs.pop(\"append_to_templated\", \"\"))\r\n File \"/usr/local/lib/python3.9/site-packages/sqlfluff/core/templaters/slicers/tracer.py\", line 77, in trace\r\n trace_template_output = trace_template.render()\r\n File \"/usr/local/lib/python3.9/site-packages/jinja2/environment.py\", line 1090, in render\r\n self.environment.handle_exception()\r\n File \"/usr/local/lib/python3.9/site-packages/jinja2/environment.py\", line 832, in handle_exception\r\n reraise(*rewrite_traceback_stack(source=source))\r\n File \"/usr/local/lib/python3.9/site-packages/jinja2/_compat.py\", line 28, in reraise\r\n raise value.with_traceback(tb)\r\n File \"<template>\", line 16, in top-level template code\r\n File \"/usr/local/lib/python3.9/site-packages/jinja2/sandbox.py\", line 462, in call\r\n return __context.call(__obj, *args, **kwargs)\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/clients/jinja.py\", line 321, in __call__\r\n return self.call_macro(*args, **kwargs)\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/clients/jinja.py\", line 248, in call_macro\r\n return macro(*args, **kwargs)\r\n File \"/usr/local/lib/python3.9/site-packages/jinja2/runtime.py\", line 679, in _invoke\r\n rv = self._func(*arguments)\r\n File \"<template>\", line 10, in template\r\n File \"/usr/local/lib/python3.9/site-packages/jinja2/sandbox.py\", line 462, in call\r\n return __context.call(__obj, *args, **kwargs)\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/adapters/base/impl.py\", line 235, in execute\r\n return self.connections.execute(sql=sql, auto_begin=auto_begin, fetch=fetch)\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/adapters/sql/connections.py\", line 122, in execute\r\n _, cursor = self.add_query(sql, auto_begin)\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/adapters/snowflake/connections.py\", line 458, in add_query\r\n connection, cursor = super().add_query(\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/adapters/sql/connections.py\", line 78, in add_query\r\n return connection, cursor\r\n File \"/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py\", line 137, in __exit__\r\n self.gen.throw(typ, value, traceback)\r\n File \"/usr/local/lib/python3.9/site-packages/dbt/adapters/snowflake/connections.py\", line 238, in exception_handler\r\n raise DatabaseException(msg)\r\ndbt.exceptions.DatabaseException: Database Error\r\n 001003 (42000): SQL compilation error:\r\n syntax error line 1 at position 0 unexpected '0'.\r\n```\n\n### How to reproduce\n\nUse the statement() block described here:\r\nhttps://docs.getdbt.com/reference/dbt-jinja-functions/statement-blocks\r\n\r\n\n\n### Dialect\n\nSnowflake\n\n### Version\n\n1.2.0 with the dbt formatter\n\n### Configuration\n\n```\r\n[sqlfluff]\r\n# verbose is an integer (0-2) indicating the level of log output\r\nverbose = 2\r\n# Turn off color formatting of output\r\nnocolor = False\r\n# Supported dialects https://docs.sqlfluff.com/en/stable/dialects.html\r\n# Or run 'sqlfluff dialects'\r\ndialect = snowflake\r\n# One of [raw|jinja|python|placeholder]\r\ntemplater = dbt\r\n# Comma separated list of rules to check, default to all\r\nrules = all\r\n# Comma separated list of rules to exclude, or None\r\nexclude_rules = None\r\n# The depth to recursively parse to (0 for unlimited)\r\nrecurse = 0\r\n# Below controls SQLFluff output, see max_line_length for SQL output\r\noutput_line_length = 80\r\n# Number of passes to run before admitting defeat\r\nrunaway_limit = 10\r\n# Ignore errors by category (one or more of the following, separated by commas: lexing,linting,parsing,templating)\r\nignore = None\r\n# Ignore linting errors found within sections of code coming directly from\r\n# templated code (e.g. from within Jinja curly braces. Note that it does not\r\n# ignore errors from literal code found within template loops.\r\nignore_templated_areas = True\r\n# can either be autodetect or a valid encoding e.g. utf-8, utf-8-sig\r\nencoding = autodetect\r\n# Ignore inline overrides (e.g. to test if still required)\r\ndisable_noqa = False\r\n# Comma separated list of file extensions to lint\r\n# NB: This config will only apply in the root folder\r\nsql_file_exts = .sql,.sql.j2,.dml,.ddl\r\n# Allow fix to run on files, even if they contain parsing errors\r\n# Note altering this is NOT RECOMMENDED as can corrupt SQL\r\nfix_even_unparsable = False\r\n# Very large files can make the parser effectively hang.\r\n# This limit skips files over a certain character length\r\n# and warns the user what has happened.\r\n# Set this to 0 to disable.\r\nlarge_file_skip_char_limit = 20000\r\n\r\n[sqlfluff:indentation]\r\n# See https://docs.sqlfluff.com/en/stable/indentation.html\r\nindented_joins = False\r\nindented_ctes = False\r\nindented_using_on = True\r\nindented_on_contents = True\r\ntemplate_blocks_indent = True\r\n\r\n[sqlfluff:templater]\r\nunwrap_wrapped_queries = True\r\n\r\n[sqlfluff:templater:jinja]\r\napply_dbt_builtins = True\r\nload_macros_from_path = macros/\r\n\r\n[sqlfluff:templater:jinja:macros]\r\n# Macros provided as builtins for dbt projects\r\ndbt_ref = {% macro ref(model_ref) %}{{model_ref}}{% endmacro %}\r\ndbt_source = {% macro source(source_name, table) %}{{source_name}}_{{table}}{% endmacro %}\r\ndbt_config = {% macro config() %}{% for k in kwargs %}{% endfor %}{% endmacro %}\r\ndbt_var = {% macro var(variable, default='') %}item{% endmacro %}\r\ndbt_is_incremental = {% macro is_incremental() %}True{% endmacro %}\r\n\r\n[sqlfluff:templater:dbt]\r\nproject_dir = ./\r\n\r\n# Some rules can be configured directly from the config common to other rules\r\n[sqlfluff:rules]\r\ntab_space_size = 4\r\nmax_line_length = 120\r\nindent_unit = space\r\ncomma_style = trailing\r\nallow_scalar = True\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = all\r\n\r\n# Some rules have their own specific config\r\n[sqlfluff:rules:L003]\r\nhanging_indents = True\r\n\r\n[sqlfluff:rules:L007]\r\noperator_new_lines = after\r\n\r\n[sqlfluff:rules:L010]\r\n# Keywords\r\ncapitalisation_policy = lower\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L011]\r\n# Aliasing preference for tables\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:L012]\r\n# Aliasing preference for columns\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:L014]\r\n# Unquoted identifiers\r\nextended_capitalisation_policy = lower\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L016]\r\n# Line length\r\nignore_comment_lines = False\r\nignore_comment_clauses = False\r\n\r\n[sqlfluff:rules:L027]\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L026]\r\n# References must be in FROM clause\r\n# Disabled for some dialects (e.g. bigquery)\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L028]\r\n# References must be consistently used\r\n# Disabled for some dialects (e.g. bigquery)\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L029]\r\n# Keywords should not be used as identifiers.\r\nunquoted_identifiers_policy = aliases\r\nquoted_identifiers_policy = none\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L030]\r\n# Function names\r\nextended_capitalisation_policy = lower\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L031]\r\n# Avoid table aliases in from clauses and join conditions.\r\n# Disabled for some dialects (e.g. bigquery)\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L036]\r\nwildcard_policy = single\r\n\r\n[sqlfluff:rules:L038]\r\n# Trailing commas\r\nselect_clause_trailing_comma = forbid\r\n\r\n[sqlfluff:rules:L040]\r\n# Null & Boolean Literals\r\ncapitalisation_policy = consistent\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L042]\r\n# By default, allow subqueries in from clauses, but not join clauses\r\nforbid_subquery_in = join\r\n\r\n[sqlfluff:rules:L047]\r\n# Consistent syntax to count all rows\r\nprefer_count_1 = False\r\nprefer_count_0 = False\r\n\r\n[sqlfluff:rules:L051]\r\n# Fully qualify JOIN clause\r\nfully_qualify_join_types = inner\r\n\r\n[sqlfluff:rules:L052]\r\n# Semi-colon formatting approach\r\nmultiline_newline = False\r\nrequire_final_semicolon = False\r\n\r\n[sqlfluff:rules:L054]\r\n# GROUP BY/ORDER BY column references\r\ngroup_by_and_order_by_style = consistent\r\n\r\n[sqlfluff:rules:L057]\r\n# Special characters in identifiers\r\nunquoted_identifiers_policy = all\r\nquoted_identifiers_policy = all\r\nallow_space_in_identifier = False\r\nadditional_allowed_characters = \"\"\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L059]\r\n# Policy on quoted and unquoted identifiers\r\nprefer_quoted_identifiers = False\r\nignore_words = None\r\nignore_words_regex = None\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L062]\r\n# Comma separated list of blocked words that should not be used\r\nblocked_words = None\r\nblocked_regex = None\r\n\r\n[sqlfluff:rules:L063]\r\n# Data Types\r\nextended_capitalisation_policy = consistent\r\n# Comma separated list of words to ignore for this rule\r\nignore_words = None\r\nignore_words_regex = None\r\n\r\n[sqlfluff:rules:L064]\r\n# Consistent usage of preferred quotes for quoted literals\r\npreferred_quoted_literal_style = consistent\r\n# Disabled for dialects that do not support single and double quotes for quoted literals (e.g. Postgres)\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L066]\r\nmin_alias_length = None\r\nmax_alias_length = None\r\n```\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "This is a curious error. Can you run `dbt compile` and post what dbt expects the compiled form of this statement to be? I worry that while a query is run at compile time, this query otherwise compiles to an empty file - and that could be causing issues.\ndbt compile doesn't output the call statement blocks since they're interpreted at runtime; however, we can see the output ran on the snowflake query history.\r\n\r\nSource test.sql\r\n```\r\n{% call statement('variables', fetch_result=true) %}\r\n\r\n select 1\r\n\r\n{% endcall %}\r\n\r\nwith source (\r\n select 1\r\n)\r\n\r\nselect * from source\r\n```\r\n\r\nCompiled output of test.sql\r\n```\r\n\r\n\r\nwith source (\r\n select 1\r\n)\r\n\r\nselect * from source\r\n```\nThe dbt [documentation](https://docs.getdbt.com/reference/dbt-jinja-functions/statement-blocks) mentions re: `statement()`:\r\n\r\n>Volatile API\r\n>While the statement and load_result setup works for now, we intend to improve this interface in the future. If you have questions or suggestions, please let us know in GitHub or on Slack.\r\n\r\nSo this might be a relatively lower priority issue. IIUC, it may also be dbt specific (not affecting the `jinja` templater).\r\n\r\n\nI did some preliminary investigation. IIUC, SQLFluff's `JinjaTracer` should treat this:\r\n```\r\n{% call statement('variables', fetch_result=true) %}\r\n\r\nselect 1 as test;\r\n\r\n{% endcall %}\r\n```\r\n\r\nlike this:\r\n```\r\n{{ statement('variables', fetch_result=true) }}\r\n```\r\n\r\nIn both cases, whatever `statement()` returns is passed through to the template output. I think this will be pretty straightforward, other than the usual trickiness of working on this complex area of the code.", "created_at": "2022-07-21T22:42:19Z", "version": "1.2", "FAIL_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%"], "PASS_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[set_multiple_variables_and_define_macro]", "test/core/templaters/jinja_test.py::test_templater_set_block_handling", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_dynamic_variable_no_violations", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_config-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_is_incremental-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_ref-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_source-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_this-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_o_config_override_dbt_builtins/override_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_p_disable_dbt_builtins/disable_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_q_multiple_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_large_file_check"], "environment_setup_commit": "388dd01e05c7dcb880165c7241ed4027d9d0171e"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4043", "base_commit": "5f639444ddf4afe8b4f0d2c7f0d4ac0b976930de", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -1116,6 +1116,68 @@ def parse(\n sys.exit(EXIT_SUCCESS)\n \n \[email protected]()\n+@common_options\n+@core_options\[email protected](\"path\", nargs=1, type=click.Path(allow_dash=True))\n+def render(\n+ path: str,\n+ bench: bool,\n+ logger: Optional[logging.Logger] = None,\n+ extra_config_path: Optional[str] = None,\n+ ignore_local_config: bool = False,\n+ **kwargs,\n+) -> None:\n+ \"\"\"Render SQL files and just spit out the result.\n+\n+ PATH is the path to a sql file. This should be either a single file\n+ file ('path/to/file.sql') or a single ('-') character to indicate reading\n+ from *stdin*.\n+ \"\"\"\n+ c = get_config(\n+ extra_config_path, ignore_local_config, require_dialect=False, **kwargs\n+ )\n+ # We don't want anything else to be logged if we want json or yaml output\n+ # unless we're writing to a file.\n+ output_stream = make_output_stream(c, None, None)\n+ lnt, formatter = get_linter_and_formatter(c, output_stream)\n+ verbose = c.get(\"verbose\")\n+\n+ progress_bar_configuration.disable_progress_bar = True\n+\n+ formatter.dispatch_config(lnt)\n+\n+ # Set up logging.\n+ set_logging_level(\n+ verbosity=verbose,\n+ formatter=formatter,\n+ logger=logger,\n+ stderr_output=False,\n+ )\n+\n+ # handle stdin if specified via lone '-'\n+ with PathAndUserErrorHandler(formatter, path):\n+ if \"-\" == path:\n+ raw_sql = sys.stdin.read()\n+ fname = \"stdin\"\n+ file_config = lnt.config\n+ else:\n+ raw_sql, file_config, _ = lnt.load_raw_file_and_config(path, lnt.config)\n+ fname = path\n+\n+ # Get file specific config\n+ file_config.process_raw_file_for_config(raw_sql)\n+ rendered = lnt.render_string(raw_sql, fname, file_config, \"utf8\")\n+\n+ if rendered.templater_violations:\n+ for v in rendered.templater_violations:\n+ click.echo(formatter.format_violation(v))\n+ sys.exit(EXIT_FAIL)\n+ else:\n+ click.echo(rendered.templated_file.templated_str)\n+ sys.exit(EXIT_SUCCESS)\n+\n+\n # This \"__main__\" handler allows invoking SQLFluff using \"python -m\", which\n # simplifies the use of cProfile, e.g.:\n # python -m cProfile -s cumtime -m sqlfluff.cli.commands lint slow_file.sql\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -110,7 +110,7 @@ def rule_tuples(self) -> List[RuleTuple]:\n # These are the building blocks of the linting process.\n \n @staticmethod\n- def _load_raw_file_and_config(\n+ def load_raw_file_and_config(\n fname: str, root_config: FluffConfig\n ) -> Tuple[str, FluffConfig, str]:\n \"\"\"Load a raw file and the associated config.\"\"\"\n@@ -837,7 +837,7 @@ def render_string(\n def render_file(self, fname: str, root_config: FluffConfig) -> RenderedFile:\n \"\"\"Load and render a file with relevant config.\"\"\"\n # Load the raw file.\n- raw_file, config, encoding = self._load_raw_file_and_config(fname, root_config)\n+ raw_file, config, encoding = self.load_raw_file_and_config(fname, root_config)\n # Render the file\n return self.render_string(raw_file, fname, config, encoding)\n \n@@ -1211,7 +1211,7 @@ def parse_path(\n self.formatter.dispatch_path(path)\n # Load the file with the config and yield the result.\n try:\n- raw_file, config, encoding = self._load_raw_file_and_config(\n+ raw_file, config, encoding = self.load_raw_file_and_config(\n fname, self.config\n )\n except SQLFluffSkipFile as s:\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -31,6 +31,7 @@\n parse,\n dialects,\n get_config,\n+ render,\n )\n from sqlfluff.core.rules import BaseRule, LintFix, LintResult\n from sqlfluff.core.parser.segments.raw import CommentSegment\n@@ -250,6 +251,15 @@ def test__cli__command_lint_stdin(command):\n invoke_assert_code(args=[lint, (\"--dialect=ansi\",) + command], cli_input=sql)\n \n \n+def test__cli__command_render_stdin():\n+ \"\"\"Check render on a simple script using stdin.\"\"\"\n+ with open(\"test/fixtures/cli/passing_a.sql\") as test_file:\n+ sql = test_file.read()\n+ result = invoke_assert_code(args=[render, (\"--dialect=ansi\", \"-\")], cli_input=sql)\n+ # Check we get back out the same file we input.\n+ assert result.output.startswith(sql)\n+\n+\n @pytest.mark.parametrize(\n \"command\",\n [\n@@ -263,6 +273,13 @@ def test__cli__command_lint_stdin(command):\n \"L051\",\n ],\n ),\n+ # Basic render\n+ (\n+ render,\n+ [\n+ \"test/fixtures/cli/passing_b.sql\",\n+ ],\n+ ),\n # Original tests from test__cli__command_lint\n (lint, [\"-n\", \"test/fixtures/cli/passing_a.sql\"]),\n (lint, [\"-n\", \"-v\", \"test/fixtures/cli/passing_a.sql\"]),\n@@ -474,8 +491,15 @@ def test__cli__command_lint_parse(command):\n (\n (\n lint,\n- [\"test/fixtures/cli/unknown_jinja_tag/test.sql\", \"-vvvvvvv\"],\n- \"y\",\n+ [\"test/fixtures/cli/unknown_jinja_tag/test.sql\"],\n+ ),\n+ 1,\n+ ),\n+ # Test render fail\n+ (\n+ (\n+ render,\n+ [\"test/fixtures/cli/fail_many.sql\"],\n ),\n 1,\n ),\n@@ -1790,3 +1814,41 @@ def test__cli__multiple_files__fix_multiple_errors_show_errors():\n \n # Assert that they are sorted in alphabetical order\n assert unfix_err_log.index(indent_pass_msg) < unfix_err_log.index(multi_fail_msg)\n+\n+\n+def test__cli__render_fail():\n+ \"\"\"Basic how render fails.\"\"\"\n+ expected_render_output = (\n+ \"L: 3 | P: 8 | TMP | Undefined jinja template \" \"variable: 'something'\"\n+ )\n+\n+ result = invoke_assert_code(\n+ ret_code=1,\n+ args=[\n+ render,\n+ [\n+ \"test/fixtures/cli/fail_many.sql\",\n+ ],\n+ ],\n+ )\n+ # Check whole output. The replace command just accounts for\n+ # cross platform testing.\n+ assert result.output.replace(\"\\\\\", \"/\").startswith(expected_render_output)\n+\n+\n+def test__cli__render_pass():\n+ \"\"\"Basic how render works.\"\"\"\n+ expected_render_output = \"SELECT 56 FROM sch1.tbl2\"\n+\n+ result = invoke_assert_code(\n+ ret_code=0,\n+ args=[\n+ render,\n+ [\n+ \"test/fixtures/templater/jinja_a/jinja.sql\",\n+ ],\n+ ],\n+ )\n+ # Check whole output. The replace command just accounts for\n+ # cross platform testing.\n+ assert result.output.replace(\"\\\\\", \"/\").startswith(expected_render_output)\ndiff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -90,7 +90,7 @@ def test__linter__skip_large_bytes(filesize, raises_skip):\n # First check the function directly\n if raises_skip:\n with pytest.raises(SQLFluffSkipFile) as excinfo:\n- Linter._load_raw_file_and_config(\n+ Linter.load_raw_file_and_config(\n \"test/fixtures/linter/indentation_errors.sql\", config\n )\n assert \"Skipping\" in str(excinfo.value)\n", "problem_statement": "add ability to render the compiled sql\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nIt would be nice to see the compiled sql in which any templates are rendered. I would be happy to work on this but it may be a struggle and would need some guidance.\n\n### Use case\n\n It would help debug linting errors around jinja templates.\r\nIt would also make it easier to copy and use the query in the bigquery ui, for example. We process our queries through Airflow so currently I can start a dag run and look at the rendered template to get this effect. That's not very efficient though :)\r\n\n\n### Dialect\n\nWe use bigquery but this could apply to all dialects.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [X] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "If you're interested in contributing this feature, I suggest starting by looking at the existing `parse` command, implemented [here](https://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/cli/commands.py#L938). I think this new command will be pretty similar except for the output format.\r\n\r\nI think `sqlfluff render` is a good name for it. \ud83d\udc4d\nIf you have questions, feel free to drop them here or ask in the \"contributing\" Slack channel.", "created_at": "2022-11-08T14:56:55Z", "version": "1.3", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass", "test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__skip_large_bytes[0-False]", "test/core/linter_test.py::test__linter__skip_large_bytes[5-True]", "test/core/linter_test.py::test__linter__skip_large_bytes[2000-False]", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__sqlfluffignore_current_directory", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__get_runner_processes[512-1-1]", "test/core/linter_test.py::test__linter__get_runner_processes[512-0-512]", "test/core/linter_test.py::test__linter__get_runner_processes[512--12-500]", "test/core/linter_test.py::test__linter__get_runner_processes[512-5-5]", "test/core/linter_test.py::test__linter__get_runner_processes[1--1-1]", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_parse_noqa[Inline", "test/core/linter_test.py::test_parse_noqa_no_dups", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[2_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_glob_ignore]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_linter_noqa_template_errors", "test/core/linter_test.py::test_linter_noqa_prs", "test/core/linter_test.py::test_linter_noqa_tmp", "test/core/linter_test.py::test_linter_noqa_disable", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]", "test/core/linter_test.py::test_advanced_api_methods", "test/core/linter_test.py::test_normalise_newlines", "test/core/linter_test.py::test_require_match_parse_grammar"], "PASS_TO_PASS": [], "environment_setup_commit": "dc59c2a5672aacedaf91f0e6129b467eefad331b"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2509", "base_commit": "5c104a71c54ce4ed83401d62dfaaa86be38e5aff", "patch": "diff --git a/src/sqlfluff/core/linter/common.py b/src/sqlfluff/core/linter/common.py\n--- a/src/sqlfluff/core/linter/common.py\n+++ b/src/sqlfluff/core/linter/common.py\n@@ -42,6 +42,7 @@ class RenderedFile(NamedTuple):\n time_dict: Dict[str, float]\n fname: str\n encoding: str\n+ source_str: str\n \n \n class ParsedString(NamedTuple):\n@@ -65,6 +66,7 @@ class ParsedString(NamedTuple):\n templated_file: TemplatedFile\n config: FluffConfig\n fname: str\n+ source_str: str\n \n \n class EnrichedFixPatch(NamedTuple):\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -26,7 +26,7 @@\n SQLParseError,\n SQLTemplaterSkipFile,\n )\n-from sqlfluff.core.parser import Lexer, Parser\n+from sqlfluff.core.parser import Lexer, Parser, RegexLexer\n from sqlfluff.core.file_helpers import get_encoding\n from sqlfluff.core.templaters import TemplatedFile\n from sqlfluff.core.rules import get_ruleset\n@@ -343,7 +343,7 @@ def parse_rendered(\n cls,\n rendered: RenderedFile,\n recurse: bool = True,\n- ):\n+ ) -> ParsedString:\n \"\"\"Parse a rendered file.\"\"\"\n t0 = time.monotonic()\n violations = cast(List[SQLBaseError], rendered.templater_violations)\n@@ -382,6 +382,7 @@ def parse_rendered(\n rendered.templated_file,\n rendered.config,\n rendered.fname,\n+ rendered.source_str,\n )\n \n @classmethod\n@@ -400,7 +401,7 @@ def extract_ignore_from_comment(\n return result\n \n @classmethod\n- def extract_ignore_mask(\n+ def extract_ignore_mask_tree(\n cls,\n tree: BaseSegment,\n rule_codes: List[str],\n@@ -419,6 +420,34 @@ def extract_ignore_mask(\n linter_logger.info(\"Parsed noqa directives from file: %r\", ignore_buff)\n return ignore_buff, violations\n \n+ @classmethod\n+ def extract_ignore_mask_source(\n+ cls,\n+ source: str,\n+ inline_comment_regex: RegexLexer,\n+ rule_codes: List[str],\n+ ) -> Tuple[List[NoQaDirective], List[SQLBaseError]]:\n+ \"\"\"Look for inline ignore comments and return NoQaDirectives.\n+\n+ Very similar to extract_ignore_mask_tree(), but can be run on raw source\n+ (i.e. does not require the code to have parsed successfully).\n+ \"\"\"\n+ ignore_buff: List[NoQaDirective] = []\n+ violations: List[SQLBaseError] = []\n+ for idx, line in enumerate(source.split(\"\\n\")):\n+ match = inline_comment_regex.search(line) if line else None\n+ if match:\n+ ignore_entry = cls.parse_noqa(\n+ line[match[0] : match[1]], idx + 1, rule_codes\n+ )\n+ if isinstance(ignore_entry, SQLParseError):\n+ violations.append(ignore_entry) # pragma: no cover\n+ elif ignore_entry:\n+ ignore_buff.append(ignore_entry)\n+ if ignore_buff:\n+ linter_logger.info(\"Parsed noqa directives from file: %r\", ignore_buff)\n+ return ignore_buff, violations\n+\n @classmethod\n def lint_fix_parsed(\n cls,\n@@ -449,7 +478,7 @@ def lint_fix_parsed(\n # Look for comment segments which might indicate lines to ignore.\n if not config.get(\"disable_noqa\"):\n rule_codes = [r.code for r in rule_set]\n- ignore_buff, ivs = cls.extract_ignore_mask(tree, rule_codes)\n+ ignore_buff, ivs = cls.extract_ignore_mask_tree(tree, rule_codes)\n all_linting_errors += ivs\n else:\n ignore_buff = []\n@@ -556,6 +585,21 @@ def lint_parsed(\n # If no parsed tree, set to None\n tree = None\n ignore_buff = []\n+ if not parsed.config.get(\"disable_noqa\"):\n+ # Templating and/or parsing have failed. Look for \"noqa\"\n+ # comments (the normal path for identifying these comments\n+ # requires access to the parse tree, and because of the failure,\n+ # we don't have a parse tree).\n+ ignore_buff, ignore_violations = cls.extract_ignore_mask_source(\n+ parsed.source_str,\n+ [\n+ lm\n+ for lm in parsed.config.get(\"dialect_obj\").lexer_matchers\n+ if lm.name == \"inline_comment\"\n+ ][0],\n+ [r.code for r in rule_set],\n+ )\n+ violations += ignore_violations\n \n # We process the ignore config here if appropriate\n for violation in violations:\n@@ -649,7 +693,13 @@ def render_string(\n time_dict = {\"templating\": time.monotonic() - t0}\n \n return RenderedFile(\n- templated_file, templater_violations, config, time_dict, fname, encoding\n+ templated_file,\n+ templater_violations,\n+ config,\n+ time_dict,\n+ fname,\n+ encoding,\n+ in_str,\n )\n \n def render_file(self, fname: str, root_config: FluffConfig) -> RenderedFile:\ndiff --git a/src/sqlfluff/core/templaters/jinja.py b/src/sqlfluff/core/templaters/jinja.py\n--- a/src/sqlfluff/core/templaters/jinja.py\n+++ b/src/sqlfluff/core/templaters/jinja.py\n@@ -386,7 +386,13 @@ def process(\n \"Unrecoverable failure in Jinja templating: {}. Have you \"\n \"configured your variables? \"\n \"https://docs.sqlfluff.com/en/latest/configuration.html\"\n- ).format(err)\n+ ).format(err),\n+ # We don't have actual line number information, but specify\n+ # line 1 so users can ignore with \"noqa\" if they want. (The\n+ # default is line 0, which can't be ignored because it's not\n+ # a valid line number.)\n+ line_no=1,\n+ line_pos=1,\n )\n )\n return None, violations\n", "test_patch": "diff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -708,18 +708,42 @@ def test_linter_noqa_with_templating():\n assert not result.get_violations()\n \n \n+def test_linter_noqa_template_errors():\n+ \"\"\"Similar to test_linter_noqa, but uses templating (Jinja).\"\"\"\n+ lntr = Linter(\n+ config=FluffConfig(\n+ overrides={\n+ \"templater\": \"jinja\",\n+ }\n+ )\n+ )\n+ sql = \"\"\"select * --noqa: TMP\n+from raw\n+where\n+ balance_date >= {{ execution_date - macros.timedelta() }} --noqa: TMP\n+\"\"\"\n+ result = lntr.lint_string(sql)\n+ assert not result.get_violations()\n+\n+\n def test_linter_noqa_prs():\n \"\"\"Test \"noqa\" feature to ignore PRS at the higher \"Linter\" level.\"\"\"\n lntr = Linter(\n config=FluffConfig(\n overrides={\n+ \"dialect\": \"bigquery\",\n \"exclude_rules\": \"L050\",\n }\n )\n )\n sql = \"\"\"\n- SELECT col_a AS a\n- FROM foo;, -- noqa: PRS\n+ CREATE TABLE IF NOT EXISTS\n+ Test.events (userID STRING,\n+ eventName STRING,\n+ eventID INTEGER,\n+ device STRUCT < mobileBrandName STRING, -- noqa: PRS\n+ mobileModelName STRING>);\n+ Insert into Test.events VALUES (\"1\",\"abc\",123,STRUCT(\"htc\",\"10\"));\n \"\"\"\n result = lntr.lint_string(sql)\n violations = result.get_violations()\n", "problem_statement": "noqa is ignored for jinja templated lines\n## Expected Behaviour\r\nLine with `noqa: TMP` should be ignored (despite of evaluation error)\r\n\r\n## Observed Behaviour\r\ntrying to lint airflow sql-template for AWS Athena query\r\nsetting up inline `-- noqa` or `--noqa: TMP` for jinja templated line not silenting templating error (typecasting error due to unable to pass datetime object while linting into template context):\r\n```\r\n== [transform/airflow/dags/queries/sfmc/player_balance.sql] FAIL\r\nL: 0 | P: 0 | TMP | Unrecoverable failure in Jinja templating: unsupported operand type(s) for -: 'int' and 'datetime.timedelta'. Have you configured your variables?\r\n | https://docs.sqlfluff.com/en/latest/configuration.html\r\n```\r\n\r\n## Steps to Reproduce\r\ntemplated file:\r\n```sql\r\nselect *, row_number() over (partition by player_id order by balance_change_date desc) as rnk\r\nfrom raw\r\nwhere\r\n balance_change_date >= cast(from_iso8601_timestamp('{{ execution_date - macros.timedelta(hours=2, minutes=10) }}') as timestamp) and --noqa: TMP\r\n balance_change_date < cast(from_iso8601_timestamp('{{ next_execution_date - macros.timedelta(minutes=10) }}') as timestamp) --noqa: TMP\r\n```\r\nrun:\r\n```bash\r\nsqlfluff lint transform/airflow/dags/queries/sfmc/player_balance.sql\r\n```\r\n\r\n## Dialect\r\npostgres (used for AWS Athena)\r\n\r\n## Version\r\ndatalake % sqlfluff --version\r\nsqlfluff, version 0.8.1\r\ndatalake % python3 --version\r\nPython 3.9.8\r\n\r\n## Configuration\r\n```ini\r\n# tox.ini\r\n[sqlfluff]\r\ntemplater = jinja\r\noutput_line_length = 180\r\nexclude_rules = L011,L012,L022,L031,L034\r\ndialect = postgres\r\n\r\n[sqlfluff:rules]\r\nmax_line_length = 120\r\n\r\n[sqlfluff:templater:jinja]\r\nlibrary_path = operation/deploy/lint\r\napply_dbt_builtins = false\r\n\r\n[sqlfluff:templater:jinja:context]\r\nds = 2021-11-11\r\nds_nodash = 20211111\r\nstart_date = 2021-11-11\r\nend_date = 2021-11-11\r\ninterval = 1\r\n# passed as int due to inabliity to pass datetime obkject \r\ndata_interval_start = 1636588800\r\ndata_interval_end = 1636588800\r\n```\r\n\r\n```python\r\n# operation/deploy/lint/macro.py\r\nfrom datetime import datetime, timedelta # noqa: F401\r\n\r\nimport dateutil # noqa: F401\r\n```\n", "hints_text": "As discussed on slack:\r\n\r\nChecking a few versions back your example has never worked.\r\nI think the templating ignoring is pretty basic (it's not included in our documentation).\r\n\r\nSo this works:\r\n\r\n```sql\r\nSELECT\r\n {{ test }} --noqa: TMP\r\nFROM\r\n table1\r\n```\r\n\r\nBut think anything beyond that simple use case, it struggles with.\r\n\r\nWill leave this issue open to see if it can be improved but for now the best solution is to defined that macro in the config (though I don't think dots in macros names are even supported in Jinja so not sure this is even possible?)", "created_at": "2022-01-29T20:32:14Z", "version": "0.8", "FAIL_TO_PASS": ["test/core/linter_test.py::test_linter_noqa_template_errors", "test/core/linter_test.py::test_linter_noqa_prs"], "PASS_TO_PASS": ["test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_parse_noqa[Inline", "test/core/linter_test.py::test_parse_noqa_no_dups", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[2_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_glob_ignore]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_linter_noqa_tmp", "test/core/linter_test.py::test_linter_noqa_disable", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]", "test/core/linter_test.py::test_advanced_api_methods", "test/core/linter_test.py::test_normalise_newlines"], "environment_setup_commit": "a5c4eae4e3e419fe95460c9afd9cf39a35a470c4"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-5206", "base_commit": "895e668a0047bd31fb87865fcab50d846bfb88ce", "patch": "diff --git a/src/sqlfluff/core/parser/segments/base.py b/src/sqlfluff/core/parser/segments/base.py\n--- a/src/sqlfluff/core/parser/segments/base.py\n+++ b/src/sqlfluff/core/parser/segments/base.py\n@@ -13,7 +13,6 @@\n import logging\n import weakref\n from collections import defaultdict\n-from copy import copy\n from dataclasses import dataclass\n from io import StringIO\n from itertools import chain\n@@ -965,25 +964,55 @@ def to_tuple(\n )\n \n def copy(\n- self, segments: Optional[Tuple[\"BaseSegment\", ...]] = None\n+ self,\n+ segments: Optional[Tuple[\"BaseSegment\", ...]] = None,\n+ parent: Optional[\"BaseSegment\"] = None,\n ) -> \"BaseSegment\":\n \"\"\"Copy the segment recursively, with appropriate copying of references.\n \n Optionally provide child segments which have already been dealt\n with to avoid another copy operation.\n+\n+ NOTE: In the copy operation it's really important that we get\n+ a clean segregation so that we can't go backward and mutate the\n+ source object, but at the same time we should be mindful of what\n+ _needs_ to be copied to avoid a deep copy where one isn't required.\n \"\"\"\n- new_seg = copy(self)\n+ cls = self.__class__\n+ new_segment = cls.__new__(cls)\n # Position markers are immutable, and it's important that we keep\n # a reference to the same TemplatedFile, so keep the same position\n- # marker.\n- new_seg.pos_marker = self.pos_marker\n+ # marker. By updating from the source dict, we achieve that.\n+ # By using the __dict__ object we also transfer the _cache_ too\n+ # which is stored there by @cached_property.\n+ new_segment.__dict__.update(self.__dict__)\n+\n+ # Reset the parent if provided.\n+ if parent:\n+ new_segment.set_parent(parent)\n+\n+ # If the segment doesn't have a segments property, we're done.\n+ # NOTE: This is a proxy way of understanding whether it's a RawSegment\n+ # of not. Typically will _have_ a `segments` attribute, but it's an\n+ # empty tuple.\n+ if not self.__dict__.get(\"segments\", None):\n+ assert (\n+ not segments\n+ ), f\"Cannot provide `segments` argument to {cls.__name__} `.copy()`\\n\"\n # If segments were provided, use them.\n- if segments:\n- new_seg.segments = segments\n- # Otherwise copy them.\n- elif self.segments:\n- new_seg.segments = tuple(seg.copy() for seg in self.segments)\n- return new_seg\n+ elif segments:\n+ new_segment.segments = segments\n+ # Otherwise we should handle recursive segment coping.\n+ # We use the native .copy() method (this method!) appropriately\n+ # so that the same logic is applied in recursion.\n+ # We set the parent for children directly on the copy method\n+ # to ensure those line up properly.\n+ else:\n+ new_segment.segments = tuple(\n+ seg.copy(parent=new_segment) for seg in self.segments\n+ )\n+\n+ return new_segment\n \n def as_record(self, **kwargs: bool) -> Optional[RecordSerialisedSegment]:\n \"\"\"Return the segment as a structurally simplified record.\n@@ -1400,7 +1429,6 @@ def apply_fixes(\n # of a create_before/create_after pair, also add\n # this segment before the edit.\n seg_buffer.append(seg)\n- seg.set_parent(self)\n \n # We're doing a replacement (it could be a single\n # segment or an iterable)\n@@ -1408,7 +1436,6 @@ def apply_fixes(\n consumed_pos = False\n for s in f.edit:\n seg_buffer.append(s)\n- s.set_parent(self)\n # If one of them has the same raw representation\n # then the first that matches gets to take the\n # original position marker.\n@@ -1424,7 +1451,6 @@ def apply_fixes(\n # in the case of a creation before, also add this\n # segment on the end\n seg_buffer.append(seg)\n- seg.set_parent(self)\n \n else: # pragma: no cover\n raise ValueError(\n@@ -1434,7 +1460,7 @@ def apply_fixes(\n )\n else:\n seg_buffer.append(seg)\n- seg.set_parent(self)\n+\n # Invalidate any caches\n self.invalidate_caches()\n \n@@ -1495,6 +1521,7 @@ def apply_fixes(\n # Pass through any additional kwargs\n **{k: getattr(self, k) for k in self.additional_kwargs},\n )\n+ new_seg.set_as_parent(recurse=False)\n # Only validate if there's a match_grammar. Otherwise we may get\n # strange results (for example with the BracketedSegment).\n if requires_validate and (\ndiff --git a/src/sqlfluff/core/rules/base.py b/src/sqlfluff/core/rules/base.py\n--- a/src/sqlfluff/core/rules/base.py\n+++ b/src/sqlfluff/core/rules/base.py\n@@ -1143,7 +1143,7 @@ def _choose_anchor_segment(\n if root_segment\n else None\n )\n- assert path\n+ assert path, f\"No path found from {root_segment} to {segment}!\"\n for seg in path[::-1]:\n # If the segment allows non code ends, then no problem.\n # We're done. This is usually the outer file segment.\n", "test_patch": "diff --git a/test/core/parser/segments/segments_base_test.py b/test/core/parser/segments/segments_base_test.py\n--- a/test/core/parser/segments/segments_base_test.py\n+++ b/test/core/parser/segments/segments_base_test.py\n@@ -302,3 +302,58 @@ def test__parser__base_segments_pickle_safe(raw_seg_list):\n assert test_seg == result_seg\n # Check specifically the treatment of the parent position.\n assert result_seg.segments[0].get_parent() is result_seg\n+\n+\n+def test__parser__base_segments_copy_isolation(DummySegment, raw_seg_list):\n+ \"\"\"Test copy isolation in BaseSegment.\n+\n+ First on one of the raws and then on the dummy segment.\n+ \"\"\"\n+ # On a raw\n+ a_seg = raw_seg_list[0]\n+ a_copy = a_seg.copy()\n+ assert a_seg is not a_copy\n+ assert a_seg == a_copy\n+ assert a_seg.pos_marker is a_copy.pos_marker\n+ a_copy.pos_marker = None\n+ assert a_copy.pos_marker is None\n+ assert a_seg.pos_marker is not None\n+\n+ # On a base\n+ b_seg = DummySegment(segments=raw_seg_list)\n+ b_copy = b_seg.copy()\n+ assert b_seg is not b_copy\n+ assert b_seg == b_copy\n+ assert b_seg.pos_marker is b_copy.pos_marker\n+ b_copy.pos_marker = None\n+ assert b_copy.pos_marker is None\n+ assert b_seg.pos_marker is not None\n+\n+ # On addition to a lint Fix\n+ fix = LintFix(\"replace\", a_seg, [b_seg])\n+ for s in fix.edit:\n+ assert not s.pos_marker\n+ assert b_seg.pos_marker\n+\n+\n+def test__parser__base_segments_parent_ref(DummySegment, raw_seg_list):\n+ \"\"\"Test getting and setting parents on BaseSegment.\"\"\"\n+ # Check initially no parent (because not set)\n+ assert not raw_seg_list[0].get_parent()\n+ # Add it to a segment (still not set)\n+ seg = DummySegment(segments=raw_seg_list)\n+ assert not seg.segments[0].get_parent()\n+ # Set one parent on one of them (but not another)\n+ seg.segments[0].set_parent(seg)\n+ assert seg.segments[0].get_parent() is seg\n+ assert not seg.segments[1].get_parent()\n+ # Set parent on all of them\n+ seg.set_as_parent()\n+ assert seg.segments[0].get_parent() is seg\n+ assert seg.segments[1].get_parent() is seg\n+ # Remove segment from parent, but don't unset.\n+ # Should still check an return None.\n+ seg_0 = seg.segments[0]\n+ seg.segments = seg.segments[1:]\n+ assert seg_0 not in seg.segments\n+ assert not seg_0.get_parent()\ndiff --git a/test/rules/std_RF01_LT09_test.py b/test/rules/std_RF01_LT09_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/rules/std_RF01_LT09_test.py\n@@ -0,0 +1,27 @@\n+\"\"\"Tests observed conflict between RF01 & LT09.\n+\n+Root cause was BaseSegment.copy().\n+\"\"\"\n+from sqlfluff.core import FluffConfig, Linter\n+\n+\n+def test__rules__std_RF01_LT09_copy() -> None:\n+ \"\"\"Tests observed conflict between RF01 & LT09.\n+\n+ https://github.com/sqlfluff/sqlfluff/issues/5203\n+ \"\"\"\n+ sql = \"\"\"\n+SELECT\n+ DISTINCT `FIELD`\n+FROM `TABLE`;\n+\"\"\"\n+ cfg = FluffConfig.from_kwargs(\n+ dialect=\"mysql\",\n+ rules=[\"RF01\", \"LT09\"],\n+ )\n+ result = Linter(config=cfg).lint_string(sql)\n+ for violation in result.violations:\n+ assert \"Unexpected exception\" not in violation.description\n+ assert len(result.violations) == 1\n+ only_violation = result.violations[0]\n+ assert only_violation.rule_code() == \"LT09\"\n", "problem_statement": "Exception thrown when SELECT DISTINCT not on the same line\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nCheck a file containing this request:\r\n\r\n```sql\r\nSELECT\r\n DISTINCT `FIELD`\r\nFROM `TABLE`;\r\n```\r\n\r\nIt fails this way:\r\n\r\n```log\r\nCRITICAL [RF01] Applying rule RF01 to 'file.sql' threw an Exception: \r\nTraceback (most recent call last):\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/core/rules/base.py\", line 864, in crawl\r\n res = self._eval(context=context)\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/rules/references/RF01.py\", line 107, in _eval\r\n self._analyze_table_references(\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/rules/references/RF01.py\", line 152, in _analyze_table_references\r\n if not self._should_ignore_reference(r, selectable):\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/rules/references/RF01.py\", line 168, in _should_ignore_reference\r\n ref_path = selectable.selectable.path_to(reference)\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/core/parser/segments/base.py\", line 1184, in path_to\r\n elif not self.get_start_loc() <= midpoint.get_start_loc() <= self.get_end_loc():\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/core/parser/segments/base.py\", line 877, in get_start_loc\r\n assert self.pos_marker\r\nAssertionError\r\n== [file.sql] FAIL\r\nL: 1 | P: 1 | LT09 | Select targets should be on a new line unless there is\r\n | only one select target. [layout.select_targets]\r\nL: 1 | P: 1 | LT10 | 'SELECT' modifiers (e.g. 'DISTINCT') must be on the same\r\n | line as 'SELECT'. [layout.select_modifiers]\r\nL: 1 | P: 1 | RF01 | Unexpected exception: ;\r\nCould you open an issue at\r\n | https://github.com/sqlfluff/sqlfluff/issues ?\r\nYou can\r\n | ignore this exception for now, by adding '-- noqa: RF01'\r\n | at the end\r\nof line 1\r\n [references.from]\r\nL: 2 | P: 1 | LT02 | Line should not be indented. [layout.indent]\r\nL: 3 | P: 13 | LT12 | Files must end with a single trailing newline.\r\n | [layout.end_of_file]\r\nAll Finished!\r\n```\r\n\r\nChecking the following request does not throw an exception (move `DISTINCT` on same line than `SELECT`):\r\n\r\n```sql\r\nSELECT DISTINCT `FIELD`\r\nFROM `TABLE`;\r\n```\r\n\r\nAdditionally, I'd like to add that checking the first request on https://online.sqlfluff.com/fluffed leads to the same exception. But if you check this request:\r\n```sql\r\nSELECT \r\nDISTINCT\r\n`FIELD`\r\nFROM `TABLE`;\r\n```\r\nThen the website crashes.\r\n\r\n### Expected Behaviour\r\n\r\nI would expect not to have an exception.\r\n\r\n### Observed Behaviour\r\n\r\nAn exception was thrown whereas, I think, there is no reason to throw it.\r\n\r\n### How to reproduce\r\n\r\nCheck the following SQL:\r\n\r\n```sql\r\nSELECT\r\n DISTINCT `FIELD`\r\nFROM `TABLE`;\r\n```\r\n\r\n### Dialect\r\n\r\nMySQL\r\n\r\n### Version\r\n\r\n2.3.2\r\n\r\n### Configuration\r\n\r\n```\r\n[sqlfluff]\r\n# Supported dialects https://docs.sqlfluff.com/en/stable/dialects.html\r\ndialect = mysql\r\nencoding = utf-8\r\n# Exclude rule LT01/layout.spacing: it expects a space even after type of fields (i.e. \"INT (11)\")\r\n# Exclude rule ST05/structure.subquery: MySQL badly supports CTEs.\r\nexclude_rules = LT01, ST05\r\nignore = parsing\r\nmax_line_length = 120\r\n# Below controls SQLFluff output, see max_line_length for SQL output\r\noutput_line_length = 80\r\ntemplater = raw\r\nverbose = 0\r\n\r\n[sqlfluff:layout:type:binary_operator]\r\nline_position = leading\r\n\r\n[sqlfluff:layout:type:comma]\r\nline_position = trailing\r\nspacing_before = touch\r\n\r\n[sqlfluff:indentation]\r\n# See https://docs.sqlfluff.com/en/stable/indentation.html\r\nindent_unit = space\r\nindented_joins = True\r\nindented_using_on = True\r\ntab_space_size = 4\r\n\r\n# Some rules can be configured directly from the config common to other rules\r\n[sqlfluff:rules]\r\nallow_scalar = True\r\nquoted_identifiers_policy = none\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = all\r\n\r\n[sqlfluff:rules:aliasing.column]\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:aliasing.table]\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:ambiguous.column_references]\r\ngroup_by_and_order_by_style = consistent\r\n\r\n[sqlfluff:rules:capitalisation.functions]\r\ncapitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.identifiers]\r\nextended_capitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.keywords]\r\ncapitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.literals]\r\ncapitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.types]\r\nextended_capitalisation_policy = upper\r\n\r\n[sqlfluff:rules:convention.count_rows]\r\nprefer_count_0 = False\r\nprefer_count_1 = True\r\n\r\n[sqlfluff:rules:convention.select_trailing_comma]\r\nselect_clause_trailing_comma = forbid\r\n\r\n[sqlfluff:rules:convention.terminator]\r\nmultiline_newline = False\r\nrequire_final_semicolon = True\r\n\r\n[sqlfluff:rules:layout.long_lines]\r\nignore_comment_lines = True\r\n\r\n[sqlfluff:rules:references.keywords]\r\nignore_words = None\r\nquoted_identifiers_policy = none\r\nunquoted_identifiers_policy = all\r\n\r\n[sqlfluff:rules:convention.quoted_literals]\r\npreferred_quoted_literal_style = single_quotes\r\n\r\n[sqlfluff:rules:references.quoting]\r\nprefer_quoted_identifiers = True\r\n\r\n[sqlfluff:rules:references.special_chars]\r\nadditional_allowed_characters = \"\"\r\nallow_space_in_identifier = False\r\nquoted_identifiers_policy = all\r\n# Special characters in identifiers\r\nunquoted_identifiers_policy = all\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\nException thrown when SELECT DISTINCT not on the same line\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\n\r\n### What Happened\r\n\r\nCheck a file containing this request:\r\n\r\n```sql\r\nSELECT\r\n DISTINCT `FIELD`\r\nFROM `TABLE`;\r\n```\r\n\r\nIt fails this way:\r\n\r\n```log\r\nCRITICAL [RF01] Applying rule RF01 to 'file.sql' threw an Exception: \r\nTraceback (most recent call last):\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/core/rules/base.py\", line 864, in crawl\r\n res = self._eval(context=context)\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/rules/references/RF01.py\", line 107, in _eval\r\n self._analyze_table_references(\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/rules/references/RF01.py\", line 152, in _analyze_table_references\r\n if not self._should_ignore_reference(r, selectable):\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/rules/references/RF01.py\", line 168, in _should_ignore_reference\r\n ref_path = selectable.selectable.path_to(reference)\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/core/parser/segments/base.py\", line 1184, in path_to\r\n elif not self.get_start_loc() <= midpoint.get_start_loc() <= self.get_end_loc():\r\n File \"/app/.venv/lib/python3.9/site-packages/sqlfluff/core/parser/segments/base.py\", line 877, in get_start_loc\r\n assert self.pos_marker\r\nAssertionError\r\n== [file.sql] FAIL\r\nL: 1 | P: 1 | LT09 | Select targets should be on a new line unless there is\r\n | only one select target. [layout.select_targets]\r\nL: 1 | P: 1 | LT10 | 'SELECT' modifiers (e.g. 'DISTINCT') must be on the same\r\n | line as 'SELECT'. [layout.select_modifiers]\r\nL: 1 | P: 1 | RF01 | Unexpected exception: ;\r\nCould you open an issue at\r\n | https://github.com/sqlfluff/sqlfluff/issues ?\r\nYou can\r\n | ignore this exception for now, by adding '-- noqa: RF01'\r\n | at the end\r\nof line 1\r\n [references.from]\r\nL: 2 | P: 1 | LT02 | Line should not be indented. [layout.indent]\r\nL: 3 | P: 13 | LT12 | Files must end with a single trailing newline.\r\n | [layout.end_of_file]\r\nAll Finished!\r\n```\r\n\r\nChecking the following request does not throw an exception (move `DISTINCT` on same line than `SELECT`):\r\n\r\n```sql\r\nSELECT DISTINCT `FIELD`\r\nFROM `TABLE`;\r\n```\r\n\r\nAdditionally, I'd like to add that checking the first request on https://online.sqlfluff.com/fluffed leads to the same exception. But if you check this request:\r\n```sql\r\nSELECT \r\nDISTINCT\r\n`FIELD`\r\nFROM `TABLE`;\r\n```\r\nThen the website crashes.\r\n\r\n### Expected Behaviour\r\n\r\nI would expect not to have an exception.\r\n\r\n### Observed Behaviour\r\n\r\nAn exception was thrown whereas, I think, there is no reason to throw it.\r\n\r\n### How to reproduce\r\n\r\nCheck the following SQL:\r\n\r\n```sql\r\nSELECT\r\n DISTINCT `FIELD`\r\nFROM `TABLE`;\r\n```\r\n\r\n### Dialect\r\n\r\nMySQL\r\n\r\n### Version\r\n\r\n2.3.2\r\n\r\n### Configuration\r\n\r\n```\r\n[sqlfluff]\r\n# Supported dialects https://docs.sqlfluff.com/en/stable/dialects.html\r\ndialect = mysql\r\nencoding = utf-8\r\n# Exclude rule LT01/layout.spacing: it expects a space even after type of fields (i.e. \"INT (11)\")\r\n# Exclude rule ST05/structure.subquery: MySQL badly supports CTEs.\r\nexclude_rules = LT01, ST05\r\nignore = parsing\r\nmax_line_length = 120\r\n# Below controls SQLFluff output, see max_line_length for SQL output\r\noutput_line_length = 80\r\ntemplater = raw\r\nverbose = 0\r\n\r\n[sqlfluff:layout:type:binary_operator]\r\nline_position = leading\r\n\r\n[sqlfluff:layout:type:comma]\r\nline_position = trailing\r\nspacing_before = touch\r\n\r\n[sqlfluff:indentation]\r\n# See https://docs.sqlfluff.com/en/stable/indentation.html\r\nindent_unit = space\r\nindented_joins = True\r\nindented_using_on = True\r\ntab_space_size = 4\r\n\r\n# Some rules can be configured directly from the config common to other rules\r\n[sqlfluff:rules]\r\nallow_scalar = True\r\nquoted_identifiers_policy = none\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = all\r\n\r\n[sqlfluff:rules:aliasing.column]\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:aliasing.table]\r\naliasing = explicit\r\n\r\n[sqlfluff:rules:ambiguous.column_references]\r\ngroup_by_and_order_by_style = consistent\r\n\r\n[sqlfluff:rules:capitalisation.functions]\r\ncapitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.identifiers]\r\nextended_capitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.keywords]\r\ncapitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.literals]\r\ncapitalisation_policy = upper\r\nignore_words = None\r\n\r\n[sqlfluff:rules:capitalisation.types]\r\nextended_capitalisation_policy = upper\r\n\r\n[sqlfluff:rules:convention.count_rows]\r\nprefer_count_0 = False\r\nprefer_count_1 = True\r\n\r\n[sqlfluff:rules:convention.select_trailing_comma]\r\nselect_clause_trailing_comma = forbid\r\n\r\n[sqlfluff:rules:convention.terminator]\r\nmultiline_newline = False\r\nrequire_final_semicolon = True\r\n\r\n[sqlfluff:rules:layout.long_lines]\r\nignore_comment_lines = True\r\n\r\n[sqlfluff:rules:references.keywords]\r\nignore_words = None\r\nquoted_identifiers_policy = none\r\nunquoted_identifiers_policy = all\r\n\r\n[sqlfluff:rules:convention.quoted_literals]\r\npreferred_quoted_literal_style = single_quotes\r\n\r\n[sqlfluff:rules:references.quoting]\r\nprefer_quoted_identifiers = True\r\n\r\n[sqlfluff:rules:references.special_chars]\r\nadditional_allowed_characters = \"\"\r\nallow_space_in_identifier = False\r\nquoted_identifiers_policy = all\r\n# Special characters in identifiers\r\nunquoted_identifiers_policy = all\r\n```\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "\n", "created_at": "2023-09-13T18:57:24Z", "version": "2.2", "FAIL_TO_PASS": ["test/rules/std_RF01_LT09_test.py::test__rules__std_RF01_LT09_copy"], "PASS_TO_PASS": ["test/core/parser/segments/segments_base_test.py::test__parser__base_segments_type", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_class_types", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_descendant_type_set", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_direct_descendant_type_set", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_to_tuple_a", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_to_tuple_b", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_to_tuple_c", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_as_record_a", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_as_record_b", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_as_record_c", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_count_segments", "test/core/parser/segments/segments_base_test.py::test__parser_base_segments_find_start_or_end_non_code[list_in0-None]", "test/core/parser/segments/segments_base_test.py::test__parser_base_segments_find_start_or_end_non_code[list_in1--1]", "test/core/parser/segments/segments_base_test.py::test__parser_base_segments_find_start_or_end_non_code[list_in2-0]", "test/core/parser/segments/segments_base_test.py::test__parser_base_segments_find_start_or_end_non_code[list_in3-0]", "test/core/parser/segments/segments_base_test.py::test__parser_base_segments_find_start_or_end_non_code[list_in4-0]", "test/core/parser/segments/segments_base_test.py::test__parser_base_segments_find_start_or_end_non_code[list_in5-None]", "test/core/parser/segments/segments_base_test.py::test__parser_base_segments_compute_anchor_edit_info", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_path_to", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_stubs", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_raw", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_base", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_raw_compare", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_base_compare", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_pickle_safe", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_copy_isolation", "test/core/parser/segments/segments_base_test.py::test__parser__base_segments_parent_ref"], "environment_setup_commit": "3625934f16857ade527f5f7dfa84b874061ea739"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-1577", "base_commit": "500505877769ab02504427284e4efdf832d299ea", "patch": "diff --git a/src/sqlfluff/core/templaters/base.py b/src/sqlfluff/core/templaters/base.py\n--- a/src/sqlfluff/core/templaters/base.py\n+++ b/src/sqlfluff/core/templaters/base.py\n@@ -84,7 +84,8 @@ def __init__(\n is the same as the source view.\n \"\"\"\n self.source_str = source_str\n- self.templated_str = templated_str or source_str\n+ # An empty string is still allowed as the templated string.\n+ self.templated_str = source_str if templated_str is None else templated_str\n # If no fname, we assume this is from a string or stdin.\n self.fname = fname\n # Assume that no sliced_file, means the file is not templated\n@@ -297,7 +298,7 @@ def templated_slice_to_source_slice(\n break\n \n subslices = self.sliced_file[\n- # Ver inclusive slice\n+ # Very inclusive slice\n min(ts_start_sf_start, ts_stop_sf_start) : max(\n ts_start_sf_stop, ts_stop_sf_stop\n )\n", "test_patch": "diff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -75,6 +75,18 @@ def test__templater_jinja_error_catatrophic():\n assert len(vs) > 0\n \n \n+def test__templater_jinja_lint_empty():\n+ \"\"\"Check that parsing a file which renders to an empty string.\n+\n+ No exception should be raised, but the parsed tree should be None.\n+ \"\"\"\n+ lntr = Linter()\n+ parsed = lntr.parse_string(in_str='{{ \"\" }}')\n+ assert parsed.templated_file.source_str == '{{ \"\" }}'\n+ assert parsed.templated_file.templated_str == \"\"\n+ assert parsed.tree is None\n+\n+\n def assert_structure(yaml_loader, path, code_only=True, include_meta=False):\n \"\"\"Check that a parsed sql file matches the yaml file with the same name.\"\"\"\n lntr = Linter()\n", "problem_statement": "\"ValueError: Position Not Found\" with macro spanning entire file\n## Expected Behaviour\r\n\r\n`sqlfluff parse` should probably not fail with an exception and stack trace.\r\n\r\n## Observed Behaviour\r\n\r\n`sqlfluff parse` throws an exception, given an input file which is entirely spanned by a Jinja macro.\r\n\r\n## Steps to Reproduce\r\n\r\n```console\r\n$ echo -n '{% macro foo() %}{% endmacro %}' | sqlfluff parse -\r\nTraceback (most recent call last):\r\n File \"/home/vladimir/work/extern/sqlfluff/venv/bin/sqlfluff\", line 33, in <module>\r\n sys.exit(load_entry_point('sqlfluff', 'console_scripts', 'sqlfluff')())\r\n File \"/home/vladimir/work/extern/sqlfluff/venv/lib/python3.9/site-packages/click/core.py\", line 1137, in __call__\r\n return self.main(*args, **kwargs)\r\n File \"/home/vladimir/work/extern/sqlfluff/venv/lib/python3.9/site-packages/click/core.py\", line 1062, in main\r\n rv = self.invoke(ctx)\r\n File \"/home/vladimir/work/extern/sqlfluff/venv/lib/python3.9/site-packages/click/core.py\", line 1668, in invoke\r\n return _process_result(sub_ctx.command.invoke(sub_ctx))\r\n File \"/home/vladimir/work/extern/sqlfluff/venv/lib/python3.9/site-packages/click/core.py\", line 1404, in invoke\r\n return ctx.invoke(self.callback, **ctx.params)\r\n File \"/home/vladimir/work/extern/sqlfluff/venv/lib/python3.9/site-packages/click/core.py\", line 763, in invoke\r\n return __callback(*args, **kwargs)\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/cli/commands.py\", line 701, in parse\r\n lnt.parse_string(\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 596, in parse_string\r\n return self.parse_rendered(rendered, recurse=recurse)\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 294, in parse_rendered\r\n tokens, lvs, config = cls._lex_templated_file(\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 127, in _lex_templated_file\r\n tokens, lex_vs = lexer.lex(templated_file)\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/core/parser/lexer.py\", line 319, in lex\r\n segments: Tuple[RawSegment, ...] = self.elements_to_segments(\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/core/parser/lexer.py\", line 346, in elements_to_segments\r\n source_slice = templated_file.templated_slice_to_source_slice(\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/core/templaters/base.py\", line 319, in templated_slice_to_source_slice\r\n ts_stop_sf_start, ts_stop_sf_stop = self._find_slice_indices_of_templated_pos(\r\n File \"/home/vladimir/work/extern/sqlfluff/src/sqlfluff/core/templaters/base.py\", line 214, in _find_slice_indices_of_templated_pos\r\n raise ValueError(\"Position Not Found\")\r\nValueError: Position Not Found\r\n```\r\n\r\nNote: the issue does not occur if the file ends with a newline. \r\n\r\nThe contents of the macro also doesn't matter.\r\n\r\n## Dialect\r\n\r\nNone specified\r\n\r\n## Version\r\nSQLFluff 6011bdbe05669b075045e8127cdf18cc537686d4, Python 3.9.6\r\n\r\n## Configuration\r\n\r\nNone\n", "hints_text": "Hi @CyberShadow, @tunetheweb, what is expected output of\r\n```console\r\n$ echo -n '{% macro foo() %}{% endmacro %}' | sqlfluff parse -\r\n```\r\n?\r\n\nProbably the same as the input. Definitely not an exception, in any case.\r\n\r\nEdit: Whoops, forgot this was a `parse` case. What @tunetheweb said below, then.\nFor parse we don't return input.\r\n\r\nIf we add a newline we get this:\r\n\r\n```\r\n% echo -n '{% macro foo() %}{% endmacro %}\\n' | sqlfluff parse -\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | [META] placeholder: [Type: 'compound', Raw: '{% macro foo() %}{% endmacro %}']\r\n[L: 1, P: 32] | newline: '\\n'\r\n```\r\n\r\nSo I'd expect the first two lines to be returned if newline isn't given.\r\n\r\nHere's some \"equivalent\" non-SQL that doesn't fail:\r\n\r\n```\r\n% echo \" \" | sqlfluff parse - \r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | whitespace: ' '\r\n[L: 1, P: 2] | newline: '\\n'\r\n\r\n% echo \"\" | sqlfluff parse - \r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | newline: '\\n'\r\n\r\n% echo \"--test\" | sqlfluff parse -\r\n[L: 1, P: 1] |file:\r\n[L: 1, P: 1] | comment: '--test'\r\n[L: 1, P: 7] | newline: '\\n'\r\n``\r\n\r\n\r\n", "created_at": "2021-10-09T15:32:42Z", "version": "0.6", "FAIL_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty"], "PASS_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catatrophic", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[--result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%"], "environment_setup_commit": "67023b85c41d23d6c6d69812a41b207c4f8a9331"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2386", "base_commit": "23d698607b45b8469c766b521d27e9a6e92e8739", "patch": "diff --git a/src/sqlfluff/core/rules/base.py b/src/sqlfluff/core/rules/base.py\n--- a/src/sqlfluff/core/rules/base.py\n+++ b/src/sqlfluff/core/rules/base.py\n@@ -875,7 +875,7 @@ def eval(self, **kwargs):\n \n plugin_name, code = rule_name_match.groups()\n # If the docstring is multiline, then we extract just summary.\n- description = cls.__doc__.split(\"\\n\")[0]\n+ description = cls.__doc__.replace(\"``\", \"'\").split(\"\\n\")[0]\n \n if plugin_name:\n code = f\"{plugin_name}_{code}\"\n", "test_patch": "diff --git a/test/core/rules/docstring_test.py b/test/core/rules/docstring_test.py\n--- a/test/core/rules/docstring_test.py\n+++ b/test/core/rules/docstring_test.py\n@@ -1,6 +1,7 @@\n \"\"\"Test rules docstring.\"\"\"\n import pytest\n \n+from sqlfluff import lint\n from sqlfluff.core.plugin.host import get_plugin_manager\n \n KEYWORD_ANTI = \"\\n | **Anti-pattern**\"\n@@ -34,3 +35,19 @@ def test_keyword_anti_before_best():\n assert rule.__doc__.index(KEYWORD_ANTI) < rule.__doc__.index(\n KEYWORD_BEST\n ), f\"{rule.__name__} keyword {KEYWORD_BEST} appears before {KEYWORD_ANTI}\"\n+\n+\n+def test_backtick_replace():\n+ \"\"\"Test replacing docstring double backticks for lint results.\"\"\"\n+ sql = \"\"\"\n+ SELECT\n+ foo.a,\n+ bar.b\n+ FROM foo\n+ JOIN bar;\n+ \"\"\"\n+ result = lint(sql, rules=[\"L051\"])\n+ # L051 docstring looks like:\n+ # ``INNER JOIN`` must be fully qualified.\n+ # Check the double bacticks (``) get replaced by a single quote (').\n+ assert result[0][\"description\"] == \"'INNER JOIN' must be fully qualified.\"\ndiff --git a/test/rules/std_L054_test.py b/test/rules/std_L054_test.py\n--- a/test/rules/std_L054_test.py\n+++ b/test/rules/std_L054_test.py\n@@ -29,7 +29,7 @@ def test__rules__std_L054_raised() -> None:\n assert len(results_l054) == 2\n assert (\n results_l054[0][\"description\"]\n- == \"Inconsistent column references in ``GROUP BY/ORDER BY`` clauses.\"\n+ == \"Inconsistent column references in 'GROUP BY/ORDER BY' clauses.\"\n )\n \n \n", "problem_statement": "Double backticks in Lint description\n\r\n(n.b. this affects a lot more rules than L051)\r\n\r\nThis was introduced in #2234 in which docstrings such as\r\n```\r\n`INNER JOIN` must be fully qualified.\r\n```\r\nwere replaced with \r\n```\r\n``INNER JOIN`` must be fully qualified.\r\n```\r\nso that they appear as code blocks in Sphinx for docs.\r\n\r\n\r\nHowever, our rules will use the first line of these docstrings in the event that no `description` is provided to the lint results.\r\n\r\nThis doesn't look great on the CLI so we should fix this. As far as I'm aware there are two approaches for this:\r\n1. Pass a `description` to all the `LintResult`s.\r\n2. Update the code that gets the default description from the docstring to do something like, replace the double backticks with a single one, or remove them, or do something clever like make them bold for the CLI and remove them for non-CLI.\r\n\r\nMy strong preference is number 2, but I'm open to discussion as to how exactly we do this \ud83d\ude04 \r\n\r\n@barrywhart @tunetheweb \n", "hints_text": "Number 2 sounds good to me!\n@barrywhart which variation?\nI would replace with single \"normal\" quotes: ' rather than \\`.\r\n\r\nThe clever approach could be cool for later, but I wouldn't try it now. I can't remember if we already handle detecting whether we're running in a terminal or not, because the techniques for doing bold or colored text don't work well when redirecting output to a file, etc.\n> The clever approach could be cool for later, but I wouldn't try it now. I can't remember if we already handle detecting whether we're running in a terminal or not, because the techniques for doing bold or colored text don't work well when redirecting output to a file, etc.\r\n\r\nYeah I think there's some `isatty` function we use in the formatter, but agree on the simple replace method for now \ud83d\ude04 ", "created_at": "2022-01-21T00:03:48Z", "version": "0.8", "FAIL_TO_PASS": ["test/core/rules/docstring_test.py::test_backtick_replace", "test/rules/std_L054_test.py::test__rules__std_L054_raised"], "PASS_TO_PASS": ["test/core/rules/docstring_test.py::test_content_count[\\n", "test/core/rules/docstring_test.py::test_keyword_anti_before_best", "test/rules/std_L054_test.py::test__rules__std_L054_unparsable", "test/rules/std_L054_test.py::test__rules__std_L054_noqa"], "environment_setup_commit": "a5c4eae4e3e419fe95460c9afd9cf39a35a470c4"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3411", "base_commit": "e60272a859e37e335088ae79a7ad59ea771545a1", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -1079,8 +1079,10 @@ def _print_out_violations_and_timing(\n output_stream.write(\"==== parsing violations ====\") # pragma: no cover\n for v in parsed_string.violations:\n output_stream.write(format_violation(v)) # pragma: no cover\n- if parsed_string.violations and parsed_string.config.get(\"dialect\") == \"ansi\":\n- output_stream.write(format_dialect_warning()) # pragma: no cover\n+ if parsed_string.violations:\n+ output_stream.write(\n+ format_dialect_warning(parsed_string.config.get(\"dialect\"))\n+ )\n \n if verbose >= 2:\n output_stream.write(\"==== timings ====\")\ndiff --git a/src/sqlfluff/cli/formatters.py b/src/sqlfluff/cli/formatters.py\n--- a/src/sqlfluff/cli/formatters.py\n+++ b/src/sqlfluff/cli/formatters.py\n@@ -187,12 +187,12 @@ def format_dialects(dialect_readout, verbose=0):\n return text_buffer.getvalue()\n \n \n-def format_dialect_warning(): # pragma: no cover\n- \"\"\"Output a warning for parsing errors found on the ansi dialect.\"\"\"\n+def format_dialect_warning(dialect):\n+ \"\"\"Output a warning for parsing errors.\"\"\"\n return colorize(\n (\n \"WARNING: Parsing errors found and dialect is set to \"\n- \"'ansi'. Have you configured your dialect?\"\n+ f\"'{dialect}'. Have you configured your dialect correctly?\"\n ),\n Color.lightgrey,\n )\n@@ -321,9 +321,9 @@ def dispatch_compilation_header(self, templater, message):\n f\"=== [{colorize(templater, Color.lightgrey)}] {message}\"\n ) # pragma: no cover\n \n- def dispatch_dialect_warning(self) -> None:\n+ def dispatch_dialect_warning(self, dialect) -> None:\n \"\"\"Dispatch a warning for dialects.\"\"\"\n- self._dispatch(format_dialect_warning()) # pragma: no cover\n+ self._dispatch(format_dialect_warning(dialect)) # pragma: no cover\n \n def _format_file_violations(\n self, fname: str, violations: List[SQLBaseError]\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -723,11 +723,11 @@ def lint_parsed(\n )\n \n # Safety flag for unset dialects\n- if parsed.config.get(\"dialect\") == \"ansi\" and linted_file.get_violations(\n+ if linted_file.get_violations(\n fixable=True if fix else None, types=SQLParseError\n ):\n if formatter: # pragma: no cover TODO?\n- formatter.dispatch_dialect_warning()\n+ formatter.dispatch_dialect_warning(parsed.config.get(\"dialect\"))\n \n return linted_file\n \n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -100,6 +100,53 @@ def test__cli__command_dialect():\n )\n \n \n+def test__cli__command_parse_error_dialect_explicit_warning():\n+ \"\"\"Check parsing error raises the right warning.\"\"\"\n+ # For any parsing error there should be a non-zero exit code\n+ # and a human-readable warning should be dislayed.\n+ # Dialect specified as commandline option.\n+ result = invoke_assert_code(\n+ ret_code=66,\n+ args=[\n+ parse,\n+ [\n+ \"-n\",\n+ \"--dialect\",\n+ \"postgres\",\n+ \"test/fixtures/cli/fail_many.sql\",\n+ ],\n+ ],\n+ )\n+ assert (\n+ \"WARNING: Parsing errors found and dialect is set to 'postgres'. \"\n+ \"Have you configured your dialect correctly?\" in result.stdout\n+ )\n+\n+\n+def test__cli__command_parse_error_dialect_implicit_warning():\n+ \"\"\"Check parsing error raises the right warning.\"\"\"\n+ # For any parsing error there should be a non-zero exit code\n+ # and a human-readable warning should be dislayed.\n+ # Dialect specified in .sqlfluff config.\n+ result = invoke_assert_code(\n+ ret_code=66,\n+ args=[\n+ # Config sets dialect to tsql\n+ parse,\n+ [\n+ \"-n\",\n+ \"--config\",\n+ \"test/fixtures/cli/extra_configs/.sqlfluff\",\n+ \"test/fixtures/cli/fail_many.sql\",\n+ ],\n+ ],\n+ )\n+ assert (\n+ \"WARNING: Parsing errors found and dialect is set to 'tsql'. \"\n+ \"Have you configured your dialect correctly?\" in result.stdout\n+ )\n+\n+\n def test__cli__command_dialect_legacy():\n \"\"\"Check the script raises the right exception on a legacy dialect.\"\"\"\n result = invoke_assert_code(\n", "problem_statement": "Update warning for parsing errors found on the ansi dialect\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nIn the past specifying a dialect was **optional**. If unspecified, the dialect defaulted to `ansi`. Because of this there is a warning presented when sqlfluff runs in parse mode and the dialect is set to ansi and parsing errors are encountered.\r\n\r\n`WARNING: Parsing errors found and dialect is set to 'ansi'. Have you configured your dialect?`\r\n\r\nCurrently, specifying a dialect is **mandatory**. Therefore this warning is perhaps not needed... and certainly not needed in its current form.\r\n\r\nI opened this issue to document the idea and solicit feedback. \r\n1. The simplest improvement to make the message more appropriate is to just change it to this:\r\n\r\n`WARNING: Parsing errors found and dialect is set to 'ansi'. Is 'ansi' the correct dialect?`\r\n\r\n2. On the other hand, we know that the user explicitly set the dialect to `ansi`. So why bother asking if it was intentional? We don't ask if you meant postgres or tsql. There's an argument to simply remove the warning altogether.\r\n\r\n3. Finally, we could potentially differentiate between `--dialect ansi` passed on the command line vs the dialect being picked up from a `.sqlfluff` config file. Perhaps the warning should be displayed only the in the case where the dialect was picked up implicitly from the config file.\n\n### Use case\n\n_No response_\n\n### Dialect\n\nansi\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [X] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "Pending feedback from the admins, I'm happy to submit a pull request on this one.\nBeen thinking about it, and I think we should show the message for all dialects. Some people might be using an incorrect dialect if their dialect is not supported.", "created_at": "2022-05-30T18:41:48Z", "version": "0.13", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-65]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-65-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files"], "environment_setup_commit": "6e8ce43a4958dbaa56256365c2a89d8db92e07d6"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2641", "base_commit": "b0ad239095b3cefb294c1b12c73c41e9f229aa81", "patch": "diff --git a/src/sqlfluff/core/rules/analysis/select_crawler.py b/src/sqlfluff/core/rules/analysis/select_crawler.py\n--- a/src/sqlfluff/core/rules/analysis/select_crawler.py\n+++ b/src/sqlfluff/core/rules/analysis/select_crawler.py\n@@ -129,6 +129,7 @@ class Query:\n parent: Optional[\"Query\"] = field(default=None)\n # Children (could be CTE, subselect, or other).\n children: List[\"Query\"] = field(default_factory=list)\n+ cte_name_segment: Optional[BaseSegment] = field(default=None)\n \n def lookup_cte(self, name: str, pop: bool = True) -> Optional[\"Query\"]:\n \"\"\"Look up a CTE by name, in the current or any parent scope.\"\"\"\n@@ -233,7 +234,7 @@ def finish_segment():\n \n # Stores the last CTE name we saw, so we can associate it with the\n # corresponding Query.\n- cte_name = None\n+ cte_name_segment: Optional[BaseSegment] = None\n \n # Visit segment and all its children\n for event, path in SelectCrawler.visit_segments(segment):\n@@ -273,10 +274,14 @@ def finish_segment():\n append_query(query)\n else:\n # We're processing a \"with\" statement.\n- if cte_name:\n+ if cte_name_segment:\n # If we have a CTE name, this is the Query for that\n # name.\n- query = self.query_class(QueryType.Simple, dialect)\n+ query = self.query_class(\n+ QueryType.Simple,\n+ dialect,\n+ cte_name_segment=cte_name_segment,\n+ )\n if path[-1].is_type(\"select_statement\", \"values_clause\"):\n # Add to the Query object we just created.\n query.selectables.append(Selectable(path[-1], dialect))\n@@ -286,8 +291,8 @@ def finish_segment():\n # to the Query later when we encounter those\n # child segments.\n pass\n- query_stack[-1].ctes[cte_name] = query\n- cte_name = None\n+ query_stack[-1].ctes[cte_name_segment.raw] = query\n+ cte_name_segment = None\n append_query(query)\n else:\n # There's no CTE name, so we're probably processing\n@@ -313,13 +318,13 @@ def finish_segment():\n elif path[-1].is_type(\"with_compound_statement\"):\n # Beginning a \"with\" statement, i.e. a block of CTEs.\n query = self.query_class(QueryType.WithCompound, dialect)\n- if cte_name:\n- query_stack[-1].ctes[cte_name] = query\n- cte_name = None\n+ if cte_name_segment:\n+ query_stack[-1].ctes[cte_name_segment.raw] = query\n+ cte_name_segment = None\n append_query(query)\n elif path[-1].is_type(\"common_table_expression\"):\n # This is a \"<<cte name>> AS\". Grab the name for later.\n- cte_name = path[-1].segments[0].raw\n+ cte_name_segment = path[-1].segments[0]\n elif event == \"end\":\n finish_segment()\n \ndiff --git a/src/sqlfluff/rules/L045.py b/src/sqlfluff/rules/L045.py\n--- a/src/sqlfluff/rules/L045.py\n+++ b/src/sqlfluff/rules/L045.py\n@@ -1,7 +1,5 @@\n \"\"\"Implementation of Rule L045.\"\"\"\n-from typing import Optional\n-\n-from sqlfluff.core.rules.base import BaseRule, LintResult, RuleContext\n+from sqlfluff.core.rules.base import BaseRule, EvalResultType, LintResult, RuleContext\n from sqlfluff.core.rules.analysis.select_crawler import Query, SelectCrawler\n \n \n@@ -49,12 +47,21 @@ def _visit_sources(cls, query: Query):\n if isinstance(source, Query):\n cls._visit_sources(source)\n \n- def _eval(self, context: RuleContext) -> Optional[LintResult]:\n+ def _eval(self, context: RuleContext) -> EvalResultType:\n if context.segment.is_type(\"statement\"):\n crawler = SelectCrawler(context.segment, context.dialect)\n if crawler.query_tree:\n # Begin analysis at the final, outer query (key=None).\n self._visit_sources(crawler.query_tree)\n if crawler.query_tree.ctes:\n- return LintResult(anchor=context.segment)\n+ return [\n+ LintResult(\n+ anchor=query.cte_name_segment,\n+ description=f\"Query defines CTE \"\n+ f'\"{query.cte_name_segment.raw}\" '\n+ f\"but does not use it.\",\n+ )\n+ for query in crawler.query_tree.ctes.values()\n+ if query.cte_name_segment\n+ ]\n return None\n", "test_patch": "diff --git a/test/fixtures/rules/std_rule_cases/L045.yml b/test/fixtures/rules/std_rule_cases/L045.yml\n--- a/test/fixtures/rules/std_rule_cases/L045.yml\n+++ b/test/fixtures/rules/std_rule_cases/L045.yml\n@@ -224,3 +224,13 @@ test_pass_spark3_values_clause_cte_2:\n configs:\n core:\n dialect: spark3\n+\n+test_fail_query_uses_templating:\n+ fail_str: |\n+ WITH\n+ random_gibberish AS (\n+ SELECT 1\n+ )\n+\n+ SELECT var_bar\n+ FROM {{ ref('issue_2235') }}\ndiff --git a/test/rules/std_L045_test.py b/test/rules/std_L045_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/rules/std_L045_test.py\n@@ -0,0 +1,46 @@\n+\"\"\"Tests the python routines within L045.\"\"\"\n+\n+import sqlfluff\n+\n+\n+def test__rules__std_L045_multiple_unused_ctes():\n+ \"\"\"Verify that L045 returns multiple lint issues, one per unused CTE.\"\"\"\n+ sql = \"\"\"\n+ WITH\n+ cte_1 AS (\n+ SELECT 1\n+ ),\n+ cte_2 AS (\n+ SELECT 2\n+ ),\n+ cte_3 AS (\n+ SELECT 3\n+ ),\n+ cte_4 AS (\n+ SELECT 4\n+ )\n+\n+ SELECT var_bar\n+ FROM cte_3\n+ \"\"\"\n+ result = sqlfluff.lint(sql, rules=[\"L045\"])\n+ assert result == [\n+ {\n+ \"code\": \"L045\",\n+ \"description\": 'Query defines CTE \"cte_1\" but does not use it.',\n+ \"line_no\": 3,\n+ \"line_pos\": 5,\n+ },\n+ {\n+ \"code\": \"L045\",\n+ \"description\": 'Query defines CTE \"cte_2\" but does not use it.',\n+ \"line_no\": 6,\n+ \"line_pos\": 5,\n+ },\n+ {\n+ \"code\": \"L045\",\n+ \"description\": 'Query defines CTE \"cte_4\" but does not use it.',\n+ \"line_no\": 12,\n+ \"line_pos\": 5,\n+ },\n+ ]\n", "problem_statement": "L045: Unused CTEs are not automatically detected when using jinja/dbt as a templater\n## Expected Behaviour\r\nWhen unused CTEs are used with jinja or dbt as a templater, these are detected by L045. \r\n\r\n## Observed Behaviour\r\nWhen ref() statements are included in a SQL file and dbt is used as a templater, these seem to interfere with the ability for rule L045 to detect the unused CTEs. The same behavior is observed when Jinja is included under the \"FROM\" statement of the relevant queries.\r\n\r\n## Steps to Reproduce\r\n(1). Generate a valid dbt project with at least two models with one variable each. For the purposes of this reproduction example, I am going to assume that one model is 'foo' with variable 'var_foo' and one model is 'bar' with variable 'var_bar'.\r\n \r\n(2) Using DBT as a templater and BigQuery as a dialect, run dbt lint on the following SQL file:\r\n\r\n```sql\r\nWITH\r\nrandom_gibberish AS (\r\n SELECT var_foo\r\n FROM\r\n {{ ref('foo') }}\r\n)\r\n\r\nSELECT var_bar\r\nFROM\r\n {{ ref('bar') }}\r\n```\r\n\r\nIf the templater is switched to Jinja, L045 again doesn't produce any errors.\r\n\r\n## Dialect\r\nBigquery\r\n\r\n## Version\r\nSQLFluff version is 0.10.0. Python version is 3.8.10.\r\nI'm using dbt 1.0.1 but the same issue occurs when Jinja is used as a templater.\r\n\r\n## Configuration\r\n```\r\n[sqlfluff]\r\ndialect = bigquery\r\nexclude_rules = L003,L008,L011,L014,L016,L029,L031,L034\r\n\r\n[sqlfluff:rules]\r\nmax_line_length = 120\r\ncomma_style = leading\r\n\r\n[sqlfluff:rules:L010]\r\ncapitalisation_policy = upper\r\n\r\n[sqlfluff:rules:L030]\r\ncapitalisation_policy = upper\r\n```\n", "hints_text": "", "created_at": "2022-02-14T20:13:17Z", "version": "0.9", "FAIL_TO_PASS": ["test/rules/std_L045_test.py::test__rules__std_L045_multiple_unused_ctes"], "PASS_TO_PASS": [], "environment_setup_commit": "a4dcf3f08d95cbde4efb39969b0ab8e33a791f21"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4777", "base_commit": "0243d4a1ba29e6cc3dc96bd9ea178d0f8a576a8f", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -693,12 +693,16 @@ def lint(\n \n \n def do_fixes(\n- result: LintingResult, formatter: Optional[OutputStreamFormatter] = None, **kwargs\n+ result: LintingResult,\n+ formatter: Optional[OutputStreamFormatter] = None,\n+ fixed_file_suffix: str = \"\",\n ):\n \"\"\"Actually do the fixes.\"\"\"\n if formatter and formatter.verbosity >= 0:\n click.echo(\"Persisting Changes...\")\n- res = result.persist_changes(formatter=formatter, **kwargs)\n+ res = result.persist_changes(\n+ formatter=formatter, fixed_file_suffix=fixed_file_suffix\n+ )\n if all(res.values()):\n if formatter and formatter.verbosity >= 0:\n click.echo(\"Done. Please check your files to confirm.\")\n@@ -774,12 +778,22 @@ def _paths_fix(\n click.echo(\"==== finding fixable violations ====\")\n exit_code = EXIT_SUCCESS\n \n+ if force and warn_force and formatter.verbosity >= 0:\n+ click.echo(\n+ f\"{formatter.colorize('FORCE MODE', Color.red)}: \" \"Attempting fixes...\"\n+ )\n+\n with PathAndUserErrorHandler(formatter):\n result: LintingResult = linter.lint_paths(\n paths,\n fix=True,\n ignore_non_existent_files=False,\n processes=processes,\n+ # If --force is set, then apply the changes as we go rather\n+ # than waiting until the end.\n+ apply_fixes=force,\n+ fixed_file_suffix=fixed_suffix,\n+ fix_even_unparsable=fix_even_unparsable,\n )\n \n if not fix_even_unparsable:\n@@ -788,25 +802,14 @@ def _paths_fix(\n # NB: We filter to linting violations here, because they're\n # the only ones which can be potentially fixed.\n num_fixable = result.num_violations(types=SQLLintError, fixable=True)\n+\n if num_fixable > 0:\n- if formatter.verbosity >= 0:\n+ if not force and formatter.verbosity >= 0:\n click.echo(\"==== fixing violations ====\")\n+\n click.echo(f\"{num_fixable} \" \"fixable linting violations found\")\n- if force:\n- if warn_force and formatter.verbosity >= 0:\n- click.echo(\n- f\"{formatter.colorize('FORCE MODE', Color.red)}: \"\n- \"Attempting fixes...\"\n- )\n- success = do_fixes(\n- result,\n- formatter,\n- types=SQLLintError,\n- fixed_file_suffix=fixed_suffix,\n- )\n- if not success:\n- sys.exit(EXIT_FAIL) # pragma: no cover\n- else:\n+\n+ if not force:\n click.echo(\n \"Are you sure you wish to attempt to fix these? [Y/n] \", nl=False\n )\n@@ -818,7 +821,6 @@ def _paths_fix(\n success = do_fixes(\n result,\n formatter,\n- types=SQLLintError,\n fixed_file_suffix=fixed_suffix,\n )\n if not success:\n@@ -886,7 +888,9 @@ def _paths_fix(\n is_flag=True,\n help=(\n \"Skip the confirmation prompt and go straight to applying \"\n- \"fixes. **Use this with caution.**\"\n+ \"fixes. Fixes will also be applied file by file, during the \"\n+ \"linting process, rather than waiting until all files are \"\n+ \"linted before fixing. **Use this with caution.**\"\n ),\n )\n @click.option(\ndiff --git a/src/sqlfluff/core/linter/linted_dir.py b/src/sqlfluff/core/linter/linted_dir.py\n--- a/src/sqlfluff/core/linter/linted_dir.py\n+++ b/src/sqlfluff/core/linter/linted_dir.py\n@@ -106,7 +106,7 @@ def stats(self) -> Dict[str, int]:\n )\n \n def persist_changes(\n- self, formatter: Any = None, fixed_file_suffix: str = \"\", **kwargs\n+ self, formatter: Any = None, fixed_file_suffix: str = \"\"\n ) -> Dict[str, Union[bool, str]]:\n \"\"\"Persist changes to files in the given path.\n \n@@ -115,19 +115,9 @@ def persist_changes(\n # Run all the fixes for all the files and return a dict\n buffer: Dict[str, Union[bool, str]] = {}\n for file in self.files:\n- if file.num_violations(fixable=True, **kwargs) > 0:\n- buffer[file.path] = file.persist_tree(suffix=fixed_file_suffix)\n- result: Union[bool, str]\n- if buffer[file.path] is True:\n- result = \"FIXED\"\n- else: # pragma: no cover\n- result = buffer[file.path]\n- else: # pragma: no cover TODO?\n- buffer[file.path] = True\n- result = \"SKIP\"\n-\n- if formatter:\n- formatter.dispatch_persist_filename(filename=file.path, result=result)\n+ buffer[file.path] = file.persist_tree(\n+ suffix=fixed_file_suffix, formatter=formatter\n+ )\n return buffer\n \n @property\ndiff --git a/src/sqlfluff/core/linter/linted_file.py b/src/sqlfluff/core/linter/linted_file.py\n--- a/src/sqlfluff/core/linter/linted_file.py\n+++ b/src/sqlfluff/core/linter/linted_file.py\n@@ -28,6 +28,8 @@\n from sqlfluff.core.errors import (\n SQLBaseError,\n SQLLintError,\n+ SQLParseError,\n+ SQLTemplaterError,\n CheckTuple,\n )\n from sqlfluff.core.templaters import TemplatedFile, RawFileSlice\n@@ -40,6 +42,8 @@\n # Instantiate the linter logger\n linter_logger: logging.Logger = logging.getLogger(\"sqlfluff.linter\")\n \n+TMP_PRS_ERROR_TYPES = (SQLTemplaterError, SQLParseError)\n+\n \n @dataclass\n class FileTimings:\n@@ -556,19 +560,46 @@ def _build_up_fixed_source_string(\n str_buff += raw_source_string[source_slice]\n return str_buff\n \n- def persist_tree(self, suffix: str = \"\") -> bool:\n+ def persist_tree(self, suffix: str = \"\", formatter: Any = None) -> bool:\n \"\"\"Persist changes to the given path.\"\"\"\n- write_buff, success = self.fix_string()\n-\n- if success:\n- fname = self.path\n- # If there is a suffix specified, then use it.s\n- if suffix:\n- root, ext = os.path.splitext(fname)\n- fname = root + suffix + ext\n- self._safe_create_replace_file(self.path, fname, write_buff, self.encoding)\n+ if self.num_violations(fixable=True) > 0:\n+ write_buff, success = self.fix_string()\n+\n+ if success:\n+ fname = self.path\n+ # If there is a suffix specified, then use it.s\n+ if suffix:\n+ root, ext = os.path.splitext(fname)\n+ fname = root + suffix + ext\n+ self._safe_create_replace_file(\n+ self.path, fname, write_buff, self.encoding\n+ )\n+ result_label = \"FIXED\"\n+ else: # pragma: no cover\n+ result_label = \"FAIL\"\n+ else:\n+ result_label = \"SKIP\"\n+ success = True\n+\n+ if formatter:\n+ formatter.dispatch_persist_filename(filename=self.path, result=result_label)\n+\n return success\n \n+ def discard_fixes_if_tmp_or_prs_errors(self) -> None:\n+ \"\"\"Discard lint fixes for files with templating or parse errors.\"\"\"\n+ num_errors = self.num_violations(\n+ types=TMP_PRS_ERROR_TYPES,\n+ filter_ignore=False,\n+ filter_warning=False,\n+ )\n+ if num_errors:\n+ # File has errors. Discard all the SQLLintError fixes:\n+ # they are potentially unsafe.\n+ for violation in self.violations:\n+ if isinstance(violation, SQLLintError):\n+ violation.fixes = []\n+\n @staticmethod\n def _safe_create_replace_file(\n input_path: str, output_path: str, write_buff: str, encoding: str\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -48,7 +48,11 @@\n NoQaDirective,\n RenderedFile,\n )\n-from sqlfluff.core.linter.linted_file import LintedFile, FileTimings\n+from sqlfluff.core.linter.linted_file import (\n+ LintedFile,\n+ FileTimings,\n+ TMP_PRS_ERROR_TYPES,\n+)\n from sqlfluff.core.linter.linted_dir import LintedDir\n from sqlfluff.core.linter.linting_result import LintingResult\n \n@@ -1149,6 +1153,9 @@ def lint_paths(\n ignore_non_existent_files: bool = False,\n ignore_files: bool = True,\n processes: Optional[int] = None,\n+ apply_fixes: bool = False,\n+ fixed_file_suffix: str = \"\",\n+ fix_even_unparsable: bool = False,\n ) -> LintingResult:\n \"\"\"Lint an iterable of paths.\"\"\"\n # If no paths specified - assume local\n@@ -1204,6 +1211,18 @@ def lint_paths(\n linter_logger.error(\"Fatal linting error. Halting further linting.\")\n break\n \n+ # If we're applying fixes, then do that here.\n+ if apply_fixes:\n+ num_tmp_prs_errors = linted_file.num_violations(\n+ types=TMP_PRS_ERROR_TYPES,\n+ filter_ignore=False,\n+ filter_warning=False,\n+ )\n+ if fix_even_unparsable or num_tmp_prs_errors == 0:\n+ linted_file.persist_tree(\n+ suffix=fixed_file_suffix, formatter=self.formatter\n+ )\n+\n # Progress bar for files is rendered only when there is more than one file.\n # Additionally, as it's updated after each loop, we need to get file name\n # from the next loop. This is why `enumerate` starts with `1` and there\ndiff --git a/src/sqlfluff/core/linter/linting_result.py b/src/sqlfluff/core/linter/linting_result.py\n--- a/src/sqlfluff/core/linter/linting_result.py\n+++ b/src/sqlfluff/core/linter/linting_result.py\n@@ -18,9 +18,6 @@\n \n from sqlfluff.core.errors import (\n CheckTuple,\n- SQLLintError,\n- SQLParseError,\n- SQLTemplaterError,\n )\n \n from sqlfluff.core.timing import TimingSummary, RuleTimingSummary\n@@ -28,6 +25,7 @@\n # Classes needed only for type checking\n from sqlfluff.core.parser.segments.base import BaseSegment\n from sqlfluff.core.linter.linted_dir import LintedDir\n+from sqlfluff.core.linter.linted_file import TMP_PRS_ERROR_TYPES\n \n \n class LintingResult:\n@@ -237,11 +235,13 @@ def as_records(self) -> List[dict]:\n if violations\n ]\n \n- def persist_changes(self, formatter, **kwargs) -> dict:\n+ def persist_changes(self, formatter, fixed_file_suffix: str = \"\") -> dict:\n \"\"\"Run all the fixes for all the files and return a dict.\"\"\"\n return self.combine_dicts(\n *(\n- path.persist_changes(formatter=formatter, **kwargs)\n+ path.persist_changes(\n+ formatter=formatter, fixed_file_suffix=fixed_file_suffix\n+ )\n for path in self.paths\n )\n )\n@@ -256,37 +256,29 @@ def tree(self) -> Optional[BaseSegment]: # pragma: no cover\n )\n return self.paths[0].tree\n \n- TMP_PRS_ERROR_TYPES = (SQLTemplaterError, SQLParseError)\n-\n def count_tmp_prs_errors(self) -> Tuple[int, int]:\n \"\"\"Count templating or parse errors before and after filtering.\"\"\"\n total_errors = self.num_violations(\n- types=self.TMP_PRS_ERROR_TYPES, filter_ignore=False, filter_warning=False\n+ types=TMP_PRS_ERROR_TYPES,\n+ filter_ignore=False,\n+ filter_warning=False,\n )\n num_filtered_errors = 0\n for linted_dir in self.paths:\n for linted_file in linted_dir.files:\n num_filtered_errors += linted_file.num_violations(\n- types=self.TMP_PRS_ERROR_TYPES\n+ types=TMP_PRS_ERROR_TYPES\n )\n return total_errors, num_filtered_errors\n \n def discard_fixes_for_lint_errors_in_files_with_tmp_or_prs_errors(self) -> None:\n \"\"\"Discard lint fixes for files with templating or parse errors.\"\"\"\n total_errors = self.num_violations(\n- types=self.TMP_PRS_ERROR_TYPES, filter_ignore=False, filter_warning=False\n+ types=TMP_PRS_ERROR_TYPES,\n+ filter_ignore=False,\n+ filter_warning=False,\n )\n if total_errors:\n for linted_dir in self.paths:\n for linted_file in linted_dir.files:\n- num_errors = linted_file.num_violations(\n- types=self.TMP_PRS_ERROR_TYPES,\n- filter_ignore=False,\n- filter_warning=False,\n- )\n- if num_errors:\n- # File has errors. Discard all the SQLLintError fixes:\n- # they are potentially unsafe.\n- for violation in linted_file.violations:\n- if isinstance(violation, SQLLintError):\n- violation.fixes = []\n+ linted_file.discard_fixes_if_tmp_or_prs_errors()\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -1940,8 +1940,8 @@ def test__cli__fix_multiple_errors_quiet_force():\n )\n normalised_output = result.output.replace(\"\\\\\", \"/\")\n assert normalised_output.startswith(\n- \"\"\"1 fixable linting violations found\n-== [test/fixtures/linter/multiple_sql_errors.sql] FIXED\"\"\"\n+ \"\"\"== [test/fixtures/linter/multiple_sql_errors.sql] FIXED\n+1 fixable linting violations found\"\"\"\n )\n \n \n", "problem_statement": "`fix` per file linted instead of at the end\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nI am just testing sqlfluff on a small example project.\r\nWe have configured it as part of `pre-commit`.\r\n\r\n```\r\n- repo: https://github.com/sqlfluff/sqlfluff\r\n rev: 1.0.0\r\n hooks:\r\n - id: sqlfluff-fix\r\n args: [--config, \".sqlfluff\", --disable_progress_bar, --processes, \"2\", --bench]\r\n files: \\.(sql)$\r\n exclude: sp_whoisactive.sql\r\n```\r\n\r\nProcessing our example already takes 30 minutes, I thus think formatting any real project would take 4+ hours.\r\n\r\nAt the moment the files are all formated first and _all together_ written at the very end. I see no benefit in writing at the very end, why are they not written sequentially?\n\n### Use case\n\nInstead of writing all formatted sql at the end, I would like to see files written sequentially.\n\n### Dialect\n\nmost likely all, i am working with t-sql.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n`fix` per file linted instead of at the end\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nI am just testing sqlfluff on a small example project.\r\nWe have configured it as part of `pre-commit`.\r\n\r\n```\r\n- repo: https://github.com/sqlfluff/sqlfluff\r\n rev: 1.0.0\r\n hooks:\r\n - id: sqlfluff-fix\r\n args: [--config, \".sqlfluff\", --disable_progress_bar, --processes, \"2\", --bench]\r\n files: \\.(sql)$\r\n exclude: sp_whoisactive.sql\r\n```\r\n\r\nProcessing our example already takes 30 minutes, I thus think formatting any real project would take 4+ hours.\r\n\r\nAt the moment the files are all formated first and _all together_ written at the very end. I see no benefit in writing at the very end, why are they not written sequentially?\n\n### Use case\n\nInstead of writing all formatted sql at the end, I would like to see files written sequentially.\n\n### Dialect\n\nmost likely all, i am working with t-sql.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "This is actually the same as #427 \nThis is actually the same as #427 ", "created_at": "2023-04-17T16:19:13Z", "version": "1.4", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_force"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse[command26]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command5-2]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command6-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command7-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command8-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command9-2]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_lint_warning", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql0]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql1]", "test/cli/commands_test.py::test__cli__command__fix[LT02-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_format_stdin[select", "test/cli/commands_test.py::test__cli__command_format_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_no_force", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass"], "environment_setup_commit": "d19de0ecd16d298f9e3bfb91da122734c40c01e5"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-1517", "base_commit": "304a197829f98e7425a46d872ada73176137e5ae", "patch": "diff --git a/src/sqlfluff/core/parser/helpers.py b/src/sqlfluff/core/parser/helpers.py\n--- a/src/sqlfluff/core/parser/helpers.py\n+++ b/src/sqlfluff/core/parser/helpers.py\n@@ -2,6 +2,7 @@\n \n from typing import Tuple, List, Any, Iterator, TYPE_CHECKING\n \n+from sqlfluff.core.errors import SQLParseError\n from sqlfluff.core.string_helpers import curtail_string\n \n if TYPE_CHECKING:\n@@ -26,11 +27,11 @@ def check_still_complete(\n \"\"\"Check that the segments in are the same as the segments out.\"\"\"\n initial_str = join_segments_raw(segments_in)\n current_str = join_segments_raw(matched_segments + unmatched_segments)\n- if initial_str != current_str: # pragma: no cover\n- raise RuntimeError(\n- \"Dropped elements in sequence matching! {!r} != {!r}\".format(\n- initial_str, current_str\n- )\n+\n+ if initial_str != current_str:\n+ raise SQLParseError(\n+ f\"Could not parse: {current_str}\",\n+ segment=unmatched_segments[0],\n )\n return True\n \n", "test_patch": "diff --git a/test/dialects/ansi_test.py b/test/dialects/ansi_test.py\n--- a/test/dialects/ansi_test.py\n+++ b/test/dialects/ansi_test.py\n@@ -3,7 +3,7 @@\n import pytest\n import logging\n \n-from sqlfluff.core import FluffConfig, Linter\n+from sqlfluff.core import FluffConfig, Linter, SQLParseError\n from sqlfluff.core.parser import Lexer\n \n \n@@ -214,3 +214,29 @@ def test__dialect__ansi_parse_indented_joins(sql_string, indented_joins, meta_lo\n idx for idx, raw_seg in enumerate(parsed.tree.iter_raw_seg()) if raw_seg.is_meta\n )\n assert res_meta_locs == meta_loc\n+\n+\[email protected](\n+ \"raw,expected_message\",\n+ [\n+ (\";;\", \"Line 1, Position 1: Found unparsable section: ';;'\"),\n+ (\"select id from tbl;\", \"\"),\n+ (\"select id from tbl;;\", \"Could not parse: ;\"),\n+ (\"select id from tbl;;;;;;\", \"Could not parse: ;;;;;\"),\n+ (\"select id from tbl;select id2 from tbl2;\", \"\"),\n+ (\n+ \"select id from tbl;;select id2 from tbl2;\",\n+ \"Could not parse: ;select id2 from tbl2;\",\n+ ),\n+ ],\n+)\n+def test__dialect__ansi_multiple_semicolons(raw: str, expected_message: str) -> None:\n+ \"\"\"Multiple semicolons should be properly handled.\"\"\"\n+ lnt = Linter()\n+ parsed = lnt.parse_string(raw)\n+\n+ assert len(parsed.violations) == (1 if expected_message else 0)\n+ if expected_message:\n+ violation = parsed.violations[0]\n+ assert isinstance(violation, SQLParseError)\n+ assert violation.desc() == expected_message\n", "problem_statement": "\"Dropped elements in sequence matching\" when doubled semicolon\n## Expected Behaviour\r\nFrankly, I'm not sure whether it (doubled `;`) should be just ignored or rather some specific rule should be triggered.\r\n## Observed Behaviour\r\n```console\r\n(.venv) ?master ~/prod/_inne/sqlfluff> echo \"select id from tbl;;\" | sqlfluff lint -\r\nTraceback (most recent call last):\r\n File \"/home/adam/prod/_inne/sqlfluff/.venv/bin/sqlfluff\", line 11, in <module>\r\n load_entry_point('sqlfluff', 'console_scripts', 'sqlfluff')()\r\n File \"/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py\", line 1137, in __call__\r\n return self.main(*args, **kwargs)\r\n File \"/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py\", line 1062, in main\r\n rv = self.invoke(ctx)\r\n File \"/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py\", line 1668, in invoke\r\n return _process_result(sub_ctx.command.invoke(sub_ctx))\r\n File \"/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py\", line 1404, in invoke\r\n return ctx.invoke(self.callback, **ctx.params)\r\n File \"/home/adam/prod/_inne/sqlfluff/.venv/lib/python3.9/site-packages/click/core.py\", line 763, in invoke\r\n return __callback(*args, **kwargs)\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/cli/commands.py\", line 347, in lint\r\n result = lnt.lint_string_wrapped(sys.stdin.read(), fname=\"stdin\")\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 789, in lint_string_wrapped\r\n linted_path.add(self.lint_string(string, fname=fname, fix=fix))\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 668, in lint_string\r\n parsed = self.parse_string(in_str=in_str, fname=fname, config=config)\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 607, in parse_string\r\n return self.parse_rendered(rendered, recurse=recurse)\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 313, in parse_rendered\r\n parsed, pvs = cls._parse_tokens(\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/linter/linter.py\", line 190, in _parse_tokens\r\n parsed: Optional[BaseSegment] = parser.parse(\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/parser/parser.py\", line 32, in parse\r\n parsed = root_segment.parse(parse_context=ctx)\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/parser/segments/base.py\", line 821, in parse\r\n check_still_complete(segments, m.matched_segments, m.unmatched_segments)\r\n File \"/home/adam/prod/_inne/sqlfluff/src/sqlfluff/core/parser/helpers.py\", line 30, in check_still_complete\r\n raise RuntimeError(\r\nRuntimeError: Dropped elements in sequence matching! 'select id from tbl;;' != ';'\r\n\r\n```\r\n## Steps to Reproduce\r\nRun \r\n```console\r\necho \"select id from tbl;;\" | sqlfluff lint -\r\n```\r\n## Dialect\r\ndefault (ansi)\r\n## Version\r\n```\r\nsqlfluff, version 0.6.6\r\nPython 3.9.5\r\n```\r\n## Configuration\r\nNone\r\n\n", "hints_text": "Sounds similar to #1458 where we should handle \"empty\" statement/files better?\nNope, that's the different issue. I doubt that solving one of them would help in other one. I think both issues should stay, just in the case.\nBut what do you think @tunetheweb - should it just ignore these `;;` or raise something like `Found unparsable section:`? \nJust tested and in BigQuery it's an error.\r\nInterestingly Oracle is fine with it.\r\n\r\nI think it should be raised as `Found unparsable section`.", "created_at": "2021-10-06T07:57:35Z", "version": "0.6", "FAIL_TO_PASS": ["test/dialects/ansi_test.py::test__dialect__ansi_multiple_semicolons[select"], "PASS_TO_PASS": ["test/dialects/ansi_test.py::test__dialect__ansi__file_lex[a", "test/dialects/ansi_test.py::test__dialect__ansi__file_lex[b.c-res1]", "test/dialects/ansi_test.py::test__dialect__ansi__file_lex[abc", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectKeywordSegment-select]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[NakedIdentifierSegment-online_sales]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[BareFunctionSegment-current_timestamp]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[FunctionSegment-current_timestamp()]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[NumericLiteralSegment-1000.0]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-online_sales", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[IntervalExpressionSegment-INTERVAL", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-CASE", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-CAST(ROUND(online_sales", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-name", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-MIN", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-DATE_ADD(CURRENT_DATE('America/New_York'),", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[1]]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[OFFSET(1)]]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-my_array[5:8]]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-4", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-bits[OFFSET(0)]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-(count_18_24", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-count_18_24", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectStatementSegment-SELECT", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-t.val/t.id]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-CAST(num", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-a.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-a.b.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-a.b.c.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ObjectReferenceSegment-a..c.*]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment--some_variable]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment--", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-concat(left(uaid,", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-c", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-c", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[ExpressionSegment-NULL::INT]", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[SelectClauseElementSegment-NULL::INT", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_parses[TruncateStatementSegment-TRUNCATE", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_not_match[ObjectReferenceSegment-\\n", "test/dialects/ansi_test.py::test__dialect__ansi_specific_segment_not_parse[SELECT", "test/dialects/ansi_test.py::test__dialect__ansi_is_whitespace", "test/dialects/ansi_test.py::test__dialect__ansi_parse_indented_joins[select", "test/dialects/ansi_test.py::test__dialect__ansi_multiple_semicolons[;;-Line"], "environment_setup_commit": "67023b85c41d23d6c6d69812a41b207c4f8a9331"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-880", "base_commit": "12f272627cd263f2acadf2ad976aec4819ee98c3", "patch": "diff --git a/plugins/sqlfluff-plugin-example/src/example/rules.py b/plugins/sqlfluff-plugin-example/src/example/rules.py\n--- a/plugins/sqlfluff-plugin-example/src/example/rules.py\n+++ b/plugins/sqlfluff-plugin-example/src/example/rules.py\n@@ -2,7 +2,7 @@\n \n from sqlfluff.core.plugin import hookimpl\n from sqlfluff.core.rules.base import (\n- BaseCrawler,\n+ BaseRule,\n LintResult,\n )\n from sqlfluff.core.rules.doc_decorators import (\n@@ -15,7 +15,7 @@\n \n \n @hookimpl\n-def get_rules() -> List[BaseCrawler]:\n+def get_rules() -> List[BaseRule]:\n \"\"\"Get plugin rules.\"\"\"\n return [Rule_Example_L001]\n \n@@ -41,7 +41,7 @@ def get_configs_info() -> dict:\n # to be displayed in the sqlfluff docs\n @document_fix_compatible\n @document_configuration\n-class Rule_Example_L001(BaseCrawler):\n+class Rule_Example_L001(BaseRule):\n \"\"\"ORDER BY on these columns is forbidden!\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/linter.py b/src/sqlfluff/core/linter.py\n--- a/src/sqlfluff/core/linter.py\n+++ b/src/sqlfluff/core/linter.py\n@@ -40,7 +40,7 @@\n from sqlfluff.core.parser.segments.base import BaseSegment, FixPatch\n from sqlfluff.core.parser.segments.meta import MetaSegment\n from sqlfluff.core.parser.segments.raw import RawSegment\n-from sqlfluff.core.rules.base import BaseCrawler\n+from sqlfluff.core.rules.base import BaseRule\n \n # Instantiate the linter logger\n linter_logger: logging.Logger = logging.getLogger(\"sqlfluff.linter\")\n@@ -728,7 +728,7 @@ def __init__(\n # Store references to user rule classes\n self.user_rules = user_rules or []\n \n- def get_ruleset(self, config: Optional[FluffConfig] = None) -> List[BaseCrawler]:\n+ def get_ruleset(self, config: Optional[FluffConfig] = None) -> List[BaseRule]:\n \"\"\"Get hold of a set of rules.\"\"\"\n rs = get_ruleset()\n # Register any user rules\ndiff --git a/src/sqlfluff/core/rules/base.py b/src/sqlfluff/core/rules/base.py\n--- a/src/sqlfluff/core/rules/base.py\n+++ b/src/sqlfluff/core/rules/base.py\n@@ -1,7 +1,7 @@\n-\"\"\"Implements the base crawler which all the rules are based on.\n+\"\"\"Implements the base rule class.\n \n-Crawlers, crawl through the trees returned by the parser and\n-evaluate particular rules.\n+Rules crawl through the trees returned by the parser and evaluate particular\n+rules.\n \n The intent is that it should be possible for the rules to be expressed\n as simply as possible, with as much of the complexity abstracted away.\n@@ -39,7 +39,7 @@ def process(self, msg, kwargs):\n \n \n class LintResult:\n- \"\"\"A class to hold the results of a crawl operation.\n+ \"\"\"A class to hold the results of a rule evaluation.\n \n Args:\n anchor (:obj:`BaseSegment`, optional): A segment which represents\n@@ -50,7 +50,7 @@ class LintResult:\n fixes which would correct this issue. If not present then it's\n assumed that this issue will have to manually fixed.\n memory (:obj:`dict`, optional): An object which stores any working\n- memory for the crawler. The `memory` returned in any `LintResult`\n+ memory for the rule. The `memory` returned in any `LintResult`\n will be passed as an input to the next segment to be crawled.\n description (:obj:`str`, optional): A description of the problem\n identified as part of this result. This will override the\n@@ -180,8 +180,8 @@ def __eq__(self, other):\n return True\n \n \n-class BaseCrawler:\n- \"\"\"The base class for a crawler, of which all rules are derived from.\n+class BaseRule:\n+ \"\"\"The base class for a rule.\n \n Args:\n code (:obj:`str`): The identifier for this rule, used in inclusion\n@@ -196,7 +196,7 @@ class BaseCrawler:\n def __init__(self, code, description, **kwargs):\n self.description = description\n self.code = code\n- # kwargs represents the config passed to the crawler. Add all kwargs as class attributes\n+ # kwargs represents the config passed to the rule. Add all kwargs as class attributes\n # so they can be accessed in rules which inherit from this class\n for key, value in kwargs.items():\n self.__dict__[key] = value\n@@ -262,7 +262,7 @@ def crawl(\n \"\"\"\n # parent stack should be a tuple if it exists\n \n- # crawlers, should evaluate on segments FIRST, before evaluating on their\n+ # Rules should evaluate on segments FIRST, before evaluating on their\n # children. They should also return a list of violations.\n \n parent_stack = parent_stack or ()\n@@ -510,7 +510,7 @@ def register(self, cls, plugin=None):\n .. code-block:: python\n \n @myruleset.register\n- class Rule_L001(BaseCrawler):\n+ class Rule_L001(BaseRule):\n \"Description of rule.\"\n \n def eval(self, **kwargs):\n@@ -561,7 +561,7 @@ def get_rulelist(self, config):\n for configuring the rules given the given config.\n \n Returns:\n- :obj:`list` of instantiated :obj:`BaseCrawler`.\n+ :obj:`list` of instantiated :obj:`BaseRule`.\n \n \"\"\"\n # Validate all generic rule configs\ndiff --git a/src/sqlfluff/core/rules/std/L001.py b/src/sqlfluff/core/rules/std/L001.py\n--- a/src/sqlfluff/core/rules/std/L001.py\n+++ b/src/sqlfluff/core/rules/std/L001.py\n@@ -1,10 +1,10 @@\n \"\"\"Implementation of Rule L001.\"\"\"\n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L001(BaseCrawler):\n+class Rule_L001(BaseRule):\n \"\"\"Unnecessary trailing whitespace.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L002.py b/src/sqlfluff/core/rules/std/L002.py\n--- a/src/sqlfluff/core/rules/std/L002.py\n+++ b/src/sqlfluff/core/rules/std/L002.py\n@@ -1,6 +1,6 @@\n \"\"\"Implementation of Rule L002.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import (\n document_configuration,\n document_fix_compatible,\n@@ -9,7 +9,7 @@\n \n @document_configuration\n @document_fix_compatible\n-class Rule_L002(BaseCrawler):\n+class Rule_L002(BaseRule):\n \"\"\"Mixed Tabs and Spaces in single whitespace.\n \n This rule will fail if a single section of whitespace\ndiff --git a/src/sqlfluff/core/rules/std/L003.py b/src/sqlfluff/core/rules/std/L003.py\n--- a/src/sqlfluff/core/rules/std/L003.py\n+++ b/src/sqlfluff/core/rules/std/L003.py\n@@ -1,6 +1,6 @@\n \"\"\"Implementation of Rule L003.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import (\n document_fix_compatible,\n document_configuration,\n@@ -9,7 +9,7 @@\n \n @document_fix_compatible\n @document_configuration\n-class Rule_L003(BaseCrawler):\n+class Rule_L003(BaseRule):\n \"\"\"Indentation not consistent with previous lines.\n \n Note:\ndiff --git a/src/sqlfluff/core/rules/std/L004.py b/src/sqlfluff/core/rules/std/L004.py\n--- a/src/sqlfluff/core/rules/std/L004.py\n+++ b/src/sqlfluff/core/rules/std/L004.py\n@@ -1,6 +1,6 @@\n \"\"\"Implementation of Rule L004.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import (\n document_fix_compatible,\n document_configuration,\n@@ -9,7 +9,7 @@\n \n @document_fix_compatible\n @document_configuration\n-class Rule_L004(BaseCrawler):\n+class Rule_L004(BaseRule):\n \"\"\"Incorrect indentation type.\n \n Note 1: spaces are only fixed to tabs if the number of spaces in the\ndiff --git a/src/sqlfluff/core/rules/std/L005.py b/src/sqlfluff/core/rules/std/L005.py\n--- a/src/sqlfluff/core/rules/std/L005.py\n+++ b/src/sqlfluff/core/rules/std/L005.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L005.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L005(BaseCrawler):\n+class Rule_L005(BaseRule):\n \"\"\"Commas should not have whitespace directly before them.\n \n Unless it's an indent. Trailing/leading commas are dealt with\ndiff --git a/src/sqlfluff/core/rules/std/L006.py b/src/sqlfluff/core/rules/std/L006.py\n--- a/src/sqlfluff/core/rules/std/L006.py\n+++ b/src/sqlfluff/core/rules/std/L006.py\n@@ -1,12 +1,12 @@\n \"\"\"Implementation of Rule L006.\"\"\"\n \n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L006(BaseCrawler):\n+class Rule_L006(BaseRule):\n \"\"\"Operators should be surrounded by a single whitespace.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L007.py b/src/sqlfluff/core/rules/std/L007.py\n--- a/src/sqlfluff/core/rules/std/L007.py\n+++ b/src/sqlfluff/core/rules/std/L007.py\n@@ -1,9 +1,9 @@\n \"\"\"Implementation of Rule L007.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n \n \n-class Rule_L007(BaseCrawler):\n+class Rule_L007(BaseRule):\n \"\"\"Operators near newlines should be after, not before the newline.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L008.py b/src/sqlfluff/core/rules/std/L008.py\n--- a/src/sqlfluff/core/rules/std/L008.py\n+++ b/src/sqlfluff/core/rules/std/L008.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L008.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L008(BaseCrawler):\n+class Rule_L008(BaseRule):\n \"\"\"Commas should be followed by a single whitespace unless followed by a comment.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L009.py b/src/sqlfluff/core/rules/std/L009.py\n--- a/src/sqlfluff/core/rules/std/L009.py\n+++ b/src/sqlfluff/core/rules/std/L009.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L009.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L009(BaseCrawler):\n+class Rule_L009(BaseRule):\n \"\"\"Files must end with a trailing newline.\"\"\"\n \n def _eval(self, segment, siblings_post, parent_stack, **kwargs):\ndiff --git a/src/sqlfluff/core/rules/std/L010.py b/src/sqlfluff/core/rules/std/L010.py\n--- a/src/sqlfluff/core/rules/std/L010.py\n+++ b/src/sqlfluff/core/rules/std/L010.py\n@@ -1,7 +1,7 @@\n \"\"\"Implementation of Rule L010.\"\"\"\n \n from typing import Tuple, List\n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import (\n document_fix_compatible,\n document_configuration,\n@@ -10,7 +10,7 @@\n \n @document_fix_compatible\n @document_configuration\n-class Rule_L010(BaseCrawler):\n+class Rule_L010(BaseRule):\n \"\"\"Inconsistent capitalisation of keywords.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L011.py b/src/sqlfluff/core/rules/std/L011.py\n--- a/src/sqlfluff/core/rules/std/L011.py\n+++ b/src/sqlfluff/core/rules/std/L011.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L011.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L011(BaseCrawler):\n+class Rule_L011(BaseRule):\n \"\"\"Implicit aliasing of table not allowed. Use explicit `AS` clause.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L013.py b/src/sqlfluff/core/rules/std/L013.py\n--- a/src/sqlfluff/core/rules/std/L013.py\n+++ b/src/sqlfluff/core/rules/std/L013.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L013.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n from sqlfluff.core.rules.doc_decorators import document_configuration\n \n \n @document_configuration\n-class Rule_L013(BaseCrawler):\n+class Rule_L013(BaseRule):\n \"\"\"Column expression without alias. Use explicit `AS` clause.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L015.py b/src/sqlfluff/core/rules/std/L015.py\n--- a/src/sqlfluff/core/rules/std/L015.py\n+++ b/src/sqlfluff/core/rules/std/L015.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L015.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L015(BaseCrawler):\n+class Rule_L015(BaseRule):\n \"\"\"DISTINCT used with parentheses.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L017.py b/src/sqlfluff/core/rules/std/L017.py\n--- a/src/sqlfluff/core/rules/std/L017.py\n+++ b/src/sqlfluff/core/rules/std/L017.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L017.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L017(BaseCrawler):\n+class Rule_L017(BaseRule):\n \"\"\"Function name not immediately followed by bracket.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L018.py b/src/sqlfluff/core/rules/std/L018.py\n--- a/src/sqlfluff/core/rules/std/L018.py\n+++ b/src/sqlfluff/core/rules/std/L018.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L018.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L018(BaseCrawler):\n+class Rule_L018(BaseRule):\n \"\"\"WITH clause closing bracket should be aligned with WITH keyword.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L019.py b/src/sqlfluff/core/rules/std/L019.py\n--- a/src/sqlfluff/core/rules/std/L019.py\n+++ b/src/sqlfluff/core/rules/std/L019.py\n@@ -2,7 +2,7 @@\n \n from typing import Dict, Any\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import (\n document_fix_compatible,\n document_configuration,\n@@ -11,7 +11,7 @@\n \n @document_fix_compatible\n @document_configuration\n-class Rule_L019(BaseCrawler):\n+class Rule_L019(BaseRule):\n \"\"\"Leading/Trailing comma enforcement.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L020.py b/src/sqlfluff/core/rules/std/L020.py\n--- a/src/sqlfluff/core/rules/std/L020.py\n+++ b/src/sqlfluff/core/rules/std/L020.py\n@@ -2,11 +2,11 @@\n \n import itertools\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n from sqlfluff.core.rules.analysis.select import get_select_statement_info\n \n \n-class Rule_L020(BaseCrawler):\n+class Rule_L020(BaseRule):\n \"\"\"Table aliases should be unique within each clause.\"\"\"\n \n def _lint_references_and_aliases(\ndiff --git a/src/sqlfluff/core/rules/std/L021.py b/src/sqlfluff/core/rules/std/L021.py\n--- a/src/sqlfluff/core/rules/std/L021.py\n+++ b/src/sqlfluff/core/rules/std/L021.py\n@@ -1,10 +1,10 @@\n \"\"\"Implementation of Rule L021.\"\"\"\n \n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n \n \n-class Rule_L021(BaseCrawler):\n+class Rule_L021(BaseRule):\n \"\"\"Ambiguous use of DISTINCT in select statement with GROUP BY.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L022.py b/src/sqlfluff/core/rules/std/L022.py\n--- a/src/sqlfluff/core/rules/std/L022.py\n+++ b/src/sqlfluff/core/rules/std/L022.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L022.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L022(BaseCrawler):\n+class Rule_L022(BaseRule):\n \"\"\"Blank line expected but not found after CTE closing bracket.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L023.py b/src/sqlfluff/core/rules/std/L023.py\n--- a/src/sqlfluff/core/rules/std/L023.py\n+++ b/src/sqlfluff/core/rules/std/L023.py\n@@ -2,12 +2,12 @@\n \n from typing import Optional, List\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L023(BaseCrawler):\n+class Rule_L023(BaseRule):\n \"\"\"Single whitespace expected after AS in WITH clause.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L029.py b/src/sqlfluff/core/rules/std/L029.py\n--- a/src/sqlfluff/core/rules/std/L029.py\n+++ b/src/sqlfluff/core/rules/std/L029.py\n@@ -1,12 +1,12 @@\n \"\"\"Implementation of Rule L029.\"\"\"\n \n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n from sqlfluff.core.rules.doc_decorators import document_configuration\n \n \n @document_configuration\n-class Rule_L029(BaseCrawler):\n+class Rule_L029(BaseRule):\n \"\"\"Keywords should not be used as identifiers.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L031.py b/src/sqlfluff/core/rules/std/L031.py\n--- a/src/sqlfluff/core/rules/std/L031.py\n+++ b/src/sqlfluff/core/rules/std/L031.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L031.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L031(BaseCrawler):\n+class Rule_L031(BaseRule):\n \"\"\"Avoid table aliases in from clauses and join conditions.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L032.py b/src/sqlfluff/core/rules/std/L032.py\n--- a/src/sqlfluff/core/rules/std/L032.py\n+++ b/src/sqlfluff/core/rules/std/L032.py\n@@ -1,9 +1,9 @@\n \"\"\"Implementation of Rule L032.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n \n \n-class Rule_L032(BaseCrawler):\n+class Rule_L032(BaseRule):\n \"\"\"Prefer specifying join keys instead of using \"USING\".\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L033.py b/src/sqlfluff/core/rules/std/L033.py\n--- a/src/sqlfluff/core/rules/std/L033.py\n+++ b/src/sqlfluff/core/rules/std/L033.py\n@@ -1,9 +1,9 @@\n \"\"\"Implementation of Rule L033.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n \n \n-class Rule_L033(BaseCrawler):\n+class Rule_L033(BaseRule):\n \"\"\"UNION ALL is preferred over UNION.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L034.py b/src/sqlfluff/core/rules/std/L034.py\n--- a/src/sqlfluff/core/rules/std/L034.py\n+++ b/src/sqlfluff/core/rules/std/L034.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L034.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L034(BaseCrawler):\n+class Rule_L034(BaseRule):\n \"\"\"Use wildcards then simple select targets before calculations and aggregates.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L035.py b/src/sqlfluff/core/rules/std/L035.py\n--- a/src/sqlfluff/core/rules/std/L035.py\n+++ b/src/sqlfluff/core/rules/std/L035.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L035.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L035(BaseCrawler):\n+class Rule_L035(BaseRule):\n \"\"\"Do not specify \"else null\" in a case when statement (redundant).\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L036.py b/src/sqlfluff/core/rules/std/L036.py\n--- a/src/sqlfluff/core/rules/std/L036.py\n+++ b/src/sqlfluff/core/rules/std/L036.py\n@@ -3,7 +3,7 @@\n from typing import List, NamedTuple\n \n from sqlfluff.core.parser import BaseSegment\n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n@@ -18,7 +18,7 @@ class SelectTargetsInfo(NamedTuple):\n \n \n @document_fix_compatible\n-class Rule_L036(BaseCrawler):\n+class Rule_L036(BaseRule):\n \"\"\"Select targets should be on a new line unless there is only one select target.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L037.py b/src/sqlfluff/core/rules/std/L037.py\n--- a/src/sqlfluff/core/rules/std/L037.py\n+++ b/src/sqlfluff/core/rules/std/L037.py\n@@ -2,7 +2,7 @@\n \n from typing import NamedTuple, Optional, List\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.parser import BaseSegment\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n@@ -15,7 +15,7 @@ class OrderByColumnInfo(NamedTuple):\n \n \n @document_fix_compatible\n-class Rule_L037(BaseCrawler):\n+class Rule_L037(BaseRule):\n \"\"\"Ambiguous ordering directions for columns in order by clause.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L038.py b/src/sqlfluff/core/rules/std/L038.py\n--- a/src/sqlfluff/core/rules/std/L038.py\n+++ b/src/sqlfluff/core/rules/std/L038.py\n@@ -1,12 +1,12 @@\n \"\"\"Implementation of Rule L038.\"\"\"\n \n-from ..base import BaseCrawler, LintFix, LintResult\n+from ..base import BaseRule, LintFix, LintResult\n from ..doc_decorators import document_fix_compatible, document_configuration\n \n \n @document_configuration\n @document_fix_compatible\n-class Rule_L038(BaseCrawler):\n+class Rule_L038(BaseRule):\n \"\"\"Trailing commas within select clause.\n \n For some database backends this is allowed. For some users\ndiff --git a/src/sqlfluff/core/rules/std/L039.py b/src/sqlfluff/core/rules/std/L039.py\n--- a/src/sqlfluff/core/rules/std/L039.py\n+++ b/src/sqlfluff/core/rules/std/L039.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L039.\"\"\"\n \n-from ..base import BaseCrawler, LintFix, LintResult\n+from ..base import BaseRule, LintFix, LintResult\n from ..doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L039(BaseCrawler):\n+class Rule_L039(BaseRule):\n \"\"\"Unnecessary whitespace found.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L041.py b/src/sqlfluff/core/rules/std/L041.py\n--- a/src/sqlfluff/core/rules/std/L041.py\n+++ b/src/sqlfluff/core/rules/std/L041.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L040.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L041(BaseCrawler):\n+class Rule_L041(BaseRule):\n \"\"\"SELECT clause modifiers such as DISTINCT must be on the same line as SELECT.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L042.py b/src/sqlfluff/core/rules/std/L042.py\n--- a/src/sqlfluff/core/rules/std/L042.py\n+++ b/src/sqlfluff/core/rules/std/L042.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L042.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n from sqlfluff.core.rules.doc_decorators import document_configuration\n \n \n @document_configuration\n-class Rule_L042(BaseCrawler):\n+class Rule_L042(BaseRule):\n \"\"\"Join/From clauses should not contain subqueries. Use CTEs instead.\n \n By default this rule is configured to allow subqueries within `FROM`\ndiff --git a/src/sqlfluff/core/rules/std/L043.py b/src/sqlfluff/core/rules/std/L043.py\n--- a/src/sqlfluff/core/rules/std/L043.py\n+++ b/src/sqlfluff/core/rules/std/L043.py\n@@ -1,11 +1,11 @@\n \"\"\"Implementation of Rule L043.\"\"\"\n \n-from sqlfluff.core.rules.base import BaseCrawler, LintFix, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L043(BaseCrawler):\n+class Rule_L043(BaseRule):\n \"\"\"Unnecessary case when statement. Use the \"when\" condition itself.\n \n If a case when else statement returns booleans, we can reduce it to the\ndiff --git a/src/sqlfluff/core/rules/std/L044.py b/src/sqlfluff/core/rules/std/L044.py\n--- a/src/sqlfluff/core/rules/std/L044.py\n+++ b/src/sqlfluff/core/rules/std/L044.py\n@@ -3,7 +3,7 @@\n \n from sqlfluff.core.rules.analysis.select_crawler import SelectCrawler\n from sqlfluff.core.dialects.base import Dialect\n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n \n \n class RuleFailure(Exception):\n@@ -12,7 +12,7 @@ class RuleFailure(Exception):\n pass\n \n \n-class Rule_L044(BaseCrawler):\n+class Rule_L044(BaseRule):\n \"\"\"Query produces an unknown number of result columns.\n \n | **Anti-pattern**\ndiff --git a/src/sqlfluff/core/rules/std/L045.py b/src/sqlfluff/core/rules/std/L045.py\n--- a/src/sqlfluff/core/rules/std/L045.py\n+++ b/src/sqlfluff/core/rules/std/L045.py\n@@ -2,13 +2,13 @@\n from typing import Dict, List\n \n from sqlfluff.core.dialects.base import Dialect\n-from sqlfluff.core.rules.base import BaseCrawler, LintResult\n+from sqlfluff.core.rules.base import BaseRule, LintResult\n from sqlfluff.core.rules.analysis.select_crawler import SelectCrawler\n from sqlfluff.core.rules.doc_decorators import document_fix_compatible\n \n \n @document_fix_compatible\n-class Rule_L045(BaseCrawler):\n+class Rule_L045(BaseRule):\n \"\"\"Query defines a CTE (common-table expression) but does not use it.\n \n | **Anti-pattern**\n", "test_patch": "diff --git a/test/core/rules/std_test.py b/test/core/rules/std_test.py\n--- a/test/core/rules/std_test.py\n+++ b/test/core/rules/std_test.py\n@@ -2,7 +2,7 @@\n import pytest\n \n from sqlfluff.core import Linter\n-from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix\n+from sqlfluff.core.rules.base import BaseRule, LintResult, LintFix\n from sqlfluff.core.rules import get_ruleset\n from sqlfluff.core.rules.doc_decorators import document_configuration\n from sqlfluff.core.config import FluffConfig\n@@ -21,14 +21,14 @@\n from sqlfluff.core.rules.std import get_rules_from_path\n \n \n-class Rule_T042(BaseCrawler):\n+class Rule_T042(BaseRule):\n \"\"\"A dummy rule.\"\"\"\n \n def _eval(self, segment, raw_stack, **kwargs):\n pass\n \n \n-class Rule_T001(BaseCrawler):\n+class Rule_T001(BaseRule):\n \"\"\"A deliberately malicious rule.\"\"\"\n \n def _eval(self, segment, raw_stack, **kwargs):\n@@ -205,7 +205,7 @@ def test_improper_configs_are_rejected(rule_config_dict):\n def test_rules_cannot_be_instantiated_without_declared_configs():\n \"\"\"Ensure that new rules must be instantiated with config values.\"\"\"\n \n- class NewRule(BaseCrawler):\n+ class NewRule(BaseRule):\n config_keywords = [\"comma_style\"]\n \n new_rule = NewRule(code=\"L000\", description=\"\", comma_style=\"trailing\")\n@@ -220,7 +220,7 @@ def test_rules_configs_are_dynamically_documented():\n \"\"\"Ensure that rule configurations are added to the class docstring.\"\"\"\n \n @document_configuration\n- class RuleWithConfig(BaseCrawler):\n+ class RuleWithConfig(BaseRule):\n \"\"\"A new rule with configuration.\"\"\"\n \n config_keywords = [\"comma_style\", \"only_aliases\"]\n@@ -229,7 +229,7 @@ class RuleWithConfig(BaseCrawler):\n assert \"only_aliases\" in RuleWithConfig.__doc__\n \n @document_configuration\n- class RuleWithoutConfig(BaseCrawler):\n+ class RuleWithoutConfig(BaseRule):\n \"\"\"A new rule without configuration.\"\"\"\n \n pass\n@@ -242,7 +242,7 @@ def test_rule_exception_is_caught_to_validation():\n std_rule_set = get_ruleset()\n \n @std_rule_set.register\n- class Rule_T000(BaseCrawler):\n+ class Rule_T000(BaseRule):\n \"\"\"Rule that throws an exception.\"\"\"\n \n def _eval(self, segment, parent_stack, **kwargs):\n", "problem_statement": "Rename BaseCrawler class as BaseRule to be clearer, avoid confusion with analysis helper classes, e.g. SelectCrawler\nDiscussed here:\r\nhttps://github.com/sqlfluff/sqlfluff/pull/779#pullrequestreview-604167034\r\n\n", "hints_text": "Yes. The fact that it's called a crawler is a historic artifact when I thought that the crawlers and rules might be separate. Given they're not, this makes total sense.", "created_at": "2021-03-21T01:36:49Z", "version": "0.4", "FAIL_TO_PASS": ["test/core/rules/std_test.py::test__rules__user_rules", "test/core/rules/std_test.py::test__rules__runaway_fail_catch", "test/core/rules/std_test.py::test__rules__std_file[L001-test/fixtures/linter/indentation_errors.sql-violations0]", "test/core/rules/std_test.py::test__rules__std_file[L002-test/fixtures/linter/indentation_errors.sql-violations1]", "test/core/rules/std_test.py::test__rules__std_file[L003-test/fixtures/linter/indentation_errors.sql-violations2]", "test/core/rules/std_test.py::test__rules__std_file[L004-test/fixtures/linter/indentation_errors.sql-violations3]", "test/core/rules/std_test.py::test__rules__std_file[L005-test/fixtures/linter/whitespace_errors.sql-violations4]", "test/core/rules/std_test.py::test__rules__std_file[L019-test/fixtures/linter/whitespace_errors.sql-violations5]", "test/core/rules/std_test.py::test__rules__std_file[L008-test/fixtures/linter/whitespace_errors.sql-violations6]", "test/core/rules/std_test.py::test__rules__std_file[L006-test/fixtures/linter/operator_errors.sql-violations7]", "test/core/rules/std_test.py::test__rules__std_file[L007-test/fixtures/linter/operator_errors.sql-violations8]", "test/core/rules/std_test.py::test__rules__std_file[L006-test/fixtures/linter/operator_errors_negative.sql-violations9]", "test/core/rules/std_test.py::test__rules__std_file[L003-test/fixtures/linter/indentation_error_hard.sql-violations10]", "test/core/rules/std_test.py::test__rules__std_file[L003-test/fixtures/linter/indentation_error_contained.sql-violations11]", "test/core/rules/std_test.py::test__rules__std_file[L016-test/fixtures/linter/block_comment_errors.sql-violations12]", "test/core/rules/std_test.py::test__rules__std_file[L016-test/fixtures/linter/block_comment_errors_2.sql-violations13]", "test/core/rules/std_test.py::test__rules__std_file[L027-test/fixtures/linter/column_references.sql-violations14]", "test/core/rules/std_test.py::test__rules__std_file[L027-test/fixtures/linter/column_references_bare_function.sql-violations15]", "test/core/rules/std_test.py::test__rules__std_file[L026-test/fixtures/linter/column_references.sql-violations16]", "test/core/rules/std_test.py::test__rules__std_file[L025-test/fixtures/linter/column_references.sql-violations17]", "test/core/rules/std_test.py::test__rules__std_file[L021-test/fixtures/linter/select_distinct_group_by.sql-violations18]", "test/core/rules/std_test.py::test__rules__std_file[L006-test/fixtures/linter/operator_errors_ignore.sql-violations19]", "test/core/rules/std_test.py::test__rules__std_file[L031-test/fixtures/linter/aliases_in_join_error.sql-violations20]", "test/core/rules/std_test.py::test__rules__std_L003_process_raw_stack", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict0]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict1]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict2]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict3]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict4]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict5]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict6]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict7]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict8]", "test/core/rules/std_test.py::test_improper_configs_are_rejected[rule_config_dict9]", "test/core/rules/std_test.py::test_rules_cannot_be_instantiated_without_declared_configs", "test/core/rules/std_test.py::test_rules_configs_are_dynamically_documented", "test/core/rules/std_test.py::test_rule_exception_is_caught_to_validation", "test/core/rules/std_test.py::test_std_rule_import_fail_bad_naming", "test/core/rules/std_test.py::test_rule_set_return_informative_error_when_rule_not_registered"], "PASS_TO_PASS": [], "environment_setup_commit": "cbdcfb09feb4883de91de142956c3be6ac7f827d"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4041", "base_commit": "66fd602d0824138f212082c8fdf381266a9edad3", "patch": "diff --git a/src/sqlfluff/core/errors.py b/src/sqlfluff/core/errors.py\n--- a/src/sqlfluff/core/errors.py\n+++ b/src/sqlfluff/core/errors.py\n@@ -1,5 +1,5 @@\n \"\"\"Errors - these are closely linked to what used to be called violations.\"\"\"\n-from typing import Optional, Tuple, List\n+from typing import Optional, Tuple, Any, List\n \n CheckTuple = Tuple[str, int, int]\n \n@@ -85,6 +85,18 @@ def get_info_dict(self):\n \"description\": self.desc(),\n }\n \n+ def check_tuple(self) -> CheckTuple:\n+ \"\"\"Get a tuple representing this error. Mostly for testing.\"\"\"\n+ return (\n+ self.rule_code(),\n+ self.line_no,\n+ self.line_pos,\n+ )\n+\n+ def source_signature(self) -> Tuple[Any, ...]:\n+ \"\"\"Return hashable source signature for deduplication.\"\"\"\n+ return (self.check_tuple(), self.desc())\n+\n def ignore_if_in(self, ignore_iterable: List[str]):\n \"\"\"Ignore this violation if it matches the iterable.\"\"\"\n if self._identifier in ignore_iterable:\n@@ -189,13 +201,21 @@ def fixable(self):\n return True\n return False\n \n- def check_tuple(self) -> CheckTuple:\n- \"\"\"Get a tuple representing this error. Mostly for testing.\"\"\"\n- return (\n- self.rule.code,\n- self.line_no,\n- self.line_pos,\n+ def source_signature(self) -> Tuple[Any, ...]:\n+ \"\"\"Return hashable source signature for deduplication.\n+\n+ For linting errors we need to dedupe on more than just location and\n+ description, we also need to check the edits potentially made, both\n+ in the templated file but also in the source.\n+ \"\"\"\n+ fix_raws = tuple(\n+ tuple(e.raw for e in f.edit) if f.edit else None for f in self.fixes\n+ )\n+ source_fixes = tuple(\n+ tuple(tuple(e.source_fixes) for e in f.edit) if f.edit else None\n+ for f in self.fixes\n )\n+ return (self.check_tuple(), self.description, fix_raws, source_fixes)\n \n def __repr__(self):\n return \"<SQLLintError: rule {} pos:{!r}, #fixes: {}, description: {}>\".format(\ndiff --git a/src/sqlfluff/core/linter/linted_file.py b/src/sqlfluff/core/linter/linted_file.py\n--- a/src/sqlfluff/core/linter/linted_file.py\n+++ b/src/sqlfluff/core/linter/linted_file.py\n@@ -54,18 +54,43 @@ def check_tuples(self, raise_on_non_linting_violations=True) -> List[CheckTuple]\n \"\"\"Make a list of check_tuples.\n \n This assumes that all the violations found are\n- linting violations (and therefore implement `check_tuple()`).\n- If they don't then this function raises that error.\n+ linting violations. If they don't then this function\n+ raises that error.\n \"\"\"\n vs: List[CheckTuple] = []\n v: SQLLintError\n for v in self.get_violations():\n- if hasattr(v, \"check_tuple\"):\n+ if isinstance(v, SQLLintError):\n vs.append(v.check_tuple())\n elif raise_on_non_linting_violations:\n raise v\n return vs\n \n+ @staticmethod\n+ def deduplicate_in_source_space(\n+ violations: List[SQLBaseError],\n+ ) -> List[SQLBaseError]:\n+ \"\"\"Removes duplicates in the source space.\n+\n+ This is useful for templated files with loops, where we'll\n+ get a violation for each pass around the loop, but the user\n+ only cares about it once and we're only going to fix it once.\n+\n+ By filtering them early we get a more a more helpful CLI\n+ output *and* and more efficient fixing routine (by handling\n+ fewer fixes).\n+ \"\"\"\n+ new_violations = []\n+ dedupe_buffer = set()\n+ for v in violations:\n+ signature = v.source_signature()\n+ if signature not in dedupe_buffer:\n+ new_violations.append(v)\n+ dedupe_buffer.add(signature)\n+ else:\n+ linter_logger.debug(\"Removing duplicate source violation: %s\", v)\n+ return new_violations\n+\n def get_violations(\n self,\n rules: Optional[Union[str, Tuple[str, ...]]] = None,\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -736,7 +736,8 @@ def lint_parsed(\n \n linted_file = LintedFile(\n parsed.fname,\n- violations,\n+ # Deduplicate violations\n+ LintedFile.deduplicate_in_source_space(violations),\n time_dict,\n tree,\n ignore_mask=ignore_buff,\n", "test_patch": "diff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -407,8 +407,9 @@ def test__linter__empty_file():\n (\n False,\n [\n- (\"L006\", 3, 16),\n- (\"L006\", 3, 16),\n+ # there are still two of each because L006 checks\n+ # for both *before* and *after* the operator.\n+ # The deduplication filter makes sure there aren't 4.\n (\"L006\", 3, 16),\n (\"L006\", 3, 16),\n (\"L006\", 3, 39),\n@@ -418,7 +419,11 @@ def test__linter__empty_file():\n ],\n )\n def test__linter__mask_templated_violations(ignore_templated_areas, check_tuples):\n- \"\"\"Test linter masks files properly around templated content.\"\"\"\n+ \"\"\"Test linter masks files properly around templated content.\n+\n+ NOTE: this also tests deduplication of fixes which have the same\n+ source position. i.e. `LintedFile.deduplicate_in_source_space()`.\n+ \"\"\"\n lntr = Linter(\n config=FluffConfig(\n overrides={\n", "problem_statement": "Deduplicate violations in the same position\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nWhen linting jinja files with loops we get multiple output violations for each time around the loop. e.g.\r\n\r\n```sql\r\nselect\r\n a,\r\n {% for val in [1, 2, 3, 4, 5, 6] %}\r\n d+ {{ val }},\r\n {% endfor %}\r\n b\r\n```\r\n\r\nwe get\r\n\r\n```\r\n== [test.sql] FAIL\r\nL: 4 | P: 10 | L006 | Missing whitespace before +\r\nL: 4 | P: 10 | L006 | Missing whitespace before +\r\nL: 4 | P: 10 | L006 | Missing whitespace before +\r\nL: 4 | P: 10 | L006 | Missing whitespace before +\r\nL: 4 | P: 10 | L006 | Missing whitespace before +\r\nL: 4 | P: 10 | L006 | Missing whitespace before +\r\nL: 7 | P: 1 | L001 | Unnecessary trailing whitespace.\r\n```\r\n\r\nThe duplicated `Missing whitespace` isn't helpful for the user. Regardless of whether we keep them in the background (perhaps we should), they shouldn't be shown to the user here because we're showing the same issue multiple times.\n\n### Use case\n\nCLI linting\n\n### Dialect\n\nall\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [X] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "", "created_at": "2022-11-08T09:57:07Z", "version": "1.3", "FAIL_TO_PASS": ["test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]"], "PASS_TO_PASS": ["test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__skip_large_bytes[0-False]", "test/core/linter_test.py::test__linter__skip_large_bytes[5-True]", "test/core/linter_test.py::test__linter__skip_large_bytes[2000-False]", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__sqlfluffignore_current_directory", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__get_runner_processes[512-1-1]", "test/core/linter_test.py::test__linter__get_runner_processes[512-0-512]", "test/core/linter_test.py::test__linter__get_runner_processes[512--12-500]", "test/core/linter_test.py::test__linter__get_runner_processes[512-5-5]", "test/core/linter_test.py::test__linter__get_runner_processes[1--1-1]", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_parse_noqa[Inline", "test/core/linter_test.py::test_parse_noqa_no_dups", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[2_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_glob_ignore]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_linter_noqa_template_errors", "test/core/linter_test.py::test_linter_noqa_prs", "test/core/linter_test.py::test_linter_noqa_tmp", "test/core/linter_test.py::test_linter_noqa_disable", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]", "test/core/linter_test.py::test_advanced_api_methods", "test/core/linter_test.py::test_normalise_newlines", "test/core/linter_test.py::test_require_match_parse_grammar"], "environment_setup_commit": "dc59c2a5672aacedaf91f0e6129b467eefad331b"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4834", "base_commit": "e884df2d00473a6ab166cb92a68d0b500a89d159", "patch": "diff --git a/src/sqlfluff/rules/layout/LT12.py b/src/sqlfluff/rules/layout/LT12.py\n--- a/src/sqlfluff/rules/layout/LT12.py\n+++ b/src/sqlfluff/rules/layout/LT12.py\n@@ -124,6 +124,10 @@ def _eval(self, context: RuleContext) -> Optional[LintResult]:\n # We only care about the final segment of the parse tree.\n parent_stack, segment = get_last_segment(FunctionalContext(context).segment)\n self.logger.debug(\"Found last segment as: %s\", segment)\n+ if not segment:\n+ # NOTE: Edge case. If the file is totally empty, we won't find a final\n+ # segment. In this case return without error.\n+ return None\n \n trailing_newlines = Segments(*get_trailing_newlines(context.segment))\n trailing_literal_newlines = trailing_newlines\ndiff --git a/src/sqlfluff/utils/reflow/sequence.py b/src/sqlfluff/utils/reflow/sequence.py\n--- a/src/sqlfluff/utils/reflow/sequence.py\n+++ b/src/sqlfluff/utils/reflow/sequence.py\n@@ -104,7 +104,10 @@ def get_raw(self) -> str:\n \n @staticmethod\n def _validate_reflow_sequence(elements: ReflowSequenceType):\n- assert elements, \"ReflowSequence has empty elements.\"\n+ # An empty set of elements _is_ allowed as an edge case.\n+ if not elements:\n+ # Return early if so\n+ return None\n # Check odds and evens\n OddType = elements[0].__class__\n EvenType = ReflowPoint if OddType is ReflowBlock else ReflowBlock\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -251,6 +251,14 @@ def test__cli__command_lint_stdin(command):\n invoke_assert_code(args=[lint, (\"--dialect=ansi\",) + command], cli_input=sql)\n \n \n+def test__cli__command_lint_empty_stdin():\n+ \"\"\"Check linting an empty file raises no exceptions.\n+\n+ https://github.com/sqlfluff/sqlfluff/issues/4807\n+ \"\"\"\n+ invoke_assert_code(args=[lint, (\"-d\", \"ansi\", \"-\")], cli_input=\"\")\n+\n+\n def test__cli__command_render_stdin():\n \"\"\"Check render on a simple script using stdin.\"\"\"\n with open(\"test/fixtures/cli/passing_a.sql\") as test_file:\n", "problem_statement": "Running `lint` on an empty file fails with critical Exception\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nThis is a bit of an odd one. When running `sqlfluff lint` on an empty file it fails with (Python) exception.\r\n\r\nWhile trying to lint empty file is probably not the main use-case for SQLFluff I still consider this somewhat relevant, when applying SQLFluff in a dynamic code base. \n\n### Expected Behaviour\n\nI'm not entirely sure what the correct result is. Feasible option are\r\n\r\n- Passing\r\n- Raise some kind of lint error (but not a critical exception)\r\n\r\nMy personal take is that lint should pass, which (I think) is similar behaviour to other linters.\n\n### Observed Behaviour\n\n`LT01` and `LT12` with an critical Exception\r\n\r\n```\r\nCRITICAL [LT01] Applying rule LT01 to 'stdin' threw an Exception: ReflowSequence has empty elements.\r\nCRITICAL [LT12] Applying rule LT12 to 'stdin' threw an Exception: tuple index out of range\r\n```\r\n\n\n### How to reproduce\n\n```sh\r\ncat /dev/null | sqlfluff lint --dialect ansi -\r\n```\n\n### Dialect\n\nansi\n\n### Version\n\nlatest main branch\r\n\r\n```\r\ngit rev-parse HEAD\r\nd19de0ecd16d298f9e3bfb91da122734c40c01e5\r\n```\n\n### Configuration\n\ndefault\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\nRunning `lint` on an empty file fails with critical Exception\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nThis is a bit of an odd one. When running `sqlfluff lint` on an empty file it fails with (Python) exception.\r\n\r\nWhile trying to lint empty file is probably not the main use-case for SQLFluff I still consider this somewhat relevant, when applying SQLFluff in a dynamic code base. \n\n### Expected Behaviour\n\nI'm not entirely sure what the correct result is. Feasible option are\r\n\r\n- Passing\r\n- Raise some kind of lint error (but not a critical exception)\r\n\r\nMy personal take is that lint should pass, which (I think) is similar behaviour to other linters.\n\n### Observed Behaviour\n\n`LT01` and `LT12` with an critical Exception\r\n\r\n```\r\nCRITICAL [LT01] Applying rule LT01 to 'stdin' threw an Exception: ReflowSequence has empty elements.\r\nCRITICAL [LT12] Applying rule LT12 to 'stdin' threw an Exception: tuple index out of range\r\n```\r\n\n\n### How to reproduce\n\n```sh\r\ncat /dev/null | sqlfluff lint --dialect ansi -\r\n```\n\n### Dialect\n\nansi\n\n### Version\n\nlatest main branch\r\n\r\n```\r\ngit rev-parse HEAD\r\nd19de0ecd16d298f9e3bfb91da122734c40c01e5\r\n```\n\n### Configuration\n\ndefault\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "I'll pick up this one - I've been in the \"empty\" file code recently and might have influenced this outcome.\nI'll pick up this one - I've been in the \"empty\" file code recently and might have influenced this outcome.", "created_at": "2023-05-02T06:58:53Z", "version": "2.0", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_lint_empty_stdin"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse[command26]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-0]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command5-2]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command6-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command7-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command8-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command9-2]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_lint_warning", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql0]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[LT01-test/fixtures/linter/indentation_errors.sql1]", "test/cli/commands_test.py::test__cli__command__fix[LT02-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_format_stdin[select", "test/cli/commands_test.py::test__cli__command_format_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[LT01-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-none]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_fix_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_force", "test/cli/commands_test.py::test__cli__fix_multiple_errors_quiet_no_force", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass"], "environment_setup_commit": "3629c3e702939c07264cc5ea903566ddc9ea2bb0"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-5170", "base_commit": "d5a0ba0838b9058d815e5376241c96b0eb48e889", "patch": "diff --git a/src/sqlfluff/core/parser/grammar/base.py b/src/sqlfluff/core/parser/grammar/base.py\n--- a/src/sqlfluff/core/parser/grammar/base.py\n+++ b/src/sqlfluff/core/parser/grammar/base.py\n@@ -1,7 +1,6 @@\n \"\"\"Base grammar, Ref, Anything and Nothing.\"\"\"\n \n import copy\n-from dataclasses import dataclass\n from typing import (\n TYPE_CHECKING,\n Any,\n@@ -14,21 +13,16 @@\n Tuple,\n TypeVar,\n Union,\n- cast,\n )\n from uuid import UUID, uuid4\n \n-from sqlfluff.core.errors import SQLParseError\n from sqlfluff.core.parser.context import ParseContext\n from sqlfluff.core.parser.helpers import trim_non_code_segments\n-from sqlfluff.core.parser.match_logging import (\n- LateBoundJoinSegmentsCurtailed,\n- parse_match_logging,\n-)\n+from sqlfluff.core.parser.match_logging import parse_match_logging\n from sqlfluff.core.parser.match_result import MatchResult\n from sqlfluff.core.parser.match_wrapper import match_wrapper\n from sqlfluff.core.parser.matchable import Matchable\n-from sqlfluff.core.parser.segments import BaseSegment, BracketedSegment, allow_ephemeral\n+from sqlfluff.core.parser.segments import BaseSegment, allow_ephemeral\n from sqlfluff.core.parser.types import MatchableType, SimpleHintType\n from sqlfluff.core.string_helpers import curtail_string\n \n@@ -36,49 +30,6 @@\n from sqlfluff.core.dialects.base import Dialect\n \n \n-def first_trimmed_raw(seg: BaseSegment) -> str:\n- \"\"\"Trim whitespace off a whole element raw.\n-\n- Used as a helper function in BaseGrammar._look_ahead_match.\n-\n- For existing compound segments, we should assume that within\n- that segment, things are internally consistent, that means\n- rather than enumerating all the individual segments of a longer\n- one we just dump out the whole segment, but splitting off the\n- first element separated by whitespace. This is a) faster and\n- also b) prevents some really horrible bugs with bracket matching.\n- See https://github.com/sqlfluff/sqlfluff/issues/433\n-\n- This fetches the _whole_ raw of a potentially compound segment\n- to match against, trimming off any whitespace. This is the\n- most efficient way to get at the first element of a potentially\n- longer segment.\n- \"\"\"\n- s = seg.raw_upper.split(maxsplit=1)\n- return s[0] if s else \"\"\n-\n-\n-@dataclass\n-class BracketInfo:\n- \"\"\"BracketInfo tuple for keeping track of brackets during matching.\n-\n- This is used in BaseGrammar._bracket_sensitive_look_ahead_match but\n- defined here for type checking.\n- \"\"\"\n-\n- bracket: BaseSegment\n- segments: Tuple[BaseSegment, ...]\n-\n- def to_segment(self, end_bracket: Tuple[BaseSegment, ...]) -> BracketedSegment:\n- \"\"\"Turn the contained segments into a bracketed segment.\"\"\"\n- assert len(end_bracket) == 1\n- return BracketedSegment(\n- segments=self.segments,\n- start_bracket=(self.bracket,),\n- end_bracket=cast(Tuple[BaseSegment], end_bracket),\n- )\n-\n-\n def cached_method_for_parse_context(\n func: Callable[[Any, ParseContext, Optional[Tuple[str]]], SimpleHintType]\n ) -> Callable[..., SimpleHintType]:\n@@ -520,355 +471,6 @@ def _longest_trimmed_match(\n # If no match at all, return nothing\n return MatchResult.from_unmatched(segments), None\n \n- @classmethod\n- def _look_ahead_match(\n- cls,\n- segments: Tuple[BaseSegment, ...],\n- matchers: List[MatchableType],\n- parse_context: ParseContext,\n- ) -> Tuple[Tuple[BaseSegment, ...], MatchResult, Optional[MatchableType]]:\n- \"\"\"Look ahead for matches beyond the first element of the segments list.\n-\n- This function also contains the performance improved hash-matching approach to\n- searching for matches, which should significantly improve performance.\n-\n- Prioritise the first match, and if multiple match at the same point the longest.\n- If two matches of the same length match at the same time, then it's the first in\n- the iterable of matchers.\n-\n- Returns:\n- `tuple` of (unmatched_segments, match_object, matcher).\n-\n- \"\"\"\n- parse_match_logging(\n- cls.__name__,\n- \"_look_ahead_match\",\n- \"IN\",\n- parse_context=parse_context,\n- v_level=4,\n- ls=len(segments),\n- seg=LateBoundJoinSegmentsCurtailed(segments),\n- )\n-\n- # Have we been passed an empty tuple?\n- if not segments: # pragma: no cover TODO?\n- return ((), MatchResult.from_empty(), None)\n-\n- # Here we enable a performance optimisation. Most of the time in this cycle\n- # happens in loops looking for simple matchers which we should\n- # be able to find a shortcut for.\n-\n- parse_match_logging(\n- cls.__name__,\n- \"_look_ahead_match\",\n- \"SI\",\n- parse_context=parse_context,\n- v_level=4,\n- )\n-\n- best_simple_match = None\n- simple_match = None\n- for idx, seg in enumerate(segments):\n- trimmed_seg = first_trimmed_raw(seg)\n- for matcher in matchers:\n- simple_match = None\n- simple = matcher.simple(parse_context=parse_context)\n- if not simple: # pragma: no cover\n- # NOTE: For all bundled dialects, this clause is true, but until\n- # the RegexMatcher is completely deprecated (and therefore that\n- # `.simple()` must provide a result), it is still _possible_\n- # to end up here.\n- raise NotImplementedError(\n- \"All matchers passed to `._look_ahead_match()` are \"\n- \"assumed to have a functioning `.simple()` option. \"\n- \"In a future release it will be compulsory for _all_ \"\n- \"matchables to implement `.simple()`. Please report \"\n- \"this as a bug on GitHub along with your current query \"\n- f\"and dialect.\\nProblematic matcher: {matcher}\"\n- )\n- simple_raws, simple_types = simple\n-\n- assert simple_raws or simple_types\n- if simple_raws:\n- if trimmed_seg in simple_raws:\n- simple_match = matcher\n-\n- if simple_types and not simple_match:\n- intersection = simple_types.intersection(seg.class_types)\n- if intersection:\n- simple_match = matcher\n-\n- # If we couldn't achieve a simple match, move on to the next option.\n- if not simple_match:\n- continue\n-\n- # If there is, check the full version matches. If it doesn't\n- # then discount it and move on.\n- match = simple_match.match(segments[idx:], parse_context)\n- if not match:\n- continue\n-\n- best_simple_match = (\n- segments[:idx],\n- match,\n- simple_match,\n- )\n- # Stop looking through matchers\n- break\n-\n- # If we have a valid match, stop looking through segments\n- if best_simple_match:\n- break\n-\n- # There are no other matchers, we can just shortcut now. Either with\n- # no match, or the best one we found (if we found one).\n- parse_match_logging(\n- cls.__name__,\n- \"_look_ahead_match\",\n- \"SC\",\n- parse_context=parse_context,\n- v_level=4,\n- bsm=None\n- if not best_simple_match\n- else (\n- len(best_simple_match[0]),\n- len(best_simple_match[1]),\n- best_simple_match[2],\n- ),\n- )\n-\n- if best_simple_match:\n- return best_simple_match\n- else:\n- return ((), MatchResult.from_unmatched(segments), None)\n-\n- @classmethod\n- def _bracket_sensitive_look_ahead_match(\n- cls,\n- segments: Tuple[BaseSegment, ...],\n- matchers: List[MatchableType],\n- parse_context: ParseContext,\n- start_bracket: Optional[MatchableType] = None,\n- end_bracket: Optional[MatchableType] = None,\n- bracket_pairs_set: str = \"bracket_pairs\",\n- ) -> Tuple[Tuple[BaseSegment, ...], MatchResult, Optional[MatchableType]]:\n- \"\"\"Same as `_look_ahead_match` but with bracket counting.\n-\n- NB: Given we depend on `_look_ahead_match` we can also utilise\n- the same performance optimisations which are implemented there.\n-\n- bracket_pairs_set: Allows specific segments to override the available\n- bracket pairs. See the definition of \"angle_bracket_pairs\" in the\n- BigQuery dialect for additional context on why this exists.\n-\n- Returns:\n- `tuple` of (unmatched_segments, match_object, matcher).\n-\n- \"\"\"\n- # Have we been passed an empty tuple?\n- if not segments:\n- return ((), MatchResult.from_unmatched(segments), None)\n-\n- # Get hold of the bracket matchers from the dialect, and append them\n- # to the list of matchers. We get them from the relevant set on the\n- # dialect. We use zip twice to \"unzip\" them. We ignore the first\n- # argument because that's just the name.\n- _, start_bracket_refs, end_bracket_refs, persists = zip(\n- *parse_context.dialect.bracket_sets(bracket_pairs_set)\n- )\n- # These are matchables, probably StringParsers.\n- start_brackets = [\n- parse_context.dialect.ref(seg_ref) for seg_ref in start_bracket_refs\n- ]\n- end_brackets = [\n- parse_context.dialect.ref(seg_ref) for seg_ref in end_bracket_refs\n- ]\n- # Add any bracket-like things passed as arguments\n- if start_bracket:\n- start_brackets += [start_bracket]\n- if end_bracket:\n- end_brackets += [end_bracket]\n- bracket_matchers = start_brackets + end_brackets\n-\n- # Make some buffers\n- seg_buff: Tuple[BaseSegment, ...] = segments\n- pre_seg_buff: Tuple[BaseSegment, ...] = ()\n- bracket_stack: List[BracketInfo] = []\n-\n- # Iterate\n- while True:\n- # Do we have anything left to match on?\n- if seg_buff:\n- # Yes we have buffer left to work with.\n- # Are we already in a bracket stack?\n- if bracket_stack:\n- # Yes, we're just looking for the closing bracket, or\n- # another opening bracket.\n- pre, match, matcher = cls._look_ahead_match(\n- seg_buff,\n- bracket_matchers,\n- parse_context=parse_context,\n- )\n-\n- if match:\n- # NB: We can only consider this as a nested bracket if the start\n- # and end tokens are not the same. If a matcher is both a start\n- # and end token we cannot deepen the bracket stack. In general,\n- # quoted strings are a typical example where the start and end\n- # tokens are the same. Currently, though, quoted strings are\n- # handled elsewhere in the parser, and there are no cases where\n- # *this* code has to handle identical start and end brackets.\n- # For now, consider this a small, speculative investment in a\n- # possible future requirement.\n- if matcher in start_brackets and matcher not in end_brackets:\n- # Add any segments leading up to this to the previous\n- # bracket.\n- bracket_stack[-1].segments += pre\n- # Add a bracket to the stack and add the matches from the\n- # segment.\n- bracket_stack.append(\n- BracketInfo(\n- bracket=match.matched_segments[0],\n- segments=match.matched_segments,\n- )\n- )\n- seg_buff = match.unmatched_segments\n- continue\n- elif matcher in end_brackets:\n- # Found an end bracket. Does its type match that of\n- # the innermost start bracket? E.g. \")\" matches \"(\",\n- # \"]\" matches \"[\".\n- # For the start bracket we don't have the matcher\n- # but we can work out the type, so we use that for\n- # the lookup.\n- start_index = [\n- bracket.type for bracket in start_brackets\n- ].index(bracket_stack[-1].bracket.get_type())\n- # For the end index, we can just look for the matcher\n- end_index = end_brackets.index(matcher)\n- bracket_types_match = start_index == end_index\n- if bracket_types_match:\n- # Yes, the types match. So we've found a\n- # matching end bracket. Pop the stack, construct\n- # a bracketed segment and carry\n- # on.\n-\n- # Complete the bracketed info\n- bracket_stack[-1].segments += (\n- pre + match.matched_segments\n- )\n- # Construct a bracketed segment (as a tuple) if allowed.\n- persist_bracket = persists[end_brackets.index(matcher)]\n- if persist_bracket:\n- new_segments: Tuple[BaseSegment, ...] = (\n- bracket_stack[-1].to_segment(\n- end_bracket=match.matched_segments\n- ),\n- )\n- else:\n- new_segments = bracket_stack[-1].segments\n- # Remove the bracket set from the stack\n- bracket_stack.pop()\n- # If we're still in a bracket, add the new segments to\n- # that bracket, otherwise add them to the buffer\n- if bracket_stack:\n- bracket_stack[-1].segments += new_segments\n- else:\n- pre_seg_buff += new_segments\n- seg_buff = match.unmatched_segments\n- continue\n- else:\n- # The types don't match. Error.\n- raise SQLParseError(\n- f\"Found unexpected end bracket!, \"\n- f\"was expecting \"\n- f\"{end_brackets[start_index]}, \"\n- f\"but got {matcher}\",\n- segment=match.matched_segments[0],\n- )\n-\n- else: # pragma: no cover\n- raise RuntimeError(\"I don't know how we get here?!\")\n- else: # pragma: no cover\n- # No match, we're in a bracket stack. Error.\n- raise SQLParseError(\n- \"Couldn't find closing bracket for opening bracket.\",\n- segment=bracket_stack[-1].bracket,\n- )\n- else:\n- # No, we're open to more opening brackets or the thing(s)\n- # that we're otherwise looking for.\n- pre, match, matcher = cls._look_ahead_match(\n- seg_buff,\n- matchers + bracket_matchers,\n- parse_context=parse_context,\n- )\n-\n- if match:\n- if matcher in matchers:\n- # It's one of the things we were looking for!\n- # Return.\n- return (pre_seg_buff + pre, match, matcher)\n- elif matcher in start_brackets:\n- # We've found the start of a bracket segment.\n- # NB: It might not *actually* be the bracket itself,\n- # but could be some non-code element preceding it.\n- # That's actually ok.\n-\n- # Add the bracket to the stack.\n- bracket_stack.append(\n- BracketInfo(\n- bracket=match.matched_segments[0],\n- segments=match.matched_segments,\n- )\n- )\n- # The matched element has already been added to the bracket.\n- # Add anything before it to the pre segment buffer.\n- # Reset the working buffer.\n- pre_seg_buff += pre\n- seg_buff = match.unmatched_segments\n- continue\n- elif matcher in end_brackets:\n- # We've found an unexpected end bracket! This is likely\n- # because we're matching a section which should have ended.\n- # If we had a match, it would have matched by now, so this\n- # means no match.\n- parse_match_logging(\n- cls.__name__,\n- \"_bracket_sensitive_look_ahead_match\",\n- \"UEXB\",\n- parse_context=parse_context,\n- v_level=3,\n- got=matcher,\n- )\n- # From here we'll drop out to the happy unmatched exit.\n- else: # pragma: no cover\n- # This shouldn't happen!?\n- raise NotImplementedError(\n- \"This shouldn't happen. Panic in \"\n- \"_bracket_sensitive_look_ahead_match.\"\n- )\n- # Not in a bracket stack, but no match.\n- # From here we'll drop out to the happy unmatched exit.\n- else:\n- # No we're at the end:\n- # Now check have we closed all our brackets?\n- if bracket_stack: # pragma: no cover\n- # No we haven't.\n- raise SQLParseError(\n- \"Couldn't find closing bracket for opened brackets: \"\n- f\"`{bracket_stack}`.\",\n- segment=bracket_stack[-1].bracket,\n- )\n-\n- # This is the happy unmatched path. This occurs when:\n- # - We reached the end with no open brackets.\n- # - No match while outside a bracket stack.\n- # - We found an unexpected end bracket before matching something\n- # interesting. We return with the mutated segments so we can reuse any\n- # bracket matching.\n- return ((), MatchResult.from_unmatched(pre_seg_buff + seg_buff), None)\n-\n def __str__(self) -> str: # pragma: no cover TODO?\n return repr(self)\n \n@@ -1052,7 +654,7 @@ def _get_elem(self, dialect: \"Dialect\") -> MatchableType:\n \n def __repr__(self) -> str:\n return \"<Ref: {}{}>\".format(\n- str(self._ref), \" [opt]\" if self.is_optional() else \"\"\n+ repr(self._ref), \" [opt]\" if self.is_optional() else \"\"\n )\n \n @match_wrapper(v_level=4) # Log less for Ref\ndiff --git a/src/sqlfluff/core/parser/grammar/greedy.py b/src/sqlfluff/core/parser/grammar/greedy.py\n--- a/src/sqlfluff/core/parser/grammar/greedy.py\n+++ b/src/sqlfluff/core/parser/grammar/greedy.py\n@@ -8,7 +8,7 @@\n BaseSegment,\n cached_method_for_parse_context,\n )\n-from sqlfluff.core.parser.helpers import trim_non_code_segments\n+from sqlfluff.core.parser.match_algorithms import greedy_match\n from sqlfluff.core.parser.match_result import MatchResult\n from sqlfluff.core.parser.match_wrapper import match_wrapper\n from sqlfluff.core.parser.segments import allow_ephemeral\n@@ -50,112 +50,13 @@ def match(\n self, segments: Tuple[BaseSegment, ...], parse_context: ParseContext\n ) -> MatchResult:\n \"\"\"Matching for GreedyUntil works just how you'd expect.\"\"\"\n- return self.greedy_match(\n+ return greedy_match(\n segments,\n parse_context,\n matchers=self._elements,\n include_terminator=False,\n )\n \n- @classmethod\n- def greedy_match(\n- cls,\n- segments: Tuple[BaseSegment, ...],\n- parse_context: ParseContext,\n- matchers: Sequence[MatchableType],\n- include_terminator: bool = False,\n- ) -> MatchResult:\n- \"\"\"Matching for GreedyUntil works just how you'd expect.\"\"\"\n- seg_buff = segments\n- seg_bank: Tuple[BaseSegment, ...] = () # Empty tuple\n-\n- while True:\n- with parse_context.deeper_match(name=\"GreedyUntil\") as ctx:\n- pre, mat, matcher = cls._bracket_sensitive_look_ahead_match(\n- seg_buff, list(matchers), parse_context=ctx\n- )\n-\n- if not mat:\n- # No terminator match? Return everything\n- return MatchResult.from_matched(segments)\n-\n- # NOTE: For some terminators we only count them if they're preceded\n- # by whitespace, and others we don't. In principle, we aim that for\n- # _keywords_ we require whitespace, and for symbols we don't.\n- # We do this by looking at the `simple` method of the returned\n- # matcher, and if it's entirely alphabetical (as defined by\n- # str.isalpha()) then we infer that it's a keyword, and therefore\n- # _does_ require whitespace before it.\n- assert matcher, f\"Match without matcher: {mat}\"\n- _simple = matcher.simple(parse_context)\n- assert _simple, f\"Terminators require a simple method: {matcher}\"\n- _strings, _types = _simple\n- # NOTE: Typed matchers aren't common here, but we assume that they\n- # _don't_ require preceding whitespace.\n- # Do we need to enforce whitespace preceding?\n- if all(_s.isalpha() for _s in _strings) and not _types:\n- # Does the match include some whitespace already?\n- # Work forward\n- idx = 0\n- while True:\n- elem = mat.matched_segments[idx]\n- if elem.is_meta: # pragma: no cover TODO?\n- idx += 1\n- continue\n- elif elem.is_type(\n- \"whitespace\", \"newline\"\n- ): # pragma: no cover TODO?\n- allowable_match = True\n- break\n- else:\n- # No whitespace before. Not allowed.\n- allowable_match = False\n- break\n-\n- # If we're not ok yet, work backward to the preceding sections.\n- if not allowable_match:\n- idx = -1\n- while True:\n- if len(pre) < abs(idx): # pragma: no cover TODO?\n- # If we're at the start, it's ok\n- allowable_match = True\n- break\n- if pre[idx].is_meta: # pragma: no cover TODO?\n- idx -= 1\n- continue\n- elif pre[idx].is_type(\"whitespace\", \"newline\"):\n- allowable_match = True\n- break\n- else:\n- # No whitespace before. Not allowed.\n- allowable_match = False\n- break\n-\n- # If this match isn't preceded by whitespace and that is\n- # a requirement, then we can't use it. Carry on...\n- if not allowable_match:\n- # Update our buffers and continue onward\n- seg_bank = seg_bank + pre + mat.matched_segments\n- seg_buff = mat.unmatched_segments\n- # Loop around, don't return yet\n- continue\n-\n- # Return everything up to the match unless it's a gap matcher.\n- if include_terminator:\n- return MatchResult(\n- seg_bank + pre + mat.matched_segments,\n- mat.unmatched_segments,\n- )\n-\n- # We can't claim any non-code segments, so we trim them off the end.\n- leading_nc, pre_seg_mid, trailing_nc = trim_non_code_segments(\n- seg_bank + pre\n- )\n- return MatchResult(\n- leading_nc + pre_seg_mid,\n- trailing_nc + mat.all_segments(),\n- )\n-\n \n T = TypeVar(\"T\", bound=\"StartsWith\")\n \n@@ -232,7 +133,7 @@ def match(\n # with, then we can still used the unmatched parts on the end.\n # We still need to deal with any non-code segments at the start.\n assert self.terminators\n- greedy_match = self.greedy_match(\n+ greedy_matched = greedy_match(\n match.unmatched_segments,\n parse_context,\n # We match up to the terminators for this segment, but _also_\n@@ -243,12 +144,12 @@ def match(\n \n # NB: If all we matched in the greedy match was non-code then we can't\n # claim it.\n- if not any(seg.is_code for seg in greedy_match.matched_segments):\n+ if not any(seg.is_code for seg in greedy_matched.matched_segments):\n # So just return the original match.\n return match\n \n # Otherwise Combine the results.\n return MatchResult(\n- match.matched_segments + greedy_match.matched_segments,\n- greedy_match.unmatched_segments,\n+ match.matched_segments + greedy_matched.matched_segments,\n+ greedy_matched.unmatched_segments,\n )\ndiff --git a/src/sqlfluff/core/parser/grammar/sequence.py b/src/sqlfluff/core/parser/grammar/sequence.py\n--- a/src/sqlfluff/core/parser/grammar/sequence.py\n+++ b/src/sqlfluff/core/parser/grammar/sequence.py\n@@ -15,6 +15,7 @@\n )\n from sqlfluff.core.parser.grammar.conditional import Conditional\n from sqlfluff.core.parser.helpers import check_still_complete, trim_non_code_segments\n+from sqlfluff.core.parser.match_algorithms import bracket_sensitive_look_ahead_match\n from sqlfluff.core.parser.match_result import MatchResult\n from sqlfluff.core.parser.match_wrapper import match_wrapper\n from sqlfluff.core.parser.matchable import Matchable\n@@ -386,7 +387,7 @@ def match(\n with parse_context.deeper_match(\n name=\"Bracketed-End\", clear_terminators=True\n ) as ctx:\n- content_segs, end_match, _ = self._bracket_sensitive_look_ahead_match(\n+ content_segs, end_match, _ = bracket_sensitive_look_ahead_match(\n segments=seg_buff,\n matchers=[end_bracket],\n parse_context=ctx,\ndiff --git a/src/sqlfluff/core/parser/match_algorithms.py b/src/sqlfluff/core/parser/match_algorithms.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/sqlfluff/core/parser/match_algorithms.py\n@@ -0,0 +1,452 @@\n+\"\"\"Matching algorithms.\n+\n+These are mostly extracted from the body of either BaseSegment\n+or BaseGrammar to un-bloat those classes.\n+\"\"\"\n+\n+from dataclasses import dataclass\n+from typing import List, Optional, Sequence, Tuple, cast\n+\n+from sqlfluff.core.errors import SQLParseError\n+from sqlfluff.core.parser.context import ParseContext\n+from sqlfluff.core.parser.helpers import trim_non_code_segments\n+from sqlfluff.core.parser.match_result import MatchResult\n+from sqlfluff.core.parser.segments import BaseSegment, BracketedSegment\n+from sqlfluff.core.parser.types import MatchableType\n+\n+\n+def first_trimmed_raw(seg: BaseSegment) -> str:\n+ \"\"\"Trim whitespace off a whole element raw.\n+\n+ Used as a helper function in BaseGrammar._look_ahead_match.\n+\n+ For existing compound segments, we should assume that within\n+ that segment, things are internally consistent, that means\n+ rather than enumerating all the individual segments of a longer\n+ one we just dump out the whole segment, but splitting off the\n+ first element separated by whitespace. This is a) faster and\n+ also b) prevents some really horrible bugs with bracket matching.\n+ See https://github.com/sqlfluff/sqlfluff/issues/433\n+\n+ This fetches the _whole_ raw of a potentially compound segment\n+ to match against, trimming off any whitespace. This is the\n+ most efficient way to get at the first element of a potentially\n+ longer segment.\n+ \"\"\"\n+ s = seg.raw_upper.split(maxsplit=1)\n+ return s[0] if s else \"\"\n+\n+\n+@dataclass\n+class BracketInfo:\n+ \"\"\"BracketInfo tuple for keeping track of brackets during matching.\n+\n+ This is used in BaseGrammar._bracket_sensitive_look_ahead_match but\n+ defined here for type checking.\n+ \"\"\"\n+\n+ bracket: BaseSegment\n+ segments: Tuple[BaseSegment, ...]\n+\n+ def to_segment(self, end_bracket: Tuple[BaseSegment, ...]) -> BracketedSegment:\n+ \"\"\"Turn the contained segments into a bracketed segment.\"\"\"\n+ assert len(end_bracket) == 1\n+ return BracketedSegment(\n+ segments=self.segments,\n+ start_bracket=(self.bracket,),\n+ end_bracket=cast(Tuple[BaseSegment], end_bracket),\n+ )\n+\n+\n+def look_ahead_match(\n+ segments: Tuple[BaseSegment, ...],\n+ matchers: List[MatchableType],\n+ parse_context: ParseContext,\n+) -> Tuple[Tuple[BaseSegment, ...], MatchResult, Optional[MatchableType]]:\n+ \"\"\"Look ahead for matches beyond the first element of the segments list.\n+\n+ This function also contains the performance improved hash-matching approach to\n+ searching for matches, which should significantly improve performance.\n+\n+ Prioritise the first match, and if multiple match at the same point the longest.\n+ If two matches of the same length match at the same time, then it's the first in\n+ the iterable of matchers.\n+\n+ Returns:\n+ `tuple` of (unmatched_segments, match_object, matcher).\n+\n+ \"\"\"\n+ # Have we been passed an empty tuple?\n+ if not segments: # pragma: no cover TODO?\n+ return ((), MatchResult.from_empty(), None)\n+\n+ # Here we enable a performance optimisation. Most of the time in this cycle\n+ # happens in loops looking for simple matchers which we should\n+ # be able to find a shortcut for.\n+ best_simple_match = None\n+ simple_match = None\n+ for idx, seg in enumerate(segments):\n+ trimmed_seg = first_trimmed_raw(seg)\n+ for matcher in matchers:\n+ simple_match = None\n+ simple = matcher.simple(parse_context=parse_context)\n+ if not simple: # pragma: no cover\n+ # NOTE: For all bundled dialects, this clause is true, but until\n+ # the RegexMatcher is completely deprecated (and therefore that\n+ # `.simple()` must provide a result), it is still _possible_\n+ # to end up here.\n+ raise NotImplementedError(\n+ \"All matchers passed to `.look_ahead_match()` are \"\n+ \"assumed to have a functioning `.simple()` option. \"\n+ \"In a future release it will be compulsory for _all_ \"\n+ \"matchables to implement `.simple()`. Please report \"\n+ \"this as a bug on GitHub along with your current query \"\n+ f\"and dialect.\\nProblematic matcher: {matcher}\"\n+ )\n+ simple_raws, simple_types = simple\n+\n+ assert simple_raws or simple_types\n+ if simple_raws:\n+ if trimmed_seg in simple_raws:\n+ simple_match = matcher\n+\n+ if simple_types and not simple_match:\n+ intersection = simple_types.intersection(seg.class_types)\n+ if intersection:\n+ simple_match = matcher\n+\n+ # If we couldn't achieve a simple match, move on to the next option.\n+ if not simple_match:\n+ continue\n+\n+ # If there is, check the full version matches. If it doesn't\n+ # then discount it and move on.\n+ match = simple_match.match(segments[idx:], parse_context)\n+ if not match:\n+ continue\n+\n+ best_simple_match = (\n+ segments[:idx],\n+ match,\n+ simple_match,\n+ )\n+ # Stop looking through matchers\n+ break\n+\n+ # If we have a valid match, stop looking through segments\n+ if best_simple_match:\n+ break\n+\n+ if best_simple_match:\n+ return best_simple_match\n+ else:\n+ return ((), MatchResult.from_unmatched(segments), None)\n+\n+\n+def bracket_sensitive_look_ahead_match(\n+ segments: Tuple[BaseSegment, ...],\n+ matchers: List[MatchableType],\n+ parse_context: ParseContext,\n+ start_bracket: Optional[MatchableType] = None,\n+ end_bracket: Optional[MatchableType] = None,\n+ bracket_pairs_set: str = \"bracket_pairs\",\n+) -> Tuple[Tuple[BaseSegment, ...], MatchResult, Optional[MatchableType]]:\n+ \"\"\"Same as `look_ahead_match` but with bracket counting.\n+\n+ NB: Given we depend on `look_ahead_match` we can also utilise\n+ the same performance optimisations which are implemented there.\n+\n+ bracket_pairs_set: Allows specific segments to override the available\n+ bracket pairs. See the definition of \"angle_bracket_pairs\" in the\n+ BigQuery dialect for additional context on why this exists.\n+\n+ Returns:\n+ `tuple` of (unmatched_segments, match_object, matcher).\n+\n+ \"\"\"\n+ # Have we been passed an empty tuple?\n+ if not segments:\n+ return ((), MatchResult.from_unmatched(segments), None)\n+\n+ # Get hold of the bracket matchers from the dialect, and append them\n+ # to the list of matchers. We get them from the relevant set on the\n+ # dialect. We use zip twice to \"unzip\" them. We ignore the first\n+ # argument because that's just the name.\n+ _, start_bracket_refs, end_bracket_refs, persists = zip(\n+ *parse_context.dialect.bracket_sets(bracket_pairs_set)\n+ )\n+ # These are matchables, probably StringParsers.\n+ start_brackets = [\n+ parse_context.dialect.ref(seg_ref) for seg_ref in start_bracket_refs\n+ ]\n+ end_brackets = [parse_context.dialect.ref(seg_ref) for seg_ref in end_bracket_refs]\n+ # Add any bracket-like things passed as arguments\n+ if start_bracket:\n+ start_brackets += [start_bracket]\n+ if end_bracket:\n+ end_brackets += [end_bracket]\n+ bracket_matchers = start_brackets + end_brackets\n+\n+ # Make some buffers\n+ seg_buff: Tuple[BaseSegment, ...] = segments\n+ pre_seg_buff: Tuple[BaseSegment, ...] = ()\n+ bracket_stack: List[BracketInfo] = []\n+\n+ # Iterate\n+ while True:\n+ # Do we have anything left to match on?\n+ if seg_buff:\n+ # Yes we have buffer left to work with.\n+ # Are we already in a bracket stack?\n+ if bracket_stack:\n+ # Yes, we're just looking for the closing bracket, or\n+ # another opening bracket.\n+ pre, match, matcher = look_ahead_match(\n+ seg_buff,\n+ bracket_matchers,\n+ parse_context=parse_context,\n+ )\n+\n+ if match:\n+ # NB: We can only consider this as a nested bracket if the start\n+ # and end tokens are not the same. If a matcher is both a start\n+ # and end token we cannot deepen the bracket stack. In general,\n+ # quoted strings are a typical example where the start and end\n+ # tokens are the same. Currently, though, quoted strings are\n+ # handled elsewhere in the parser, and there are no cases where\n+ # *this* code has to handle identical start and end brackets.\n+ # For now, consider this a small, speculative investment in a\n+ # possible future requirement.\n+ if matcher in start_brackets and matcher not in end_brackets:\n+ # Add any segments leading up to this to the previous\n+ # bracket.\n+ bracket_stack[-1].segments += pre\n+ # Add a bracket to the stack and add the matches from the\n+ # segment.\n+ bracket_stack.append(\n+ BracketInfo(\n+ bracket=match.matched_segments[0],\n+ segments=match.matched_segments,\n+ )\n+ )\n+ seg_buff = match.unmatched_segments\n+ continue\n+ elif matcher in end_brackets:\n+ # Found an end bracket. Does its type match that of\n+ # the innermost start bracket? E.g. \")\" matches \"(\",\n+ # \"]\" matches \"[\".\n+ # For the start bracket we don't have the matcher\n+ # but we can work out the type, so we use that for\n+ # the lookup.\n+ start_index = [\n+ bracket.type for bracket in start_brackets\n+ ].index(bracket_stack[-1].bracket.get_type())\n+ # For the end index, we can just look for the matcher\n+ end_index = end_brackets.index(matcher)\n+ bracket_types_match = start_index == end_index\n+ if bracket_types_match:\n+ # Yes, the types match. So we've found a\n+ # matching end bracket. Pop the stack, construct\n+ # a bracketed segment and carry\n+ # on.\n+\n+ # Complete the bracketed info\n+ bracket_stack[-1].segments += pre + match.matched_segments\n+ # Construct a bracketed segment (as a tuple) if allowed.\n+ persist_bracket = persists[end_brackets.index(matcher)]\n+ if persist_bracket:\n+ new_segments: Tuple[BaseSegment, ...] = (\n+ bracket_stack[-1].to_segment(\n+ end_bracket=match.matched_segments\n+ ),\n+ )\n+ else:\n+ new_segments = bracket_stack[-1].segments\n+ # Remove the bracket set from the stack\n+ bracket_stack.pop()\n+ # If we're still in a bracket, add the new segments to\n+ # that bracket, otherwise add them to the buffer\n+ if bracket_stack:\n+ bracket_stack[-1].segments += new_segments\n+ else:\n+ pre_seg_buff += new_segments\n+ seg_buff = match.unmatched_segments\n+ continue\n+ else:\n+ # The types don't match. Error.\n+ raise SQLParseError(\n+ f\"Found unexpected end bracket!, \"\n+ f\"was expecting \"\n+ f\"{end_brackets[start_index]}, \"\n+ f\"but got {matcher}\",\n+ segment=match.matched_segments[0],\n+ )\n+\n+ else: # pragma: no cover\n+ raise RuntimeError(\"I don't know how we get here?!\")\n+ else: # pragma: no cover\n+ # No match, we're in a bracket stack. Error.\n+ raise SQLParseError(\n+ \"Couldn't find closing bracket for opening bracket.\",\n+ segment=bracket_stack[-1].bracket,\n+ )\n+ else:\n+ # No, we're open to more opening brackets or the thing(s)\n+ # that we're otherwise looking for.\n+ pre, match, matcher = look_ahead_match(\n+ seg_buff,\n+ matchers + bracket_matchers,\n+ parse_context=parse_context,\n+ )\n+\n+ if match:\n+ if matcher in matchers:\n+ # It's one of the things we were looking for!\n+ # Return.\n+ return (pre_seg_buff + pre, match, matcher)\n+ elif matcher in start_brackets:\n+ # We've found the start of a bracket segment.\n+ # NB: It might not *actually* be the bracket itself,\n+ # but could be some non-code element preceding it.\n+ # That's actually ok.\n+\n+ # Add the bracket to the stack.\n+ bracket_stack.append(\n+ BracketInfo(\n+ bracket=match.matched_segments[0],\n+ segments=match.matched_segments,\n+ )\n+ )\n+ # The matched element has already been added to the bracket.\n+ # Add anything before it to the pre segment buffer.\n+ # Reset the working buffer.\n+ pre_seg_buff += pre\n+ seg_buff = match.unmatched_segments\n+ continue\n+ elif matcher in end_brackets:\n+ # We've found an unexpected end bracket! This is likely\n+ # because we're matching a section which should have ended.\n+ # If we had a match, it would have matched by now, so this\n+ # means no match.\n+ pass\n+ # From here we'll drop out to the happy unmatched exit.\n+ else: # pragma: no cover\n+ # This shouldn't happen!?\n+ raise NotImplementedError(\n+ \"This shouldn't happen. Panic in \"\n+ \"_bracket_sensitive_look_ahead_match.\"\n+ )\n+ # Not in a bracket stack, but no match.\n+ # From here we'll drop out to the happy unmatched exit.\n+ else:\n+ # No we're at the end:\n+ # Now check have we closed all our brackets?\n+ if bracket_stack: # pragma: no cover\n+ # No we haven't.\n+ raise SQLParseError(\n+ \"Couldn't find closing bracket for opened brackets: \"\n+ f\"`{bracket_stack}`.\",\n+ segment=bracket_stack[-1].bracket,\n+ )\n+\n+ # This is the happy unmatched path. This occurs when:\n+ # - We reached the end with no open brackets.\n+ # - No match while outside a bracket stack.\n+ # - We found an unexpected end bracket before matching something\n+ # interesting. We return with the mutated segments so we can reuse any\n+ # bracket matching.\n+ return ((), MatchResult.from_unmatched(pre_seg_buff + seg_buff), None)\n+\n+\n+def greedy_match(\n+ segments: Tuple[BaseSegment, ...],\n+ parse_context: ParseContext,\n+ matchers: Sequence[MatchableType],\n+ include_terminator: bool = False,\n+) -> MatchResult:\n+ \"\"\"Looks ahead to claim everything up to some future terminators.\"\"\"\n+ seg_buff = segments\n+ seg_bank: Tuple[BaseSegment, ...] = () # Empty tuple\n+\n+ while True:\n+ with parse_context.deeper_match(name=\"GreedyUntil\") as ctx:\n+ pre, mat, matcher = bracket_sensitive_look_ahead_match(\n+ seg_buff, list(matchers), parse_context=ctx\n+ )\n+\n+ if not mat:\n+ # No terminator match? Return everything\n+ return MatchResult.from_matched(segments)\n+\n+ # NOTE: For some terminators we only count them if they're preceded\n+ # by whitespace, and others we don't. In principle, we aim that for\n+ # _keywords_ we require whitespace, and for symbols we don't.\n+ # We do this by looking at the `simple` method of the returned\n+ # matcher, and if it's entirely alphabetical (as defined by\n+ # str.isalpha()) then we infer that it's a keyword, and therefore\n+ # _does_ require whitespace before it.\n+ assert matcher, f\"Match without matcher: {mat}\"\n+ _simple = matcher.simple(parse_context)\n+ assert _simple, f\"Terminators require a simple method: {matcher}\"\n+ _strings, _types = _simple\n+ # NOTE: Typed matchers aren't common here, but we assume that they\n+ # _don't_ require preceding whitespace.\n+ # Do we need to enforce whitespace preceding?\n+ if all(_s.isalpha() for _s in _strings) and not _types:\n+ # Does the match include some whitespace already?\n+ # Work forward\n+ idx = 0\n+ while True:\n+ elem = mat.matched_segments[idx]\n+ if elem.is_meta: # pragma: no cover TODO?\n+ idx += 1\n+ continue\n+ elif elem.is_type(\"whitespace\", \"newline\"): # pragma: no cover TODO?\n+ allowable_match = True\n+ break\n+ else:\n+ # No whitespace before. Not allowed.\n+ allowable_match = False\n+ break\n+\n+ # If we're not ok yet, work backward to the preceding sections.\n+ if not allowable_match:\n+ idx = -1\n+ while True:\n+ if len(pre) < abs(idx): # pragma: no cover TODO?\n+ # If we're at the start, it's ok\n+ allowable_match = True\n+ break\n+ if pre[idx].is_meta: # pragma: no cover TODO?\n+ idx -= 1\n+ continue\n+ elif pre[idx].is_type(\"whitespace\", \"newline\"):\n+ allowable_match = True\n+ break\n+ else:\n+ # No whitespace before. Not allowed.\n+ allowable_match = False\n+ break\n+\n+ # If this match isn't preceded by whitespace and that is\n+ # a requirement, then we can't use it. Carry on...\n+ if not allowable_match:\n+ # Update our buffers and continue onward\n+ seg_bank = seg_bank + pre + mat.matched_segments\n+ seg_buff = mat.unmatched_segments\n+ # Loop around, don't return yet\n+ continue\n+\n+ # Return everything up to the match unless it's a gap matcher.\n+ if include_terminator:\n+ return MatchResult(\n+ seg_bank + pre + mat.matched_segments,\n+ mat.unmatched_segments,\n+ )\n+\n+ # We can't claim any non-code segments, so we trim them off the end.\n+ leading_nc, pre_seg_mid, trailing_nc = trim_non_code_segments(seg_bank + pre)\n+ return MatchResult(\n+ leading_nc + pre_seg_mid,\n+ trailing_nc + mat.all_segments(),\n+ )\ndiff --git a/src/sqlfluff/core/parser/match_logging.py b/src/sqlfluff/core/parser/match_logging.py\n--- a/src/sqlfluff/core/parser/match_logging.py\n+++ b/src/sqlfluff/core/parser/match_logging.py\n@@ -1,12 +1,9 @@\n \"\"\"Classes to help with match logging.\"\"\"\n \n import logging\n-from typing import TYPE_CHECKING, Any, Tuple\n-\n-from sqlfluff.core.parser.helpers import join_segments_raw_curtailed\n+from typing import TYPE_CHECKING, Any\n \n if TYPE_CHECKING: # pragma: no cover\n- from sqlfluff.core.parser import BaseSegment\n from sqlfluff.core.parser.context import ParseContext\n \n \n@@ -100,17 +97,3 @@ def parse_match_logging(\n ParseMatchLogObject(\n parse_context, grammar, func, msg, v_level=v_level, **kwargs\n ).log()\n-\n-\n-class LateBoundJoinSegmentsCurtailed:\n- \"\"\"Object to delay `join_segments_raw_curtailed` until later.\n-\n- This allows us to defer the string manipulation involved\n- until actually required by the logger.\n- \"\"\"\n-\n- def __init__(self, segments: Tuple[\"BaseSegment\", ...]) -> None:\n- self.segments = segments\n-\n- def __str__(self) -> str:\n- return repr(join_segments_raw_curtailed(self.segments))\n", "test_patch": "diff --git a/test/core/parser/grammar/grammar_base_test.py b/test/core/parser/grammar/grammar_base_test.py\n--- a/test/core/parser/grammar/grammar_base_test.py\n+++ b/test/core/parser/grammar/grammar_base_test.py\n@@ -3,18 +3,15 @@\n NOTE: All of these tests depend somewhat on the KeywordSegment working as planned.\n \"\"\"\n \n-import pytest\n import logging\n \n-from sqlfluff.core.parser import (\n- KeywordSegment,\n- StringParser,\n-)\n+import pytest\n+\n+from sqlfluff.core.parser import KeywordSegment, StringParser\n from sqlfluff.core.parser.context import ParseContext\n-from sqlfluff.core.parser.segments import EphemeralSegment\n-from sqlfluff.core.parser.grammar.base import BaseGrammar\n from sqlfluff.core.parser.grammar import OneOf, Sequence\n-from sqlfluff.core.errors import SQLParseError\n+from sqlfluff.core.parser.grammar.base import BaseGrammar\n+from sqlfluff.core.parser.segments import EphemeralSegment\n \n # NB: All of these tests depend somewhat on the KeywordSegment working as planned\n \n@@ -91,61 +88,6 @@ def test__parser__grammar__base__longest_trimmed_match__adv(seg_list, caplog):\n assert len(match) == 3\n \n \[email protected](\n- \"seg_list_slice,matcher_keywords,result_slice,winning_matcher,pre_match_slice\",\n- [\n- # Basic version, we should find bar first\n- (slice(None, None), [\"bar\", \"foo\"], slice(None, 1), \"bar\", None),\n- # Look ahead for foo\n- (slice(None, None), [\"foo\"], slice(2, 3), \"foo\", slice(None, 2)),\n- ],\n-)\n-def test__parser__grammar__base__look_ahead_match(\n- seg_list_slice,\n- matcher_keywords,\n- result_slice,\n- winning_matcher,\n- pre_match_slice,\n- seg_list,\n-):\n- \"\"\"Test the _look_ahead_match method of the BaseGrammar.\"\"\"\n- # Make the matcher keywords\n- matchers = [StringParser(keyword, KeywordSegment) for keyword in matcher_keywords]\n- # Fetch the matching keyword from above by index\n- winning_matcher = matchers[matcher_keywords.index(winning_matcher)]\n-\n- ctx = ParseContext(dialect=None)\n- m = BaseGrammar._look_ahead_match(\n- seg_list[seg_list_slice],\n- matchers,\n- ctx,\n- )\n-\n- # Check structure of the response.\n- assert isinstance(m, tuple)\n- assert len(m) == 3\n- # Unpack\n- result_pre_match, result_match, result_matcher = m\n-\n- # Check the right matcher won\n- assert result_matcher == winning_matcher\n-\n- # Make check tuple for the pre-match section\n- if pre_match_slice:\n- pre_match_slice = seg_list[pre_match_slice]\n- else:\n- pre_match_slice = ()\n- assert result_pre_match == pre_match_slice\n-\n- # Make the check tuple\n- expected_result = make_result_tuple(\n- result_slice=result_slice,\n- matcher_keywords=matcher_keywords,\n- seg_list=seg_list,\n- )\n- assert result_match.matched_segments == expected_result\n-\n-\n def test__parser__grammar__base__ephemeral_segment(seg_list):\n \"\"\"Test the ephemeral features on BaseGrammar.\n \n@@ -165,110 +107,3 @@ def test__parser__grammar__base__ephemeral_segment(seg_list):\n chkpoint = m.matched_segments[0]\n # Check it's got the same content.\n assert chkpoint.segments == seg_list\n-\n-\n-def test__parser__grammar__base__bracket_sensitive_look_ahead_match(\n- bracket_seg_list, fresh_ansi_dialect\n-):\n- \"\"\"Test the _bracket_sensitive_look_ahead_match method of the BaseGrammar.\"\"\"\n- bs = StringParser(\"bar\", KeywordSegment)\n- fs = StringParser(\"foo\", KeywordSegment)\n- # We need a dialect here to do bracket matching\n- ctx = ParseContext(dialect=fresh_ansi_dialect)\n- # Basic version, we should find bar first\n- pre_section, match, matcher = BaseGrammar._bracket_sensitive_look_ahead_match(\n- bracket_seg_list, [fs, bs], ctx\n- )\n- assert pre_section == ()\n- assert matcher == bs\n- # NB the middle element is a match object\n- assert match.matched_segments == (\n- KeywordSegment(\"bar\", bracket_seg_list[0].pos_marker),\n- )\n-\n- # Look ahead for foo, we should find the one AFTER the brackets, not the\n- # on IN the brackets.\n- pre_section, match, matcher = BaseGrammar._bracket_sensitive_look_ahead_match(\n- bracket_seg_list, [fs], ctx\n- )\n- # NB: The bracket segments will have been mutated, so we can't directly compare.\n- # Make sure we've got a bracketed section in there.\n- assert len(pre_section) == 5\n- assert pre_section[2].is_type(\"bracketed\")\n- assert len(pre_section[2].segments) == 4\n- assert matcher == fs\n- # We shouldn't match the whitespace with the keyword\n- assert match.matched_segments == (\n- KeywordSegment(\"foo\", bracket_seg_list[8].pos_marker),\n- )\n- # Check that the unmatched segments are nothing.\n- assert not match.unmatched_segments\n-\n-\n-def test__parser__grammar__base__bracket_fail_with_open_paren_close_square_mismatch(\n- generate_test_segments, fresh_ansi_dialect\n-):\n- \"\"\"Test _bracket_sensitive_look_ahead_match failure case.\n-\n- Should fail when the type of a close bracket doesn't match the type of the\n- corresponding open bracket, but both are \"definite\" brackets.\n- \"\"\"\n- fs = StringParser(\"foo\", KeywordSegment)\n- # We need a dialect here to do bracket matching\n- ctx = ParseContext(dialect=fresh_ansi_dialect)\n- # Basic version, we should find bar first\n- with pytest.raises(SQLParseError) as sql_parse_error:\n- BaseGrammar._bracket_sensitive_look_ahead_match(\n- generate_test_segments(\n- [\n- \"select\",\n- \" \",\n- \"*\",\n- \" \",\n- \"from\",\n- \"(\",\n- \"foo\",\n- \"]\", # Bracket types don't match (parens vs square)\n- ]\n- ),\n- [fs],\n- ctx,\n- )\n- assert sql_parse_error.match(\"Found unexpected end bracket\")\n-\n-\n-def test__parser__grammar__base__bracket_fail_with_unexpected_end_bracket(\n- generate_test_segments, fresh_ansi_dialect\n-):\n- \"\"\"Test _bracket_sensitive_look_ahead_match edge case.\n-\n- Should fail gracefully and stop matching if we find a trailing unmatched.\n- \"\"\"\n- fs = StringParser(\"foo\", KeywordSegment)\n- # We need a dialect here to do bracket matching\n- ctx = ParseContext(dialect=fresh_ansi_dialect)\n- _, match, _ = BaseGrammar._bracket_sensitive_look_ahead_match(\n- generate_test_segments(\n- [\n- \"bar\",\n- \"(\", # This bracket pair should be mutated\n- \")\",\n- \" \",\n- \")\", # This is the unmatched bracket\n- \" \",\n- \"foo\",\n- ]\n- ),\n- [fs],\n- ctx,\n- )\n- # Check we don't match (even though there's a foo at the end)\n- assert not match\n- # Check the first bracket pair have been mutated.\n- segs = match.unmatched_segments\n- assert segs[1].is_type(\"bracketed\")\n- assert segs[1].raw == \"()\"\n- assert len(segs[1].segments) == 2\n- # Check the trailing foo hasn't been mutated\n- assert segs[5].raw == \"foo\"\n- assert not isinstance(segs[5], KeywordSegment)\ndiff --git a/test/core/parser/grammar/grammar_ref_test.py b/test/core/parser/grammar/grammar_ref_test.py\n--- a/test/core/parser/grammar/grammar_ref_test.py\n+++ b/test/core/parser/grammar/grammar_ref_test.py\n@@ -23,6 +23,12 @@ def test__parser__grammar__ref_eq():\n assert r1 not in check_list\n \n \n+def test__parser__grammar__ref_repr():\n+ \"\"\"Test the __repr__ method of Ref.\"\"\"\n+ assert repr(Ref(\"foo\")) == \"<Ref: 'foo'>\"\n+ assert repr(Ref(\"bar\", optional=True)) == \"<Ref: 'bar' [opt]>\"\n+\n+\n def test__parser__grammar_ref_exclude(generate_test_segments, fresh_ansi_dialect):\n \"\"\"Test the Ref grammar exclude option.\"\"\"\n ni = Ref(\"NakedIdentifierSegment\", exclude=Ref.keyword(\"ABS\"))\ndiff --git a/test/core/parser/match_algorithms_test.py b/test/core/parser/match_algorithms_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/core/parser/match_algorithms_test.py\n@@ -0,0 +1,192 @@\n+\"\"\"Tests for the BaseGrammar and it's methods.\n+\n+NOTE: All of these tests depend somewhat on the KeywordSegment working as planned.\n+\"\"\"\n+\n+import pytest\n+\n+from sqlfluff.core.errors import SQLParseError\n+from sqlfluff.core.parser import KeywordSegment, StringParser\n+from sqlfluff.core.parser.context import ParseContext\n+from sqlfluff.core.parser.match_algorithms import (\n+ bracket_sensitive_look_ahead_match,\n+ look_ahead_match,\n+)\n+\n+# NB: All of these tests depend somewhat on the KeywordSegment working as planned\n+\n+\n+def make_result_tuple(result_slice, matcher_keywords, seg_list):\n+ \"\"\"Make a comparison tuple for test matching.\"\"\"\n+ # No result slice means no match.\n+ if not result_slice:\n+ return ()\n+\n+ return tuple(\n+ KeywordSegment(elem.raw, pos_marker=elem.pos_marker)\n+ if elem.raw in matcher_keywords\n+ else elem\n+ for elem in seg_list[result_slice]\n+ )\n+\n+\[email protected](\n+ \"seg_list_slice,matcher_keywords,result_slice,winning_matcher,pre_match_slice\",\n+ [\n+ # Basic version, we should find bar first\n+ (slice(None, None), [\"bar\", \"foo\"], slice(None, 1), \"bar\", None),\n+ # Look ahead for foo\n+ (slice(None, None), [\"foo\"], slice(2, 3), \"foo\", slice(None, 2)),\n+ ],\n+)\n+def test__parser__algorithms__look_ahead_match(\n+ seg_list_slice,\n+ matcher_keywords,\n+ result_slice,\n+ winning_matcher,\n+ pre_match_slice,\n+ seg_list,\n+):\n+ \"\"\"Test the look_ahead_match method of the BaseGrammar.\"\"\"\n+ # Make the matcher keywords\n+ matchers = [StringParser(keyword, KeywordSegment) for keyword in matcher_keywords]\n+ # Fetch the matching keyword from above by index\n+ winning_matcher = matchers[matcher_keywords.index(winning_matcher)]\n+\n+ ctx = ParseContext(dialect=None)\n+ m = look_ahead_match(\n+ seg_list[seg_list_slice],\n+ matchers,\n+ ctx,\n+ )\n+\n+ # Check structure of the response.\n+ assert isinstance(m, tuple)\n+ assert len(m) == 3\n+ # Unpack\n+ result_pre_match, result_match, result_matcher = m\n+\n+ # Check the right matcher won\n+ assert result_matcher == winning_matcher\n+\n+ # Make check tuple for the pre-match section\n+ if pre_match_slice:\n+ pre_match_slice = seg_list[pre_match_slice]\n+ else:\n+ pre_match_slice = ()\n+ assert result_pre_match == pre_match_slice\n+\n+ # Make the check tuple\n+ expected_result = make_result_tuple(\n+ result_slice=result_slice,\n+ matcher_keywords=matcher_keywords,\n+ seg_list=seg_list,\n+ )\n+ assert result_match.matched_segments == expected_result\n+\n+\n+def test__parser__algorithms__bracket_sensitive_look_ahead_match(\n+ bracket_seg_list, fresh_ansi_dialect\n+):\n+ \"\"\"Test the bracket_sensitive_look_ahead_match method of the BaseGrammar.\"\"\"\n+ bs = StringParser(\"bar\", KeywordSegment)\n+ fs = StringParser(\"foo\", KeywordSegment)\n+ # We need a dialect here to do bracket matching\n+ ctx = ParseContext(dialect=fresh_ansi_dialect)\n+ # Basic version, we should find bar first\n+ pre_section, match, matcher = bracket_sensitive_look_ahead_match(\n+ bracket_seg_list, [fs, bs], ctx\n+ )\n+ assert pre_section == ()\n+ assert matcher == bs\n+ # NB the middle element is a match object\n+ assert match.matched_segments == (\n+ KeywordSegment(\"bar\", bracket_seg_list[0].pos_marker),\n+ )\n+\n+ # Look ahead for foo, we should find the one AFTER the brackets, not the\n+ # on IN the brackets.\n+ pre_section, match, matcher = bracket_sensitive_look_ahead_match(\n+ bracket_seg_list, [fs], ctx\n+ )\n+ # NB: The bracket segments will have been mutated, so we can't directly compare.\n+ # Make sure we've got a bracketed section in there.\n+ assert len(pre_section) == 5\n+ assert pre_section[2].is_type(\"bracketed\")\n+ assert len(pre_section[2].segments) == 4\n+ assert matcher == fs\n+ # We shouldn't match the whitespace with the keyword\n+ assert match.matched_segments == (\n+ KeywordSegment(\"foo\", bracket_seg_list[8].pos_marker),\n+ )\n+ # Check that the unmatched segments are nothing.\n+ assert not match.unmatched_segments\n+\n+\n+def test__parser__algorithms__bracket_fail_with_open_paren_close_square_mismatch(\n+ generate_test_segments, fresh_ansi_dialect\n+):\n+ \"\"\"Test bracket_sensitive_look_ahead_match failure case.\n+\n+ Should fail when the type of a close bracket doesn't match the type of the\n+ corresponding open bracket, but both are \"definite\" brackets.\n+ \"\"\"\n+ fs = StringParser(\"foo\", KeywordSegment)\n+ # We need a dialect here to do bracket matching\n+ ctx = ParseContext(dialect=fresh_ansi_dialect)\n+ # Basic version, we should find bar first\n+ with pytest.raises(SQLParseError) as sql_parse_error:\n+ bracket_sensitive_look_ahead_match(\n+ generate_test_segments(\n+ [\n+ \"select\",\n+ \" \",\n+ \"*\",\n+ \" \",\n+ \"from\",\n+ \"(\",\n+ \"foo\",\n+ \"]\", # Bracket types don't match (parens vs square)\n+ ]\n+ ),\n+ [fs],\n+ ctx,\n+ )\n+ assert sql_parse_error.match(\"Found unexpected end bracket\")\n+\n+\n+def test__parser__algorithms__bracket_fail_with_unexpected_end_bracket(\n+ generate_test_segments, fresh_ansi_dialect\n+):\n+ \"\"\"Test bracket_sensitive_look_ahead_match edge case.\n+\n+ Should fail gracefully and stop matching if we find a trailing unmatched.\n+ \"\"\"\n+ fs = StringParser(\"foo\", KeywordSegment)\n+ # We need a dialect here to do bracket matching\n+ ctx = ParseContext(dialect=fresh_ansi_dialect)\n+ _, match, _ = bracket_sensitive_look_ahead_match(\n+ generate_test_segments(\n+ [\n+ \"bar\",\n+ \"(\", # This bracket pair should be mutated\n+ \")\",\n+ \" \",\n+ \")\", # This is the unmatched bracket\n+ \" \",\n+ \"foo\",\n+ ]\n+ ),\n+ [fs],\n+ ctx,\n+ )\n+ # Check we don't match (even though there's a foo at the end)\n+ assert not match\n+ # Check the first bracket pair have been mutated.\n+ segs = match.unmatched_segments\n+ assert segs[1].is_type(\"bracketed\")\n+ assert segs[1].raw == \"()\"\n+ assert len(segs[1].segments) == 2\n+ # Check the trailing foo hasn't been mutated\n+ assert segs[5].raw == \"foo\"\n+ assert not isinstance(segs[5], KeywordSegment)\n", "problem_statement": "[EXPERIMENT]: Rethink Matching routines\nThis is another experiment, and also a biggie. It's a rethink of matching as part of #5124.\r\n\r\nThis will need some tidying to get it into a state that it's reviewable, but given the scale of it - I think I shouldn't take it much further without getting some of it merged.\r\n\r\nIt's mostly additions for now, so I now need to strip out the things that we can get rid of as a result. Opening PR for testing and in particular for coverage.\n", "hints_text": "This is far too big, I'll divide it up into pieces before merging. I think other things need to come first.", "created_at": "2023-09-05T18:41:30Z", "version": "2.2", "FAIL_TO_PASS": ["test/core/parser/grammar/grammar_base_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice0-matcher_keywords0-False-result_slice0]", "test/core/parser/grammar/grammar_base_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice1-matcher_keywords1-True-result_slice1]", "test/core/parser/grammar/grammar_base_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice2-matcher_keywords2-False-None]", "test/core/parser/grammar/grammar_base_test.py::test__parser__grammar__base__longest_trimmed_match__basic[seg_list_slice3-matcher_keywords3-True-result_slice3]", "test/core/parser/grammar/grammar_base_test.py::test__parser__grammar__base__longest_trimmed_match__adv", "test/core/parser/grammar/grammar_base_test.py::test__parser__grammar__base__ephemeral_segment", "test/core/parser/grammar/grammar_ref_test.py::test__parser__grammar__ref_eq", "test/core/parser/grammar/grammar_ref_test.py::test__parser__grammar__ref_repr", "test/core/parser/grammar/grammar_ref_test.py::test__parser__grammar_ref_exclude", "test/core/parser/match_algorithms_test.py::test__parser__algorithms__look_ahead_match[seg_list_slice0-matcher_keywords0-result_slice0-bar-None]", "test/core/parser/match_algorithms_test.py::test__parser__algorithms__look_ahead_match[seg_list_slice1-matcher_keywords1-result_slice1-foo-pre_match_slice1]", "test/core/parser/match_algorithms_test.py::test__parser__algorithms__bracket_sensitive_look_ahead_match", "test/core/parser/match_algorithms_test.py::test__parser__algorithms__bracket_fail_with_open_paren_close_square_mismatch", "test/core/parser/match_algorithms_test.py::test__parser__algorithms__bracket_fail_with_unexpected_end_bracket"], "PASS_TO_PASS": [], "environment_setup_commit": "3625934f16857ade527f5f7dfa84b874061ea739"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3066", "base_commit": "2b93a26e6f15129fd1846bee52f51077eef7ca0c", "patch": "diff --git a/src/sqlfluff/core/templaters/slicers/tracer.py b/src/sqlfluff/core/templaters/slicers/tracer.py\n--- a/src/sqlfluff/core/templaters/slicers/tracer.py\n+++ b/src/sqlfluff/core/templaters/slicers/tracer.py\n@@ -10,6 +10,7 @@\n \n from jinja2 import Environment\n from jinja2.environment import Template\n+from jinja2.exceptions import TemplateSyntaxError\n \n from sqlfluff.core.templaters.base import (\n RawFileSlice,\n@@ -240,10 +241,21 @@ def update_inside_set_or_macro(\n # as other code inside these regions require special handling.\n # (Generally speaking, JinjaTracer ignores the contents of these\n # blocks, treating them like opaque templated regions.)\n- filtered_trimmed_parts = [p for p in trimmed_parts if not p.isspace()]\n- if len(filtered_trimmed_parts) < 3 or filtered_trimmed_parts[2] != \"=\":\n- # Entering a set/macro block.\n- self.inside_set_or_macro = True\n+ try:\n+ # Entering a set/macro block. Build a source string consisting\n+ # of just this one Jinja command and see if it parses. If so,\n+ # it's a standalone command. OTOH, if it fails with \"Unexpected\n+ # end of template\", it was the opening command for a block.\n+ self.env.from_string(\n+ f\"{self.env.block_start_string} {' '.join(trimmed_parts)} \"\n+ f\"{self.env.block_end_string}\"\n+ )\n+ except TemplateSyntaxError as e:\n+ if \"Unexpected end of template\" in e.message:\n+ # It was opening a block, thus we're inside a set or macro.\n+ self.inside_set_or_macro = True\n+ else:\n+ raise # pragma: no cover\n elif block_type == \"block_end\" and (trimmed_parts[0] in (\"endmacro\", \"endset\")):\n # Exiting a set/macro block.\n self.inside_set_or_macro = False\n", "test_patch": "diff --git a/test/core/templaters/jinja_test.py b/test/core/templaters/jinja_test.py\n--- a/test/core/templaters/jinja_test.py\n+++ b/test/core/templaters/jinja_test.py\n@@ -335,6 +335,58 @@ class RawTemplatedTestCase(NamedTuple):\n \"\\n\",\n ],\n ),\n+ RawTemplatedTestCase(\n+ \"set_multiple_variables_and_define_macro\",\n+ \"\"\"{% macro echo(text) %}\n+{{text}}\n+{% endmacro %}\n+\n+{% set a, b = 1, 2 %}\n+\n+SELECT\n+ {{ echo(a) }},\n+ {{ echo(b) }}\"\"\",\n+ \"\\n\\n\\n\\nSELECT\\n \\n1\\n,\\n \\n2\\n\",\n+ [\n+ \"{% macro echo(text) %}\",\n+ \"\\n\",\n+ \"{{text}}\",\n+ \"\\n\",\n+ \"{% endmacro %}\",\n+ \"\\n\\n\",\n+ \"{% set a, b = 1, 2 %}\",\n+ \"\\n\\nSELECT\\n \",\n+ \"{{ echo(a) }}\",\n+ \",\\n \",\n+ \"{{ echo(b) }}\",\n+ ],\n+ [\n+ \"\",\n+ \"\",\n+ \"\",\n+ \"\",\n+ \"\",\n+ \"\\n\\n\",\n+ \"\",\n+ \"\\n\\nSELECT\\n \",\n+ \"\\n1\\n\",\n+ \",\\n \",\n+ \"\\n2\\n\",\n+ ],\n+ [\n+ \"{% macro echo(text) %}\",\n+ \"\\n\",\n+ \"{{text}}\",\n+ \"\\n\",\n+ \"{% endmacro %}\",\n+ \"\\n\\n\",\n+ \"{% set a, b = 1, 2 %}\",\n+ \"\\n\\nSELECT\\n \",\n+ \"{{ echo(a) }}\",\n+ \",\\n \",\n+ \"{{ echo(b) }}\",\n+ ],\n+ ),\n ],\n ids=lambda case: case.name,\n )\n", "problem_statement": "Jinja: sqlfluff fails in the presence of assignments with multiple targets\n### Search before asking\r\n\r\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\r\n\r\nI did search, and I think this _may_ be related, but since no more information was provided I cannot confirm it: https://github.com/sqlfluff/sqlfluff/issues/2947. For this reason, I opened a new issue.\r\n\r\n### What Happened\r\n\r\nJinja templates support multiple targets in [assignments](https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments). However, `sqlfluff` fails to lint a file in the presence of an assignment with multiple targets.\r\n\r\nI traced this back to the `update_inside_set_or_macro` function, specifically [this line](https://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/core/templaters/slicers/tracer.py#L244=).\r\n\r\nThe way `sqlfluff` is determining whether we are inside a [block assignment](https://jinja.palletsprojects.com/en/3.0.x/templates/#block-assignments) is by checking for the presence of an equals in the second index of the trimmed parts of the current raw slice:\r\n\r\n```python\r\nif len(filtered_trimmed_parts) < 3 or filtered_trimmed_parts[2] != \"=\":\r\n```\r\n\r\nThis condition is false for single target assignments:\r\n\r\n```sql\r\n{% set a = 1 %}\r\n```\r\n\r\nWhich produce the expected trimmed parts (with spaces removed as in [line 243](https://github.com/sqlfluff/sqlfluff/blob/main/src/sqlfluff/core/templaters/slicers/tracer.py#L243=)):\r\n\r\n```python\r\n['set', 'a', '=', '1']\r\n# 2 \r\n```\r\n\r\nHowever, with multiple targets:\r\n\r\n```sql\r\n{% set a, b = 1, 2 %}\r\n```\r\n\r\n```python\r\n['set', 'a', ',', 'b', '=', '1', '2']\r\n# 4 \r\n```\r\n\r\nEquals is no longer in the index 2, but has been bumped to index 4, yet we are not in the expanded block form of set assignments. This causes the `inside_set_or_macro` flag to be incorrectly set to `True`, as if we were using a block assignment, which causes the entire template to be ignored (or something like that), and leads to the eventual `ValueError` raised.\r\n\r\nI played around a bit with potential solutions: first, I tried incrementing the index of the equals by the number of commas:\r\n\r\n```python\r\nequals_index = 2 + sum((c == ',' for c in filtered_trimmed_parts))\r\nif len(filtered_trimmed_parts) < 3 or filtered_trimmed_parts[equals_index] != \"=\":\r\n```\r\n\r\nHowever, this would bring issues if using the expanded form of set assignments with any commas in it, or in the presence of an uneven number of commas on both sides of the assignment.\r\n\r\nAnother simpler option would be to check for the presence of a single equals:\r\n\r\n```python\r\nif len(filtered_trimmed_parts) < 3 or filtered_trimmed_parts.count(\"=\") != 1:\r\n```\r\n\r\nThis one seems more promising, specially considering that multiple targets appear not to be supported with block assignments (at least, that's what I think, as the docs don't mention it, and trying it locally raises a too many values to unpack error). Thus, the first condition will always be true for block assignments (so, even the presence of an equals in the body of the assignment would not cause issues).\r\n\r\n### Expected Behaviour\r\n\r\nsqlfluff should lint files properly, even in the presence of assignments with multiple targets.\r\n\r\n### Observed Behaviour\r\n\r\nLinting fails when an exception is raised:\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"/home/tomasfarias/.pyenv/versions/3.10dbt/bin/sqlfluff\", line 8, in <module>\r\n sys.exit(cli())\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/click/core.py\", line 1128, in __call__\r\n return self.main(*args, **kwargs)\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/click/core.py\", line 1053, in main\r\n rv = self.invoke(ctx)\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/click/core.py\", line 1659, in invoke\r\n return _process_result(sub_ctx.command.invoke(sub_ctx))\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/click/core.py\", line 1395, in invoke\r\n return ctx.invoke(self.callback, **ctx.params)\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/click/core.py\", line 754, in invoke\r\n return __callback(*args, **kwargs)\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/cli/commands.py\", line 541, in lint\r\n result = lnt.lint_paths(\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/linter/linter.py\", line 1098, in lint_paths\r\n self.lint_path(\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/linter/linter.py\", line 1050, in lint_path\r\n for i, linted_file in enumerate(runner.run(fnames, fix), start=1):\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/linter/runner.py\", line 101, in run\r\n for fname, partial in self.iter_partials(fnames, fix=fix):\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/linter/runner.py\", line 54, in iter_partials\r\n for fname, rendered in self.iter_rendered(fnames):\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/linter/runner.py\", line 43, in iter_rendered\r\n yield fname, self.linter.render_file(fname, self.config)\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/linter/linter.py\", line 771, in render_file\r\n return self.render_string(raw_file, fname, config, encoding)\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/linter/linter.py\", line 742, in render_string\r\n templated_file, templater_violations = self.templater.process(\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/templaters/jinja.py\", line 394, in process\r\n TemplatedFile(\r\n File \"/home/tomasfarias/.pyenv/versions/3.10.2/envs/3.10dbt/lib/python3.10/site-packages/sqlfluff/core/templaters/base.py\", line 94, in __init__\r\n raise ValueError(\"Cannot instantiate a templated file unsliced!\")\r\nValueError: Cannot instantiate a templated file unsliced!\r\n```\r\n\r\n### How to reproduce\r\n\r\n1. Save the following template to `model.sql` in an empty directory:\r\n```sql\r\n{% set a, b = 1, 2 %}\r\n\r\nSELECT {{ a }}\r\n```\r\n2. Run `sqlfluff lint model.sql --dialect 'postgres'`\r\n\r\n\r\n### Dialect\r\n\r\nTried with postgres and redshift dialects, however I think others may be affected as long as they use jinja templates.\r\n\r\n### Version\r\n\r\nv0.12.0\r\n\r\n### Configuration\r\n\r\nNothing, ran from an empty directory.\r\n\r\n### Are you willing to work on and submit a PR to address the issue?\r\n\r\n- [X] Yes I am willing to submit a PR!\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\r\n\n", "hints_text": "Heh, I didn't know this syntax was possible, but not surprising since it's valid in Python itself.\r\n\r\nI have wondered if we could potentially run the Python parser on the text inside the brackets. Jinja syntax is mostly the same as Python.\nPerhaps we can leverage [this](https://github.com/pallets/jinja/blob/main/src/jinja2/parser.py#L223L232) from the Jinja parser, either calling it directly or mimicking its behavior.\r\n\r\nNote that (IIUC) it returns an `Assign` object if it's a standalone tag or an `AssignBlock` if it's part of a set/endset pair.\r\n\r\n```\r\n def parse_set(self) -> t.Union[nodes.Assign, nodes.AssignBlock]:\r\n \"\"\"Parse an assign statement.\"\"\"\r\n lineno = next(self.stream).lineno\r\n target = self.parse_assign_target(with_namespace=True)\r\n if self.stream.skip_if(\"assign\"):\r\n expr = self.parse_tuple()\r\n return nodes.Assign(target, expr, lineno=lineno)\r\n filter_node = self.parse_filter(None)\r\n body = self.parse_statements((\"name:endset\",), drop_needle=True)\r\n return nodes.AssignBlock(target, filter_node, body, lineno=lineno)\r\n```", "created_at": "2022-04-10T19:20:47Z", "version": "0.12", "FAIL_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja_slices[set_multiple_variables_and_define_macro]"], "PASS_TO_PASS": ["test/core/templaters/jinja_test.py::test__templater_jinja[simple]", "test/core/templaters/jinja_test.py::test__templater_jinja[unboundlocal_bugfix]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_left_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_block]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[basic_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_right_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_data]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[strip_both_comment]", "test/core/templaters/jinja_test.py::test__templater_jinja_slices[union_all_loop1]", "test/core/templaters/jinja_test.py::test_templater_set_block_handling", "test/core/templaters/jinja_test.py::test__templater_jinja_error_variable", "test/core/templaters/jinja_test.py::test__templater_jinja_dynamic_variable_no_violations", "test/core/templaters/jinja_test.py::test__templater_jinja_error_syntax", "test/core/templaters/jinja_test.py::test__templater_jinja_error_catastrophic", "test/core/templaters/jinja_test.py::test__templater_jinja_error_macro_path_does_not_exist", "test/core/templaters/jinja_test.py::test__templater_jinja_lint_empty", "test/core/templaters/jinja_test.py::test__templater_full[jinja_a/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_b/jinja-False-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_config-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_is_incremental-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_ref-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_source-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_this-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_c_dbt/dbt_builtins_var_default-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_e/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_f/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_g_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_h_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_i_raw/raw_tag_2-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_j_libraries/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_k_config_override_path_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/001-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_l_metas/002-False-True]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_m_libraries_module/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_n_nested_macros/jinja-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_o_config_override_dbt_builtins/override_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_full[jinja_p_disable_dbt_builtins/disable_dbt_builtins-True-False]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[foo", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_template[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[-None-result0]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[foo-None-result1]", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{{", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[SELECT\\n", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[{%-", "test/core/templaters/jinja_test.py::test__templater_jinja_slice_file[select\\n"], "environment_setup_commit": "8f6fd1d8a8d69b2c463fbcf5bd1131c47f12ad88"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2625", "base_commit": "d44c83e7cee923869e3ca6149da4e6d1ad0286eb", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -6,13 +6,7 @@\n import logging\n import time\n from logging import LogRecord\n-from typing import (\n- Callable,\n- Tuple,\n- NoReturn,\n- Optional,\n- List,\n-)\n+from typing import Callable, Tuple, NoReturn, Optional, List, cast\n \n import yaml\n \n@@ -418,6 +412,17 @@ def dialects(**kwargs) -> None:\n click.echo(format_dialects(dialect_readout), color=c.get(\"color\"))\n \n \n+def dump_file_payload(filename: Optional[str], payload: str):\n+ \"\"\"Write the output file content to stdout or file.\"\"\"\n+ # If there's a file specified to write to, write to it.\n+ if filename:\n+ with open(filename, \"w\") as out_file:\n+ out_file.write(payload)\n+ # Otherwise write to stdout\n+ else:\n+ click.echo(payload)\n+\n+\n @cli.command()\n @common_options\n @core_options\n@@ -429,6 +434,14 @@ def dialects(**kwargs) -> None:\n type=click.Choice([ft.value for ft in FormatType], case_sensitive=False),\n help=\"What format to return the lint result in (default=human).\",\n )\[email protected](\n+ \"--write-output\",\n+ help=(\n+ \"Optionally provide a filename to write the results to, mostly used in \"\n+ \"tandem with --format. NB: Setting an output file re-enables normal \"\n+ \"stdout logging.\"\n+ ),\n+)\n @click.option(\n \"--annotation-level\",\n default=\"notice\",\n@@ -468,6 +481,7 @@ def lint(\n paths: Tuple[str],\n processes: int,\n format: str,\n+ write_output: Optional[str],\n annotation_level: str,\n nofail: bool,\n disregard_sqlfluffignores: bool,\n@@ -497,7 +511,8 @@ def lint(\n \n \"\"\"\n config = get_config(extra_config_path, ignore_local_config, **kwargs)\n- non_human_output = format != FormatType.human.value\n+ non_human_output = (format != FormatType.human.value) or (write_output is not None)\n+ file_output = None\n lnt, formatter = get_linter_and_formatter(config, silent=non_human_output)\n \n verbose = config.get(\"verbose\")\n@@ -535,9 +550,9 @@ def lint(\n click.echo(format_linting_stats(result, verbose=verbose))\n \n if format == FormatType.json.value:\n- click.echo(json.dumps(result.as_records()))\n+ file_output = json.dumps(result.as_records())\n elif format == FormatType.yaml.value:\n- click.echo(yaml.dump(result.as_records(), sort_keys=False))\n+ file_output = yaml.dump(result.as_records(), sort_keys=False)\n elif format == FormatType.github_annotation.value:\n github_result = []\n for record in result.as_records():\n@@ -558,7 +573,10 @@ def lint(\n \"annotation_level\": annotation_level,\n }\n )\n- click.echo(json.dumps(github_result))\n+ file_output = json.dumps(github_result)\n+\n+ if file_output:\n+ dump_file_payload(write_output, cast(str, file_output))\n \n if bench:\n click.echo(\"==== overall timings ====\")\n@@ -876,6 +894,14 @@ def quoted_presenter(dumper, data):\n ),\n help=\"What format to return the parse result in.\",\n )\[email protected](\n+ \"--write-output\",\n+ help=(\n+ \"Optionally provide a filename to write the results to, mostly used in \"\n+ \"tandem with --format. NB: Setting an output file re-enables normal \"\n+ \"stdout logging.\"\n+ ),\n+)\n @click.option(\n \"--profiler\", is_flag=True, help=\"Set this flag to engage the python profiler.\"\n )\n@@ -892,6 +918,7 @@ def parse(\n code_only: bool,\n include_meta: bool,\n format: str,\n+ write_output: Optional[str],\n profiler: bool,\n bench: bool,\n nofail: bool,\n@@ -909,7 +936,8 @@ def parse(\n \"\"\"\n c = get_config(extra_config_path, ignore_local_config, **kwargs)\n # We don't want anything else to be logged if we want json or yaml output\n- non_human_output = format in (FormatType.json.value, FormatType.yaml.value)\n+ # unless we're writing to a file.\n+ non_human_output = (format != FormatType.human.value) or (write_output is not None)\n lnt, formatter = get_linter_and_formatter(c, silent=non_human_output)\n verbose = c.get(\"verbose\")\n recurse = c.get(\"recurse\")\n@@ -975,9 +1003,12 @@ def parse(\n # For yaml dumping always dump double quoted strings if they contain\n # tabs or newlines.\n yaml.add_representer(str, quoted_presenter)\n- click.echo(yaml.dump(parsed_strings_dict, sort_keys=False))\n+ file_output = yaml.dump(parsed_strings_dict, sort_keys=False)\n elif format == FormatType.json.value:\n- click.echo(json.dumps(parsed_strings_dict))\n+ file_output = json.dumps(parsed_strings_dict)\n+\n+ # Dump the output to stdout or to file as appropriate.\n+ dump_file_payload(write_output, file_output)\n \n except OSError: # pragma: no cover\n click.echo(\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -798,19 +798,35 @@ def test__cli__command__fix_no_force(rule, fname, prompt, exit_code, fix_exit_co\n \n \n @pytest.mark.parametrize(\"serialize\", [\"yaml\", \"json\"])\n-def test__cli__command_parse_serialize_from_stdin(serialize):\[email protected](\"write_file\", [None, \"outfile\"])\n+def test__cli__command_parse_serialize_from_stdin(serialize, write_file, tmp_path):\n \"\"\"Check that the parser serialized output option is working.\n \n+ This tests both output to stdout and output to file.\n+\n Not going to test for the content of the output as that is subject to change.\n \"\"\"\n+ cmd_args = (\"-\", \"--format\", serialize)\n+\n+ if write_file:\n+ target_file = os.path.join(tmp_path, write_file + \".\" + serialize)\n+ cmd_args += (\"--write-output\", target_file)\n+\n result = invoke_assert_code(\n- args=[parse, (\"-\", \"--format\", serialize)],\n+ args=[parse, cmd_args],\n cli_input=\"select * from tbl\",\n )\n+\n+ if write_file:\n+ with open(target_file, \"r\") as payload_file:\n+ result_payload = payload_file.read()\n+ else:\n+ result_payload = result.output\n+\n if serialize == \"json\":\n- result = json.loads(result.output)\n+ result = json.loads(result_payload)\n elif serialize == \"yaml\":\n- result = yaml.safe_load(result.output)\n+ result = yaml.safe_load(result_payload)\n else:\n raise Exception\n result = result[0] # only one file\n@@ -880,24 +896,42 @@ def test__cli__command_fail_nice_not_found(command):\n \n \n @pytest.mark.parametrize(\"serialize\", [\"yaml\", \"json\", \"github-annotation\"])\n-def test__cli__command_lint_serialize_multiple_files(serialize):\n- \"\"\"Check the general format of JSON output for multiple files.\"\"\"\[email protected](\"write_file\", [None, \"outfile\"])\n+def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_path):\n+ \"\"\"Check the general format of JSON output for multiple files.\n+\n+ This tests runs both stdout checking and file checking.\n+ \"\"\"\n fpath = \"test/fixtures/linter/indentation_errors.sql\"\n \n+ cmd_args = (fpath, fpath, \"--format\", serialize, \"--disable_progress_bar\")\n+\n+ if write_file:\n+ target_file = os.path.join(\n+ tmp_path, write_file + (\".yaml\" if serialize == \"yaml\" else \".json\")\n+ )\n+ cmd_args += (\"--write-output\", target_file)\n+\n # note the file is in here twice. two files = two payloads.\n result = invoke_assert_code(\n- args=[lint, (fpath, fpath, \"--format\", serialize, \"--disable_progress_bar\")],\n+ args=[lint, cmd_args],\n ret_code=65,\n )\n \n+ if write_file:\n+ with open(target_file, \"r\") as payload_file:\n+ result_payload = payload_file.read()\n+ else:\n+ result_payload = result.output\n+\n if serialize == \"json\":\n- result = json.loads(result.output)\n+ result = json.loads(result_payload)\n assert len(result) == 2\n elif serialize == \"yaml\":\n- result = yaml.safe_load(result.output)\n+ result = yaml.safe_load(result_payload)\n assert len(result) == 2\n elif serialize == \"github-annotation\":\n- result = json.loads(result.output)\n+ result = json.loads(result_payload)\n filepaths = {r[\"file\"] for r in result}\n assert len(filepaths) == 1\n else:\n", "problem_statement": "Suppress dbt logs and warnings when using --format github-annotation\nSometimes, running:\r\n```\r\nsqlfluff lint --format github-annotation --annotation-level failure --nofail \r\n```\r\n\r\nCan result in the first couple of output lines being logs which break the annotations, for example:\r\n```\r\n14:21:42 Partial parse save file not found. Starting full parse.\r\nWarning: [WARNING]: Did not find matching node for patch with name 'xxxx' in the 'models' section of file 'models/production/xxxxx/xxxxx.yml'\r\n```\r\n\r\n## Version\r\ndbt 1.0.0, SQLFLuff 0.9.0\r\n\n", "hints_text": "my workaround was to add `sed -i '/^\\[/!d' annotations.json` to the git actions command to delete the extra lines from dbt that were not part of the annotations beginning with `[`\nPerhaps the better solution here is to add an ability for SQLFluff to write an annotations.json file itself with a command like\r\n```\r\nsqlfluff lint --format github-annotation --annotation-level failure --nofail ${{ steps.get_files_to_lint.outputs.lintees }} --write-output annotations.json\r\n```\r\nwhich would still allow the user to see log outputs, rather than the user having to stream the logs into a file with:\r\n\r\n```\r\nsqlfluff lint --format github-annotation --annotation-level failure --nofail ${{ steps.get_files_to_lint.outputs.lintees }} > annotations.json\r\n```\nRelates to https://github.com/sqlfluff/sqlfluff-github-actions/issues/15\n@NiallRees: That sounds like a great suggestion -- I had the same thought. I was the original author of the `github-annotation` format, and it seemed natural to add it to the existing list of formats. TBH, of the 4 formats, only one is intended for humans. If we make this change, I suggest we consider changing all the formats to support this.", "created_at": "2022-02-13T13:24:21Z", "version": "0.9", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-65-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_pass_on_correct_encoding_argument", "test/cli/commands_test.py::test_cli_fail_on_wrong_encoding_argument", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_when_verbose_mode"], "environment_setup_commit": "a4dcf3f08d95cbde4efb39969b0ab8e33a791f21"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-891", "base_commit": "bcc986e7d217f017130385b89cbda837f3e650ac", "patch": "diff --git a/src/sqlfluff/core/errors.py b/src/sqlfluff/core/errors.py\n--- a/src/sqlfluff/core/errors.py\n+++ b/src/sqlfluff/core/errors.py\n@@ -82,9 +82,9 @@ def pos_marker(self):\n \"\"\"Get the position marker of the violation.\n \n Returns:\n- The :obj:`PosMarker` of the segments if the violation has a segment,\n- the :obj:`PosMarker` directly stored in a `pos` attribute or None\n- if neither a present.\n+ The :obj:`FilePositionMarker` of the segments if the violation has a segment,\n+ the :obj:`FilePositionMarker` directly stored in a `pos` attribute or None\n+ if neither is present.\n \n \"\"\"\n if hasattr(self, \"segment\"):\ndiff --git a/src/sqlfluff/core/linter.py b/src/sqlfluff/core/linter.py\n--- a/src/sqlfluff/core/linter.py\n+++ b/src/sqlfluff/core/linter.py\n@@ -53,6 +53,14 @@ class RuleTuple(NamedTuple):\n description: str\n \n \n+class NoQaDirective(NamedTuple):\n+ \"\"\"Parsed version of a 'noqa' comment.\"\"\"\n+\n+ line_no: int # Source line number\n+ rules: Optional[Tuple[str, ...]] # Affected rule names\n+ action: Optional[str] # \"enable\", \"disable\", or \"None\"\n+\n+\n class ProtoFile(NamedTuple):\n \"\"\"Proto object to be inherited by LintedFile.\"\"\"\n \n@@ -60,7 +68,7 @@ class ProtoFile(NamedTuple):\n violations: list\n time_dict: dict\n tree: Any\n- ignore_mask: list\n+ ignore_mask: List[NoQaDirective]\n \n \n class ParsedString(NamedTuple):\n@@ -95,10 +103,10 @@ class LintedFile(NamedTuple):\n \"\"\"A class to store the idea of a linted file.\"\"\"\n \n path: str\n- violations: list\n+ violations: List[SQLBaseError]\n time_dict: dict\n tree: Optional[BaseSegment]\n- ignore_mask: list\n+ ignore_mask: List[NoQaDirective]\n templated_file: TemplatedFile\n \n def check_tuples(self) -> List[CheckTuple]:\n@@ -152,15 +160,90 @@ def get_violations(\n violations = [v for v in violations if not v.ignore]\n # Ignore any rules in the ignore mask\n if self.ignore_mask:\n- for line_no, rules in self.ignore_mask:\n- violations = [\n- v\n- for v in violations\n- if not (\n- v.line_no() == line_no\n- and (rules is None or v.rule_code() in rules)\n- )\n- ]\n+ violations = self._ignore_masked_violations(violations)\n+ return violations\n+\n+ @staticmethod\n+ def _ignore_masked_violations_single_line(\n+ violations: List[SQLBaseError], ignore_mask: List[NoQaDirective]\n+ ):\n+ \"\"\"Returns whether to ignore error for line-specific directives.\n+\n+ The \"ignore\" list is assumed to ONLY contain NoQaDirectives with\n+ action=None.\n+ \"\"\"\n+ for ignore in ignore_mask:\n+ violations = [\n+ v\n+ for v in violations\n+ if not (\n+ v.line_no() == ignore.line_no\n+ and (ignore.rules is None or v.rule_code() in ignore.rules)\n+ )\n+ ]\n+ return violations\n+\n+ @staticmethod\n+ def _should_ignore_violation_line_range(\n+ line_no: int, ignore_rule: List[NoQaDirective]\n+ ):\n+ \"\"\"Returns whether to ignore a violation at line_no.\"\"\"\n+ # Loop through the NoQaDirectives to find the state of things at\n+ # line_no. Assumptions about \"ignore_rule\":\n+ # - Contains directives for only ONE RULE, i.e. the rule that was\n+ # violated at line_no\n+ # - Sorted in ascending order by line number\n+ disable = False\n+ for ignore in ignore_rule:\n+ if ignore.line_no > line_no:\n+ break\n+ disable = ignore.action == \"disable\"\n+ return disable\n+\n+ @classmethod\n+ def _ignore_masked_violations_line_range(\n+ cls, violations: List[SQLBaseError], ignore_mask: List[NoQaDirective]\n+ ):\n+ \"\"\"Returns whether to ignore error for line-range directives.\n+\n+ The \"ignore\" list is assumed to ONLY contain NoQaDirectives where\n+ action is \"enable\" or \"disable\".\n+ \"\"\"\n+ result = []\n+ for v in violations:\n+ # Find the directives that affect the violated rule \"v\", either\n+ # because they specifically reference it or because they don't\n+ # specify a list of rules, thus affecting ALL rules.\n+ ignore_rule = sorted(\n+ [\n+ ignore\n+ for ignore in ignore_mask\n+ if not ignore.rules\n+ or (v.rule_code() in cast(Tuple[str, ...], ignore.rules))\n+ ],\n+ key=lambda ignore: ignore.line_no,\n+ )\n+ # Determine whether to ignore the violation, based on the relevant\n+ # enable/disable directives.\n+ if not cls._should_ignore_violation_line_range(v.line_no(), ignore_rule):\n+ result.append(v)\n+ return result\n+\n+ def _ignore_masked_violations(\n+ self, violations: List[SQLBaseError]\n+ ) -> List[SQLBaseError]:\n+ \"\"\"Remove any violations specified by ignore_mask.\n+\n+ This involves two steps:\n+ 1. Filter out violations affected by single-line \"noqa\" directives.\n+ 2. Filter out violations affected by disable/enable \"noqa\" directives.\n+ \"\"\"\n+ ignore_specific = [ignore for ignore in self.ignore_mask if not ignore.action]\n+ ignore_range = [ignore for ignore in self.ignore_mask if ignore.action]\n+ violations = self._ignore_masked_violations_single_line(\n+ violations, ignore_specific\n+ )\n+ violations = self._ignore_masked_violations_line_range(violations, ignore_range)\n return violations\n \n def num_violations(self, **kwargs) -> int:\n@@ -907,27 +990,53 @@ def parse_string(\n bencher(\"Finish parsing {0!r}\".format(short_fname))\n return ParsedString(parsed, violations, time_dict, templated_file, config)\n \n- @staticmethod\n- def extract_ignore_from_comment(comment: RawSegment):\n- \"\"\"Extract ignore mask entries from a comment segment.\"\"\"\n+ @classmethod\n+ def parse_noqa(cls, comment: str, line_no: int):\n+ \"\"\"Extract ignore mask entries from a comment string.\"\"\"\n # Also trim any whitespace afterward\n- comment_content = comment.raw_trimmed().strip()\n- if comment_content.startswith(\"noqa\"):\n+ if comment.startswith(\"noqa\"):\n # This is an ignore identifier\n- comment_remainder = comment_content[4:]\n+ comment_remainder = comment[4:]\n if comment_remainder:\n if not comment_remainder.startswith(\":\"):\n return SQLParseError(\n \"Malformed 'noqa' section. Expected 'noqa: <rule>[,...]\",\n- segment=comment,\n )\n- comment_remainder = comment_remainder[1:]\n- rules = [r.strip() for r in comment_remainder.split(\",\")]\n- return (comment.pos_marker.line_no, tuple(rules))\n- else:\n- return (comment.pos_marker.line_no, None)\n+ comment_remainder = comment_remainder[1:].strip()\n+ if comment_remainder:\n+ action: Optional[str]\n+ if \"=\" in comment_remainder:\n+ action, rule_part = comment_remainder.split(\"=\", 1)\n+ if action not in {\"disable\", \"enable\"}:\n+ return SQLParseError(\n+ \"Malformed 'noqa' section. Expected 'noqa: enable=<rule>[,...] | all' or 'noqa: disable=<rule>[,...] | all\",\n+ )\n+ else:\n+ action = None\n+ rule_part = comment_remainder\n+ if rule_part in {\"disable\", \"enable\"}:\n+ return SQLParseError(\n+ \"Malformed 'noqa' section. Expected 'noqa: enable=<rule>[,...] | all' or 'noqa: disable=<rule>[,...] | all\",\n+ )\n+ rules: Optional[Tuple[str, ...]]\n+ if rule_part != \"all\":\n+ rules = tuple(r.strip() for r in rule_part.split(\",\"))\n+ else:\n+ rules = None\n+ return NoQaDirective(line_no, rules, action)\n+ return NoQaDirective(line_no, None, None)\n return None\n \n+ @classmethod\n+ def extract_ignore_from_comment(cls, comment: RawSegment):\n+ \"\"\"Extract ignore mask entries from a comment segment.\"\"\"\n+ # Also trim any whitespace afterward\n+ comment_content = comment.raw_trimmed().strip()\n+ result = cls.parse_noqa(comment_content, comment.pos_marker.line_no)\n+ if isinstance(result, SQLParseError):\n+ result.segment = comment\n+ return result\n+\n @staticmethod\n def _warn_unfixable(code: str):\n linter_logger.warning(\n", "test_patch": "diff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -1,11 +1,23 @@\n \"\"\"The Test file for the linter class.\"\"\"\n \n import pytest\n+from typing import List\n from unittest.mock import patch\n \n from sqlfluff.core import Linter, FluffConfig\n-from sqlfluff.core.errors import SQLLintError, SQLParseError\n-from sqlfluff.core.linter import LintingResult\n+from sqlfluff.core.errors import SQLBaseError, SQLLintError, SQLParseError\n+from sqlfluff.core.linter import LintingResult, NoQaDirective\n+import sqlfluff.core.linter as linter\n+from sqlfluff.core.parser import FilePositionMarker\n+\n+\n+class DummyLintError(SQLBaseError):\n+ \"\"\"Fake lint error used by tests, similar to SQLLintError.\"\"\"\n+\n+ def __init__(self, pos: FilePositionMarker, code: str = \"L001\"):\n+ self.pos = pos\n+ self._code = code\n+ super(DummyLintError, self).__init__()\n \n \n def normalise_paths(paths):\n@@ -193,7 +205,7 @@ def test__linter__linting_unexpected_error_handled_gracefully(\n \"\"\"Test that an unexpected internal error is handled gracefully and returns the issue-surfacing file.\"\"\"\n patched_lint_string.side_effect = Exception(\"Something unexpected happened\")\n lntr = Linter()\n- lntr.lint_paths([\"test/fixtures/linter/passing.sql\"])\n+ lntr.lint_paths((\"test/fixtures/linter/passing.sql\",))\n assert (\n \"Unable to lint test/fixtures/linter/passing.sql due to an internal error.\"\n # NB: Replace is to handle windows-style paths.\n@@ -249,3 +261,240 @@ def test__linter__mask_templated_violations(ignore_templated_areas, check_tuples\n )\n linted = lntr.lint_path(path=\"test/fixtures/templater/jinja_h_macros/jinja.sql\")\n assert linted.check_tuples() == check_tuples\n+\n+\[email protected](\n+ \"input,expected\",\n+ [\n+ (\"\", None),\n+ (\"noqa\", NoQaDirective(0, None, None)),\n+ (\"noqa?\", SQLParseError),\n+ (\"noqa:\", NoQaDirective(0, None, None)),\n+ (\"noqa:L001,L002\", NoQaDirective(0, (\"L001\", \"L002\"), None)),\n+ (\"noqa: enable=L005\", NoQaDirective(0, (\"L005\",), \"enable\")),\n+ (\"noqa: disable=L010\", NoQaDirective(0, (\"L010\",), \"disable\")),\n+ (\"noqa: disable=all\", NoQaDirective(0, None, \"disable\")),\n+ (\"noqa: disable\", SQLParseError),\n+ ],\n+)\n+def test_parse_noqa(input, expected):\n+ \"\"\"Test correct of \"noqa\" comments.\"\"\"\n+ result = Linter.parse_noqa(input, 0)\n+ if not isinstance(expected, type):\n+ assert result == expected\n+ else:\n+ # With exceptions, just check the type, not the contents.\n+ assert isinstance(result, expected)\n+\n+\[email protected](\n+ \"noqa,violations,expected\",\n+ [\n+ [\n+ [],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [\n+ 0,\n+ ],\n+ ],\n+ [\n+ [dict(comment=\"noqa: L001\", line_no=1)],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [],\n+ ],\n+ [\n+ [dict(comment=\"noqa: L001\", line_no=2)],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [0],\n+ ],\n+ [\n+ [dict(comment=\"noqa: L002\", line_no=1)],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [0],\n+ ],\n+ [\n+ [dict(comment=\"noqa: enable=L001\", line_no=1)],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [0],\n+ ],\n+ [\n+ [dict(comment=\"noqa: disable=L001\", line_no=1)],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=L001\", line_no=2),\n+ dict(comment=\"noqa: enable=L001\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [0],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=L001\", line_no=2),\n+ dict(comment=\"noqa: enable=L001\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=2))],\n+ [],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=L001\", line_no=2),\n+ dict(comment=\"noqa: enable=L001\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=3))],\n+ [],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=L001\", line_no=2),\n+ dict(comment=\"noqa: enable=L001\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=4))],\n+ [0],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=all\", line_no=2),\n+ dict(comment=\"noqa: enable=all\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=1))],\n+ [0],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=all\", line_no=2),\n+ dict(comment=\"noqa: enable=all\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=2))],\n+ [],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=all\", line_no=2),\n+ dict(comment=\"noqa: enable=all\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=3))],\n+ [],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=all\", line_no=2),\n+ dict(comment=\"noqa: enable=all\", line_no=4),\n+ ],\n+ [DummyLintError(FilePositionMarker(statement_index=None, line_no=4))],\n+ [0],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=L001\", line_no=2),\n+ dict(comment=\"noqa: enable=all\", line_no=4),\n+ ],\n+ [\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=2), code=\"L001\"\n+ ),\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=2), code=\"L002\"\n+ ),\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=4), code=\"L001\"\n+ ),\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=4), code=\"L002\"\n+ ),\n+ ],\n+ [1, 2, 3],\n+ ],\n+ [\n+ [\n+ dict(comment=\"noqa: disable=all\", line_no=2),\n+ dict(comment=\"noqa: enable=L001\", line_no=4),\n+ ],\n+ [\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=2), code=\"L001\"\n+ ),\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=2), code=\"L002\"\n+ ),\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=4), code=\"L001\"\n+ ),\n+ DummyLintError(\n+ FilePositionMarker(statement_index=None, line_no=4), code=\"L002\"\n+ ),\n+ ],\n+ [2],\n+ ],\n+ ],\n+ ids=[\n+ \"1_violation_no_ignore\",\n+ \"1_violation_ignore_specific_line\",\n+ \"1_violation_ignore_different_specific_line\",\n+ \"1_violation_ignore_different_specific_rule\",\n+ \"1_violation_ignore_enable_this_range\",\n+ \"1_violation_ignore_disable_this_range\",\n+ \"1_violation_line_1_ignore_disable_specific_2_3\",\n+ \"1_violation_line_2_ignore_disable_specific_2_3\",\n+ \"1_violation_line_3_ignore_disable_specific_2_3\",\n+ \"1_violation_line_4_ignore_disable_specific_2_3\",\n+ \"1_violation_line_1_ignore_disable_all_2_3\",\n+ \"1_violation_line_2_ignore_disable_all_2_3\",\n+ \"1_violation_line_3_ignore_disable_all_2_3\",\n+ \"1_violation_line_4_ignore_disable_all_2_3\",\n+ \"4_violations_two_types_disable_specific_enable_all\",\n+ \"4_violations_two_types_disable_all_enable_specific\",\n+ ],\n+)\n+def test_linted_file_ignore_masked_violations(\n+ noqa: dict, violations: List[SQLBaseError], expected\n+):\n+ \"\"\"Test that _ignore_masked_violations() correctly filters violations.\"\"\"\n+ ignore_mask = [Linter.parse_noqa(**c) for c in noqa]\n+ lf = linter.LintedFile(\n+ path=\"\",\n+ violations=violations,\n+ time_dict={},\n+ tree=None,\n+ ignore_mask=ignore_mask,\n+ templated_file=linter.TemplatedFile(\"\"),\n+ )\n+ result = lf._ignore_masked_violations(violations)\n+ expected_violations = [v for i, v in enumerate(violations) if i in expected]\n+ assert expected_violations == result\n+\n+\n+def test_linter_noqa():\n+ \"\"\"Test \"noqa\" feature at the higher \"Linter\" level.\"\"\"\n+ lntr = Linter(\n+ config=FluffConfig(\n+ overrides={\n+ \"rules\": \"L012\",\n+ }\n+ )\n+ )\n+ sql = \"\"\"\n+ SELECT\n+ col_a a,\n+ col_b b, --noqa: disable=L012\n+ col_c c,\n+ col_d d, --noqa: enable=L012\n+ col_e e,\n+ col_f f,\n+ col_g g, --noqa\n+ col_h h,\n+ col_i i, --noqa:L012\n+ col_j j,\n+ col_k k, --noqa:L013\n+ col_l l,\n+ col_m m,\n+ col_n n, --noqa: disable=all\n+ col_o o,\n+ col_p p --noqa: enable=all\n+ FROM foo\n+ \"\"\"\n+ result = lntr.lint_string(sql)\n+ violations = result.get_violations()\n+ assert {3, 6, 7, 8, 10, 12, 13, 14, 15, 18} == {v.line_no() for v in violations}\n", "problem_statement": "Add \"enable\" and \"disable\" syntax to noqa to allow rules disabling across multiple lines\nSee the `pylint` docs for an example: https://docs.pylint.org/en/1.6.0/faq.html#is-it-possible-to-locally-disable-a-particular-message\n", "hints_text": "", "created_at": "2021-03-25T12:55:23Z", "version": "0.4", "FAIL_TO_PASS": ["test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linter_noqa"], "PASS_TO_PASS": [], "environment_setup_commit": "cbdcfb09feb4883de91de142956c3be6ac7f827d"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-2573", "base_commit": "8822bf4d831ccbf6bc63a44b34978daf6939d996", "patch": "diff --git a/src/sqlfluff/core/config.py b/src/sqlfluff/core/config.py\n--- a/src/sqlfluff/core/config.py\n+++ b/src/sqlfluff/core/config.py\n@@ -395,7 +395,7 @@ def load_config_up_to_path(\n \n @classmethod\n def find_ignore_config_files(\n- cls, path, working_path=os.getcwd(), ignore_file_name=\".sqlfluffignore\"\n+ cls, path, working_path=Path.cwd(), ignore_file_name=\".sqlfluffignore\"\n ):\n \"\"\"Finds sqlfluff ignore files from both the path and its parent paths.\"\"\"\n return set(\n@@ -417,8 +417,8 @@ def iter_config_locations_up_to_path(path, working_path=Path.cwd()):\n The lowest priority is the user appdir, then home dir, then increasingly\n the configs closest to the file being directly linted.\n \"\"\"\n- given_path = Path(path).resolve()\n- working_path = Path(working_path).resolve()\n+ given_path = Path(path).absolute()\n+ working_path = Path(working_path).absolute()\n \n # If we've been passed a file and not a directory,\n # then go straight to the directory.\ndiff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -843,6 +843,7 @@ def paths_from_path(\n # matched, but we warn the users when that happens\n is_exact_file = os.path.isfile(path)\n \n+ path_walk: WalkableType\n if is_exact_file:\n # When the exact file to lint is passed, we\n # fill path_walk with an input that follows\n@@ -850,24 +851,26 @@ def paths_from_path(\n # (root, directories, files)\n dirpath = os.path.dirname(path)\n files = [os.path.basename(path)]\n- ignore_file_paths = ConfigLoader.find_ignore_config_files(\n- path=path, working_path=working_path, ignore_file_name=ignore_file_name\n- )\n- # Add paths that could contain \"ignore files\"\n- # to the path_walk list\n- path_walk_ignore_file = [\n- (\n- os.path.dirname(ignore_file_path),\n- None,\n- # Only one possible file, since we only\n- # have one \"ignore file name\"\n- [os.path.basename(ignore_file_path)],\n- )\n- for ignore_file_path in ignore_file_paths\n- ]\n- path_walk: WalkableType = [(dirpath, None, files)] + path_walk_ignore_file\n+ path_walk = [(dirpath, None, files)]\n else:\n- path_walk = os.walk(path)\n+ path_walk = list(os.walk(path))\n+\n+ ignore_file_paths = ConfigLoader.find_ignore_config_files(\n+ path=path, working_path=working_path, ignore_file_name=ignore_file_name\n+ )\n+ # Add paths that could contain \"ignore files\"\n+ # to the path_walk list\n+ path_walk_ignore_file = [\n+ (\n+ os.path.dirname(ignore_file_path),\n+ None,\n+ # Only one possible file, since we only\n+ # have one \"ignore file name\"\n+ [os.path.basename(ignore_file_path)],\n+ )\n+ for ignore_file_path in ignore_file_paths\n+ ]\n+ path_walk += path_walk_ignore_file\n \n # If it's a directory then expand the path!\n buffer = []\n", "test_patch": "diff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -1,10 +1,12 @@\n \"\"\"The Test file for the linter class.\"\"\"\n \n-import pytest\n+import os\n import logging\n from typing import List\n from unittest.mock import patch\n \n+import pytest\n+\n from sqlfluff.core import Linter, FluffConfig\n from sqlfluff.core.linter import runner\n from sqlfluff.core.errors import SQLLexError, SQLBaseError, SQLLintError, SQLParseError\n@@ -91,6 +93,23 @@ def test__linter__path_from_paths__explicit_ignore():\n assert len(paths) == 0\n \n \n+def test__linter__path_from_paths__sqlfluffignore_current_directory():\n+ \"\"\"Test that .sqlfluffignore in the current directory is read when dir given.\"\"\"\n+ oldcwd = os.getcwd()\n+ try:\n+ os.chdir(\"test/fixtures/linter/sqlfluffignore\")\n+ lntr = Linter()\n+ paths = lntr.paths_from_path(\n+ \"path_a/\",\n+ ignore_non_existent_files=True,\n+ ignore_files=True,\n+ working_path=\"test/fixtures/linter/sqlfluffignore/\",\n+ )\n+ assert len(paths) == 0\n+ finally:\n+ os.chdir(oldcwd)\n+\n+\n def test__linter__path_from_paths__dot():\n \"\"\"Test extracting paths from a dot.\"\"\"\n lntr = Linter()\n", "problem_statement": "Configuration from current working path not being loaded when path provided.\nI have the following directory structure.\r\n```\r\n~/GitHub/sqlfluff-bug\r\n\u279c tree -a\r\n.\r\n\u251c\u2500\u2500 .sqlfluffignore\r\n\u251c\u2500\u2500 ignore_me_1.sql\r\n\u251c\u2500\u2500 path_a\r\n\u2502\u00a0\u00a0 \u2514\u2500\u2500 ignore_me_2.sql\r\n\u2514\u2500\u2500 path_b\r\n \u251c\u2500\u2500 ignore_me_3.sql\r\n \u2514\u2500\u2500 lint_me_1.sql\r\n\r\n2 directories, 5 files\r\n```\r\nAnd the following ignore file\r\n\r\n```\r\n~/GitHub/sqlfluff-bug\r\n\u279c cat .sqlfluffignore\r\n\r\n~/GitHub/sqlfluff-bug\r\n\u279c cat .sqlfluffignore\r\nignore_me_1.sql\r\npath_a/\r\npath_b/ignore_me_3.sql%\r\n```\r\n\r\nWhen I run the following I get the expected result. Sqlfluff only lints the one file that is not ignored.\r\n```\r\n~/GitHub/sqlfluff-bug\r\n\u279c sqlfluff lint .\r\n\r\n~/GitHub/sqlfluff-bug\r\n\u279c sqlfluff lint .\r\n== [path_b/lint_me_1.sql] FAIL\r\nL: 2 | P: 1 | L003 | Indent expected and not found compared to line #1\r\nL: 2 | P: 10 | L010 | Inconsistent capitalisation of keywords.\r\n```\r\n\r\nHowever when I run the lint explicitly on one of the two directories then ignored files are also linted.\r\n\r\n```\r\n~/GitHub/sqlfluff-bug\r\n\u279c sqlfluff lint path_a\r\n\r\n~/GitHub/sqlfluff-bug\r\n\u279c sqlfluff lint path_a\r\n== [path_a/ignore_me_2.sql] FAIL\r\nL: 2 | P: 1 | L003 | Indent expected and not found compared to line #1\r\nL: 2 | P: 10 | L010 | Inconsistent capitalisation of keywords.\r\n\r\n~/GitHub/sqlfluff-bug\r\n\u279c sqlfluff lint path_b\r\n\r\n~/GitHub/sqlfluff-bug\r\n\u279c sqlfluff lint path_b\r\n== [path_b/ignore_me_3.sql] FAIL\r\nL: 2 | P: 1 | L003 | Indent expected and not found compared to line #1\r\nL: 2 | P: 10 | L010 | Inconsistent capitalisation of keywords.\r\n== [path_b/lint_me_1.sql] FAIL\r\nL: 2 | P: 1 | L003 | Indent expected and not found compared to line #1\r\nL: 2 | P: 10 | L010 | Inconsistent capitalisation of keywords.\r\n```\r\n\r\nIf this is the expected behaviour then it might be worthwhile to add an example to the [docs](https://docs.sqlfluff.com/en/latest/configuration.html#sqlfluffignore).\r\n\r\nEdit: I've replicated this issue on sqlfluff version 0.3.2 to 0.3.6.\n", "hints_text": "This is currently functioning as expected in that it only looks for `.sqlfluffignore` files within the directories you specify. So if you point sqlfluff at `/path_b`, it would only looks for a `.sqlfluffignore` file at `/path_b/.sqlfluffignore` and any child directories of that. It won't check in parents of the given file.\r\n\r\nI think that's the expected behavior consistent with `.dockerignore` and `.gitignore` .\r\n\r\nI agree about clarifying the documentation, which uses the phrase `placed in the root of your project` which I think alone is misleading.\nI think the behavior described in this issue is desirable.\r\n\r\nFor CI with pre-commit for example, right now I would need to add a `.sqlfluffignore` to each sub-directory containing sql files I want to ignore. That's because pre-commit will give the full path pointing to each file that changed before commit.\r\n\r\nI'm not sure the behavior is consistent with `.gitignore` because the \"project root\" stays the same and `.gitignore` files are applied from top level down to the subdirectory of each file, while in `sqlfluff` we don't really have a project root, which I think could come from a new configuration in `.sqlfluff` (or we could assume `cwd` if it's parent directory of the file we're trying to lint).\nI've just hit this issue myself (but for configuration file) and I agree with @dmateusp on this one.\r\n\r\nI think this is more than a documentation issue.\r\n\r\nFrom putting together the initial configuration code, the config loader, *should* check the current working directory for config loading, but it feels like that isn't working right now.", "created_at": "2022-02-07T17:47:05Z", "version": "0.9", "FAIL_TO_PASS": ["test/core/linter_test.py::test__linter__path_from_paths__sqlfluffignore_current_directory"], "PASS_TO_PASS": ["test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_parse_noqa[Inline", "test/core/linter_test.py::test_parse_noqa_no_dups", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[2_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_glob_ignore]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_linter_noqa_template_errors", "test/core/linter_test.py::test_linter_noqa_prs", "test/core/linter_test.py::test_linter_noqa_tmp", "test/core/linter_test.py::test_linter_noqa_disable", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]", "test/core/linter_test.py::test_advanced_api_methods", "test/core/linter_test.py::test_normalise_newlines"], "environment_setup_commit": "a4dcf3f08d95cbde4efb39969b0ab8e33a791f21"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3109", "base_commit": "38c31c99f6be6c2ffcc9e4132387edb7af8c5d06", "patch": "diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py\n--- a/src/sqlfluff/cli/commands.py\n+++ b/src/sqlfluff/cli/commands.py\n@@ -1,6 +1,7 @@\n \"\"\"Contains the CLI.\"\"\"\n \n from itertools import chain\n+import os\n import sys\n import json\n import logging\n@@ -29,9 +30,10 @@\n colorize,\n format_dialect_warning,\n format_dialects,\n- CallbackFormatter,\n+ OutputStreamFormatter,\n )\n from sqlfluff.cli.helpers import cli_table, get_package_version\n+from sqlfluff.cli.outputstream import make_output_stream, OutputStream\n \n # Import from sqlfluff core.\n from sqlfluff.core import (\n@@ -332,28 +334,9 @@ def get_config(\n sys.exit(66)\n \n \n-def _callback_handler(cfg: FluffConfig) -> Callable:\n- \"\"\"Returns function which will be bound as a callback for printing passed message.\n-\n- Called in `get_linter_and_formatter`.\n- \"\"\"\n-\n- def _echo_with_tqdm_lock(message: str) -> None:\n- \"\"\"Makes sure that message printing (echoing) will be not in conflict with tqdm.\n-\n- It may happen that progressbar conflicts with extra printing. Nothing very\n- serious happens then, except that there is printed (not removed) progressbar\n- line. The `external_write_mode` allows to disable tqdm for writing time.\n- \"\"\"\n- with tqdm.external_write_mode():\n- click.echo(message=message, color=cfg.get(\"color\"))\n-\n- return _echo_with_tqdm_lock\n-\n-\n def get_linter_and_formatter(\n- cfg: FluffConfig, silent: bool = False\n-) -> Tuple[Linter, CallbackFormatter]:\n+ cfg: FluffConfig, output_stream: Optional[OutputStream] = None\n+) -> Tuple[Linter, OutputStreamFormatter]:\n \"\"\"Get a linter object given a config.\"\"\"\n try:\n # We're just making sure it exists at this stage.\n@@ -364,20 +347,12 @@ def get_linter_and_formatter(\n except KeyError: # pragma: no cover\n click.echo(f\"Error: Unknown dialect '{cfg.get('dialect')}'\")\n sys.exit(66)\n-\n- if not silent:\n- # Instantiate the linter and return it (with an output function)\n- formatter = CallbackFormatter(\n- callback=_callback_handler(cfg=cfg),\n- verbosity=cfg.get(\"verbose\"),\n- output_line_length=cfg.get(\"output_line_length\"),\n- )\n- return Linter(config=cfg, formatter=formatter), formatter\n- else:\n- # Instantiate the linter and return. NB: No formatter\n- # in the Linter and a black formatter otherwise.\n- formatter = CallbackFormatter(callback=lambda m: None, verbosity=0)\n- return Linter(config=cfg), formatter\n+ formatter = OutputStreamFormatter(\n+ output_stream=output_stream or make_output_stream(cfg),\n+ verbosity=cfg.get(\"verbose\"),\n+ output_line_length=cfg.get(\"output_line_length\"),\n+ )\n+ return Linter(config=cfg, formatter=formatter), formatter\n \n \n @click.group(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@@ -521,7 +496,8 @@ def lint(\n )\n non_human_output = (format != FormatType.human.value) or (write_output is not None)\n file_output = None\n- lnt, formatter = get_linter_and_formatter(config, silent=non_human_output)\n+ output_stream = make_output_stream(config, format, write_output)\n+ lnt, formatter = get_linter_and_formatter(config, output_stream)\n \n verbose = config.get(\"verbose\")\n progress_bar_configuration.disable_progress_bar = disable_progress_bar\n@@ -610,6 +586,7 @@ def lint(\n if file_output:\n dump_file_payload(write_output, cast(str, file_output))\n \n+ output_stream.close()\n if bench:\n click.echo(\"==== overall timings ====\")\n click.echo(cli_table([(\"Clock time\", result.total_time)]))\n@@ -733,7 +710,10 @@ def fix(\n extra_config_path, ignore_local_config, require_dialect=False, **kwargs\n )\n fix_even_unparsable = config.get(\"fix_even_unparsable\")\n- lnt, formatter = get_linter_and_formatter(config, silent=fixing_stdin)\n+ output_stream = make_output_stream(\n+ config, None, os.devnull if fixing_stdin else None\n+ )\n+ lnt, formatter = get_linter_and_formatter(config, output_stream)\n \n verbose = config.get(\"verbose\")\n progress_bar_configuration.disable_progress_bar = disable_progress_bar\n@@ -974,7 +954,8 @@ def parse(\n # We don't want anything else to be logged if we want json or yaml output\n # unless we're writing to a file.\n non_human_output = (format != FormatType.human.value) or (write_output is not None)\n- lnt, formatter = get_linter_and_formatter(c, silent=non_human_output)\n+ output_stream = make_output_stream(c, format, write_output)\n+ lnt, formatter = get_linter_and_formatter(c, output_stream)\n verbose = c.get(\"verbose\")\n recurse = c.get(\"recurse\")\n \n@@ -1020,7 +1001,7 @@ def parse(\n # iterative print for human readout\n if format == FormatType.human.value:\n violations_count = _print_out_violations_and_timing(\n- bench, code_only, total_time, verbose, parsed_strings\n+ output_stream, bench, code_only, total_time, verbose, parsed_strings\n )\n else:\n parsed_strings_dict = [\n@@ -1072,6 +1053,7 @@ def parse(\n \n \n def _print_out_violations_and_timing(\n+ output_stream: OutputStream,\n bench: bool,\n code_only: bool,\n total_time: float,\n@@ -1086,30 +1068,30 @@ def _print_out_violations_and_timing(\n timing.add(parsed_string.time_dict)\n \n if parsed_string.tree:\n- click.echo(parsed_string.tree.stringify(code_only=code_only))\n+ output_stream.write(parsed_string.tree.stringify(code_only=code_only))\n else:\n # TODO: Make this prettier\n- click.echo(\"...Failed to Parse...\") # pragma: no cover\n+ output_stream.write(\"...Failed to Parse...\") # pragma: no cover\n \n violations_count += len(parsed_string.violations)\n if parsed_string.violations:\n- click.echo(\"==== parsing violations ====\") # pragma: no cover\n+ output_stream.write(\"==== parsing violations ====\") # pragma: no cover\n for v in parsed_string.violations:\n- click.echo(format_violation(v)) # pragma: no cover\n+ output_stream.write(format_violation(v)) # pragma: no cover\n if parsed_string.violations and parsed_string.config.get(\"dialect\") == \"ansi\":\n- click.echo(format_dialect_warning()) # pragma: no cover\n+ output_stream.write(format_dialect_warning()) # pragma: no cover\n \n if verbose >= 2:\n- click.echo(\"==== timings ====\")\n- click.echo(cli_table(parsed_string.time_dict.items()))\n+ output_stream.write(\"==== timings ====\")\n+ output_stream.write(cli_table(parsed_string.time_dict.items()))\n \n if verbose >= 2 or bench:\n- click.echo(\"==== overall timings ====\")\n- click.echo(cli_table([(\"Clock time\", total_time)]))\n+ output_stream.write(\"==== overall timings ====\")\n+ output_stream.write(cli_table([(\"Clock time\", total_time)]))\n timing_summary = timing.summary()\n for step in timing_summary:\n- click.echo(f\"=== {step} ===\")\n- click.echo(cli_table(timing_summary[step].items()))\n+ output_stream.write(f\"=== {step} ===\")\n+ output_stream.write(cli_table(timing_summary[step].items()))\n \n return violations_count\n \ndiff --git a/src/sqlfluff/cli/formatters.py b/src/sqlfluff/cli/formatters.py\n--- a/src/sqlfluff/cli/formatters.py\n+++ b/src/sqlfluff/cli/formatters.py\n@@ -2,7 +2,7 @@\n \n \n from io import StringIO\n-from typing import Callable, List, Union\n+from typing import List, Union\n \n from sqlfluff.cli.helpers import (\n colorize,\n@@ -12,6 +12,7 @@\n get_python_implementation,\n pad_line,\n )\n+from sqlfluff.cli.outputstream import OutputStream\n from sqlfluff.core import SQLBaseError, FluffConfig, Linter\n from sqlfluff.core.enums import Color\n from sqlfluff.core.linter import LintedFile\n@@ -199,8 +200,8 @@ def format_dialect_warning(): # pragma: no cover\n )\n \n \n-class CallbackFormatter:\n- \"\"\"Formatter which uses a callback to output information.\n+class OutputStreamFormatter:\n+ \"\"\"Formatter which writes to an OutputStream.\n \n On instantiation, this formatter accepts a function to\n dispatch messages. Each public method accepts an object\n@@ -212,23 +213,20 @@ class CallbackFormatter:\n \n \n Args:\n- callback (:obj:`callable`): A callable which can be\n- be called with a string to be output.\n- verbosity (:obj:`int`): An integer specifying how\n- verbose the output should be.\n- filter_empty (:obj:`bool`): If True, empty messages\n- will not be dispatched.\n-\n+ output_stream: Output is sent here\n+ verbosity: Specifies how verbose output should be\n+ filter_empty: If True, empty messages will not be dispatched\n+ output_line_length: Maximum line length\n \"\"\"\n \n def __init__(\n self,\n- callback: Callable,\n+ output_stream: OutputStream,\n verbosity: int = 0,\n filter_empty: bool = True,\n output_line_length: int = 80,\n ):\n- self._callback = callback\n+ self._output_stream = output_stream\n self._verbosity = verbosity\n self._filter_empty = filter_empty\n self.output_line_length = output_line_length\n@@ -240,7 +238,7 @@ def _dispatch(self, s: str) -> None:\n \"\"\"\n # The strip here is to filter out any empty messages\n if (not self._filter_empty) or s.strip(\" \\n\\t\"):\n- self._callback(s)\n+ self._output_stream.write(s)\n \n def _format_config(self, linter: Linter) -> str:\n \"\"\"Format the config of a `Linter`.\"\"\"\ndiff --git a/src/sqlfluff/cli/outputstream.py b/src/sqlfluff/cli/outputstream.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/sqlfluff/cli/outputstream.py\n@@ -0,0 +1,76 @@\n+\"\"\"Classes for managing linter output, used with OutputStreamFormatter.\"\"\"\n+import abc\n+import os\n+from typing import Any, Optional\n+\n+import click\n+from tqdm import tqdm\n+\n+from sqlfluff.core import FluffConfig\n+from sqlfluff.core.enums import FormatType\n+\n+\n+class OutputStream(abc.ABC):\n+ \"\"\"Base class for linter output stream.\"\"\"\n+\n+ def __init__(self, config: FluffConfig, context: Any = None):\n+ self.config = config\n+\n+ def write(self, message: str) -> None:\n+ \"\"\"Write message to output.\"\"\"\n+ raise NotImplementedError # pragma: no cover\n+\n+ def close(self):\n+ \"\"\"Close output stream.\"\"\"\n+ pass\n+\n+\n+class TqdmOutput(OutputStream):\n+ \"\"\"Outputs to stdout, coordinates to avoid conflict with tqdm.\n+\n+ It may happen that progressbar conflicts with extra printing. Nothing very\n+ serious happens then, except that there is printed (not removed) progressbar\n+ line. The `external_write_mode` allows to disable tqdm for writing time.\n+ \"\"\"\n+\n+ def __init__(self, config: FluffConfig):\n+ super().__init__(config)\n+\n+ def write(self, message: str) -> None:\n+ \"\"\"Write message to stdout.\"\"\"\n+ with tqdm.external_write_mode():\n+ click.echo(message=message, color=self.config.get(\"color\"))\n+\n+\n+class FileOutput(OutputStream):\n+ \"\"\"Outputs to a specified file.\"\"\"\n+\n+ def __init__(self, config: FluffConfig, output_path: str):\n+ super().__init__(config)\n+ self.file = open(output_path, \"w\")\n+\n+ def write(self, message: str) -> None:\n+ \"\"\"Write message to output_path.\"\"\"\n+ print(message, file=self.file)\n+\n+ def close(self):\n+ \"\"\"Close output file.\"\"\"\n+ self.file.close()\n+\n+\n+def make_output_stream(\n+ config: FluffConfig,\n+ format: Optional[str] = None,\n+ output_path: Optional[str] = None,\n+) -> OutputStream:\n+ \"\"\"Create and return appropriate OutputStream instance.\"\"\"\n+ if format is None or format == FormatType.human.value:\n+ if not output_path:\n+ # Human-format output to stdout.\n+ return TqdmOutput(config)\n+ else:\n+ # Human-format output to a file.\n+ return FileOutput(config, output_path)\n+ else:\n+ # Discard human output as not required\n+ return FileOutput(config, os.devnull)\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -968,11 +968,12 @@ def test__cli__command_fail_nice_not_found(command):\n \n \n @pytest.mark.parametrize(\n- \"serialize\", [\"yaml\", \"json\", \"github-annotation\", \"github-annotation-native\"]\n+ \"serialize\",\n+ [\"human\", \"yaml\", \"json\", \"github-annotation\", \"github-annotation-native\"],\n )\n @pytest.mark.parametrize(\"write_file\", [None, \"outfile\"])\n def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_path):\n- \"\"\"Check the general format of JSON output for multiple files.\n+ \"\"\"Test the output output formats for multiple files.\n \n This tests runs both stdout checking and file checking.\n \"\"\"\n@@ -987,9 +988,11 @@ def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_\n )\n \n if write_file:\n- target_file = os.path.join(\n- tmp_path, write_file + (\".yaml\" if serialize == \"yaml\" else \".json\")\n- )\n+ ext = {\n+ \"human\": \".txt\",\n+ \"yaml\": \".yaml\",\n+ }\n+ target_file = os.path.join(tmp_path, write_file + ext.get(serialize, \".json\"))\n cmd_args += (\"--write-output\", target_file)\n \n # note the file is in here twice. two files = two payloads.\n@@ -1004,7 +1007,9 @@ def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_\n else:\n result_payload = result.output\n \n- if serialize == \"json\":\n+ if serialize == \"human\":\n+ assert len(result_payload.split(\"\\n\")) == 29 if write_file else 30\n+ elif serialize == \"json\":\n result = json.loads(result_payload)\n assert len(result) == 2\n elif serialize == \"yaml\":\ndiff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -11,7 +11,8 @@\n from sqlfluff.core.dialects import load_raw_dialect\n from sqlfluff.core.linter import runner\n from sqlfluff.core.errors import SQLLexError, SQLBaseError, SQLLintError, SQLParseError\n-from sqlfluff.cli.formatters import CallbackFormatter\n+from sqlfluff.cli.formatters import OutputStreamFormatter\n+from sqlfluff.cli.outputstream import make_output_stream\n from sqlfluff.core.linter import LintingResult, NoQaDirective\n import sqlfluff.core.linter as linter\n from sqlfluff.core.parser import GreedyUntil, Ref\n@@ -256,8 +257,10 @@ def imap_unordered(self, *args, **kwargs):\n \n monkeypatch.setattr(runner.MultiProcessRunner, \"_create_pool\", _create_pool)\n \n+ config = FluffConfig(overrides={\"dialect\": \"ansi\"})\n+ output_stream = make_output_stream(config, None, os.devnull)\n lntr = Linter(\n- formatter=CallbackFormatter(callback=lambda m: None, verbosity=0),\n+ formatter=OutputStreamFormatter(output_stream, verbosity=0),\n dialect=\"ansi\",\n )\n result = lntr.lint_paths(\n", "problem_statement": "Write-output human format does not produce result\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nWhen running SQLFluff using the following statement:\r\n`python -m sqlfluff lint --write-output test.txt --config=config/sql-lint.cfg`\r\nno result was produced.\n\n### Expected Behaviour\n\nI expect a file to appear, in this case called test,txt, containing all violations found.\n\n### Observed Behaviour\n\nLooking through the code I saw human was the default format so expected adding --format=human would not make a difference. To be sure, I also ran the statement using the flag and it still produced nothing.\r\n\r\nTo make sure it was just the human format which was having problems, I also executed the statement using --format=json,yaml,github-annotations, all of which did produce the expected result which leads me to believe there is something wrong with the human format.\n\n### How to reproduce\n\nI imagine simply executing `sqlfluff lint --write-output test.txt example.sql`\n\n### Dialect\n\nT-SQL\n\n### Version\n\n0.11.2\n\n### Configuration\n\n[sqlfluff]\r\ndialect = tsql\r\nexclude_rules = L014,\r\n L016,\r\n L031,\r\n L035,\r\n L059\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "This line in cli.py seems largely to blame -- it somewhat conflates output _format_ with writing to a file or not.\r\n```\r\nnon_human_output = (format != FormatType.human.value) or (write_output is not None)\r\n```\r\n\r\nIt will require some care to fix this. Simply removing `or (write_output is not None)` didn't seem to fix it.\r\n\r\nAs a workaround until this is fixed, you may be able to use output redirection, e.g.\r\n```\r\npython -m sqlfluff lint --config=config/sql-lint.cfg > test.txt\r\n```\r\n\r\n\nYour workaround does work for me, thank you. Seeing as this solution is only a workaround I imagine closing the ticket is not preferable.", "created_at": "2022-04-17T20:42:13Z", "version": "0.12", "FAIL_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-65-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_pass_on_correct_encoding_argument", "test/cli/commands_test.py::test_cli_fail_on_wrong_encoding_argument", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__sqlfluffignore_current_directory", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_parse_noqa[Inline", "test/core/linter_test.py::test_parse_noqa_no_dups", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[2_violations_comment_inline_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violations_comment_inline_glob_ignore]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_linter_noqa_template_errors", "test/core/linter_test.py::test_linter_noqa_prs", "test/core/linter_test.py::test_linter_noqa_tmp", "test/core/linter_test.py::test_linter_noqa_disable", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]", "test/core/linter_test.py::test_advanced_api_methods", "test/core/linter_test.py::test_normalise_newlines", "test/core/linter_test.py::test_require_match_parse_grammar"], "PASS_TO_PASS": [], "environment_setup_commit": "8f6fd1d8a8d69b2c463fbcf5bd1131c47f12ad88"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-1763", "base_commit": "a10057635e5b2559293a676486f0b730981f037a", "patch": "diff --git a/src/sqlfluff/core/linter/linted_file.py b/src/sqlfluff/core/linter/linted_file.py\n--- a/src/sqlfluff/core/linter/linted_file.py\n+++ b/src/sqlfluff/core/linter/linted_file.py\n@@ -7,6 +7,8 @@\n \n import os\n import logging\n+import shutil\n+import tempfile\n from typing import (\n Any,\n Iterable,\n@@ -493,7 +495,24 @@ def persist_tree(self, suffix: str = \"\") -> bool:\n if suffix:\n root, ext = os.path.splitext(fname)\n fname = root + suffix + ext\n- # Actually write the file.\n- with open(fname, \"w\", encoding=self.encoding) as f:\n- f.write(write_buff)\n+ self._safe_create_replace_file(fname, write_buff, self.encoding)\n return success\n+\n+ @staticmethod\n+ def _safe_create_replace_file(fname, write_buff, encoding):\n+ # Write to a temporary file first, so in case of encoding or other\n+ # issues, we don't delete or corrupt the user's existing file.\n+ dirname, basename = os.path.split(fname)\n+ with tempfile.NamedTemporaryFile(\n+ mode=\"w\",\n+ encoding=encoding,\n+ prefix=basename,\n+ dir=dirname,\n+ suffix=os.path.splitext(fname)[1],\n+ delete=False,\n+ ) as tmp:\n+ tmp.file.write(write_buff)\n+ tmp.flush()\n+ os.fsync(tmp.fileno())\n+ # Once the temp file is safely written, replace the existing file.\n+ shutil.move(tmp.name, fname)\n", "test_patch": "diff --git a/test/core/linter_test.py b/test/core/linter_test.py\n--- a/test/core/linter_test.py\n+++ b/test/core/linter_test.py\n@@ -641,3 +641,56 @@ def test__attempt_to_change_templater_warning(caplog):\n assert \"Attempt to set templater to \" in caplog.text\n finally:\n logger.propagate = original_propagate_value\n+\n+\[email protected](\n+ \"case\",\n+ [\n+ dict(\n+ name=\"utf8_create\",\n+ fname=\"test.sql\",\n+ encoding=\"utf-8\",\n+ existing=None,\n+ update=\"def\",\n+ expected=\"def\",\n+ ),\n+ dict(\n+ name=\"utf8_update\",\n+ fname=\"test.sql\",\n+ encoding=\"utf-8\",\n+ existing=\"abc\",\n+ update=\"def\",\n+ expected=\"def\",\n+ ),\n+ dict(\n+ name=\"utf8_special_char\",\n+ fname=\"test.sql\",\n+ encoding=\"utf-8\",\n+ existing=\"abc\",\n+ update=\"\u2192\", # Special utf-8 character\n+ expected=\"\u2192\",\n+ ),\n+ dict(\n+ name=\"incorrect_encoding\",\n+ fname=\"test.sql\",\n+ encoding=\"Windows-1252\",\n+ existing=\"abc\",\n+ update=\"\u2192\", # Not valid in Windows-1252\n+ expected=\"abc\", # File should be unchanged\n+ ),\n+ ],\n+ ids=lambda case: case[\"name\"],\n+)\n+def test_safe_create_replace_file(case, tmp_path):\n+ \"\"\"Test creating or updating .sql files, various content and encoding.\"\"\"\n+ p = tmp_path / case[\"fname\"]\n+ if case[\"existing\"]:\n+ p.write_text(case[\"existing\"])\n+ try:\n+ linter.LintedFile._safe_create_replace_file(\n+ str(p), case[\"update\"], case[\"encoding\"]\n+ )\n+ except: # noqa: E722\n+ pass\n+ actual = p.read_text(encoding=case[\"encoding\"])\n+ assert case[\"expected\"] == actual\n", "problem_statement": "dbt postgres fix command errors with UnicodeEncodeError and also wipes the .sql file\n_If this is a parsing or linting issue, please include a minimal SQL example which reproduces the issue, along with the `sqlfluff parse` output, `sqlfluff lint` output and `sqlfluff fix` output when relevant._\r\n\r\n## Expected Behaviour\r\nViolation failure notice at a minimum, without wiping the file. Would like a way to ignore the known error at a minimum as --noqa is not getting past this. Actually would expect --noqa to totally ignore this.\r\n\r\n## Observed Behaviour\r\nReported error: `UnicodeEncodeError: 'charmap' codec can't encode character '\\u2192' in position 120: character maps to <undefined>`\r\n\r\n## Steps to Reproduce\r\nSQL file:\r\n```sql\r\nSELECT\r\n reacted_table_name_right.descendant_id AS category_id,\r\n string_agg(redacted_table_name_left.name, ' \u2192 ' ORDER BY reacted_table_name_right.generations DESC) AS breadcrumbs -- noqa\r\nFROM {{ ref2('redacted_schema_name', 'redacted_table_name_left') }} AS redacted_table_name_left\r\nINNER JOIN {{ ref2('redacted_schema_name', 'reacted_table_name_right') }} AS reacted_table_name_right\r\n ON redacted_table_name_left.id = order_issue_category_hierarchies.ancestor_id\r\nGROUP BY reacted_table_name_right.descendant_id\r\n```\r\nRunning `sqlfluff fix --ignore templating,parsing,lexing -vvvv` and accepting proposed fixes for linting violations.\r\n\r\n## Dialect\r\n`postgres`, with `dbt` templater\r\n\r\n## Version\r\n`python 3.7.12`\r\n`sqlfluff 0.7.0`\r\n`sqlfluff-templater-dbt 0.7.0`\r\n\r\n## Configuration\r\nI've tried a few, here's one:\r\n```\r\n[sqlfluff]\r\nverbose = 2\r\ndialect = postgres\r\ntemplater = dbt\r\nexclude_rules = None\r\noutput_line_length = 80\r\nrunaway_limit = 10\r\nignore_templated_areas = True\r\nprocesses = 3\r\n# Comma separated list of file extensions to lint.\r\n\r\n# NB: This config will only apply in the root folder.\r\nsql_file_exts = .sql\r\n\r\n[sqlfluff:indentation]\r\nindented_joins = False\r\nindented_using_on = True\r\ntemplate_blocks_indent = True\r\n\r\n[sqlfluff:templater]\r\nunwrap_wrapped_queries = True\r\n\r\n[sqlfluff:templater:jinja]\r\napply_dbt_builtins = True\r\n\r\n[sqlfluff:templater:jinja:macros]\r\n# Macros provided as builtins for dbt projects\r\ndbt_ref = {% macro ref(model_ref) %}{{model_ref}}{% endmacro %}\r\ndbt_source = {% macro source(source_name, table) %}{{source_name}}_{{table}}{% endmacro %}\r\ndbt_config = {% macro config() %}{% for k in kwargs %}{% endfor %}{% endmacro %}\r\ndbt_var = {% macro var(variable, default='') %}item{% endmacro %}\r\ndbt_is_incremental = {% macro is_incremental() %}True{% endmacro %}\r\n\r\n# Common config across rules\r\n[sqlfluff:rules]\r\ntab_space_size = 4\r\nindent_unit = space\r\nsingle_table_references = consistent\r\nunquoted_identifiers_policy = all\r\n\r\n# L001 - Remove trailing whitespace (fix)\r\n# L002 - Single section of whitespace should not contain both tabs and spaces (fix)\r\n# L003 - Keep consistent indentation (fix)\r\n# L004 - We use 4 spaces for indentation just for completeness (fix)\r\n# L005 - Remove space before commas (fix)\r\n# L006 - Operators (+, -, *, /) will be wrapped by a single space each side (fix)\r\n\r\n# L007 - Operators should not be at the end of a line\r\n[sqlfluff:rules:L007] # Keywords\r\noperator_new_lines = after\r\n\r\n# L008 - Always use a single whitespace after a comma (fix)\r\n# L009 - Files will always end with a trailing newline\r\n\r\n# L010 - All keywords will use full upper case (fix)\r\n[sqlfluff:rules:L010] # Keywords\r\ncapitalisation_policy = upper\r\n\r\n# L011 - Always explicitly alias tables (fix)\r\n[sqlfluff:rules:L011] # Aliasing\r\naliasing = explicit\r\n\r\n# L012 - Do not have to explicitly alias all columns\r\n[sqlfluff:rules:L012] # Aliasing\r\naliasing = explicit\r\n\r\n# L013 - Always explicitly alias a column with an expression in it (fix)\r\n[sqlfluff:rules:L013] # Aliasing\r\nallow_scalar = False\r\n\r\n# L014 - Always user full lower case for 'quoted identifiers' -> column refs. without an alias (fix)\r\n[sqlfluff:rules:L014] # Unquoted identifiers\r\nextended_capitalisation_policy = lower\r\n\r\n# L015 - Always remove parenthesis when using DISTINCT to be clear that DISTINCT applies to all columns (fix)\r\n\r\n# L016 - Lines should be 120 characters of less. Comment lines should not be ignored (fix)\r\n[sqlfluff:rules:L016]\r\nignore_comment_lines = False\r\nmax_line_length = 120\r\n\r\n# L017 - There should not be whitespace between function name and brackets (fix)\r\n# L018 - Always align closing bracket of WITH to the WITH keyword (fix)\r\n\r\n# L019 - Always use trailing commas / commas at the end of the line (fix)\r\n[sqlfluff:rules:L019]\r\ncomma_style = trailing\r\n\r\n# L020 - Table aliases will always be unique per statement\r\n# L021 - Remove any use of ambiguous DISTINCT and GROUP BY combinations. Lean on removing the GROUP BY.\r\n# L022 - Add blank lines after common table expressions (CTE) / WITH.\r\n# L023 - Always add a single whitespace after AS in a WITH clause (fix)\r\n\r\n[sqlfluff:rules:L026]\r\nforce_enable = False\r\n\r\n# L027 - Always add references if more than one referenced table or view is used\r\n\r\n[sqlfluff:rules:L028]\r\nforce_enable = False\r\n\r\n[sqlfluff:rules:L029] # Keyword identifiers\r\nunquoted_identifiers_policy = aliases\r\n\r\n[sqlfluff:rules:L030] # Function names\r\ncapitalisation_policy = upper\r\n\r\n# L032 - We prefer use of join keys rather than USING\r\n# L034 - We prefer ordering of columns in select statements as (fix):\r\n# 1. wildcards\r\n# 2. single identifiers\r\n# 3. calculations and aggregates\r\n\r\n# L035 - Omit 'else NULL'; it is redundant (fix)\r\n# L036 - Move select targets / identifiers onto new lines each (fix)\r\n# L037 - When using ORDER BY, make the direction explicit (fix)\r\n\r\n# L038 - Never use trailing commas at the end of the SELECT clause\r\n[sqlfluff:rules:L038]\r\nselect_clause_trailing_comma = forbid\r\n\r\n# L039 - Remove unnecessary whitespace (fix)\r\n\r\n[sqlfluff:rules:L040] # Null & Boolean Literals\r\ncapitalisation_policy = upper\r\n\r\n# L042 - Join clauses should not contain subqueries. Use common tables expressions (CTE) instead.\r\n[sqlfluff:rules:L042]\r\n# By default, allow subqueries in from clauses, but not join clauses.\r\nforbid_subquery_in = join\r\n\r\n# L043 - Reduce CASE WHEN conditions to COALESCE (fix)\r\n# L044 - Prefer a known number of columns along the path to the source data\r\n# L045 - Remove unused common tables expressions (CTE) / WITH statements (fix)\r\n# L046 - Jinja tags should have a single whitespace on both sides\r\n\r\n# L047 - Use COUNT(*) instead of COUNT(0) or COUNT(1) alternatives (fix)\r\n[sqlfluff:rules:L047] # Consistent syntax to count all rows\r\nprefer_count_1 = False\r\nprefer_count_0 = False\r\n\r\n# L048 - Quoted literals should be surrounded by a single whitespace (fix)\r\n# L049 - Always use IS or IS NOT for comparisons with NULL (fix)\r\n```\r\n\n", "hints_text": "I get a dbt-related error -- can you provide your project file as well? Also, what operating system are you running this on? I tested a simplified (non-dbt) version of your file on my Mac, and it worked okay.\r\n\r\n```\r\ndbt.exceptions.DbtProjectError: Runtime Error\r\n no dbt_project.yml found at expected path /Users/bhart/dev/sqlfluff/dbt_project.yml\r\n```\nNever mind the questions above -- I managed to reproduce the error in a sample dbt project. Taking a look now...\n@Tumble17: Have you tried setting the `encoding` parameter in `.sqlfluff`? Do you know what encoding you're using? The default is `autodetect`, and SQLFluff \"thinks\" the file uses \"Windows-1252\" encoding, which I assume is incorrect -- that's why SQLFluff is unable to write out the updated file.\nI added this line to the first section of your `.sqlfluff`, and now it seems to work. I'll look into changing the behavior of `sqlfluff fix` so it doesn't erase the file when it fails.\r\n\r\n```\r\nencoding = utf-8\r\n```", "created_at": "2021-10-26T17:28:28Z", "version": "0.6", "FAIL_TO_PASS": ["test/core/linter_test.py::test_safe_create_replace_file[utf8_create]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_update]", "test/core/linter_test.py::test_safe_create_replace_file[utf8_special_char]"], "PASS_TO_PASS": ["test/core/linter_test.py::test__linter__path_from_paths__dir", "test/core/linter_test.py::test__linter__path_from_paths__default", "test/core/linter_test.py::test__linter__path_from_paths__exts", "test/core/linter_test.py::test__linter__path_from_paths__file", "test/core/linter_test.py::test__linter__path_from_paths__not_exist", "test/core/linter_test.py::test__linter__path_from_paths__not_exist_ignore", "test/core/linter_test.py::test__linter__path_from_paths__explicit_ignore", "test/core/linter_test.py::test__linter__path_from_paths__dot", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/]", "test/core/linter_test.py::test__linter__path_from_paths__ignore[test/fixtures/linter/sqlfluffignore/.]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/indentation_errors.sql]", "test/core/linter_test.py::test__linter__lint_string_vs_file[test/fixtures/linter/whitespace_errors.sql]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[None-7]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[L010-2]", "test/core/linter_test.py::test__linter__get_violations_filter_rules[rules2-2]", "test/core/linter_test.py::test__linter__linting_result__sum_dicts", "test/core/linter_test.py::test__linter__linting_result__combine_dicts", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[False-list]", "test/core/linter_test.py::test__linter__linting_result_check_tuples_by_path[True-dict]", "test/core/linter_test.py::test__linter__linting_result_get_violations[1]", "test/core/linter_test.py::test__linter__linting_result_get_violations[2]", "test/core/linter_test.py::test__linter__linting_parallel_thread[False]", "test/core/linter_test.py::test__linter__linting_parallel_thread[True]", "test/core/linter_test.py::test_lint_path_parallel_wrapper_exception", "test/core/linter_test.py::test__linter__linting_unexpected_error_handled_gracefully", "test/core/linter_test.py::test__linter__raises_malformed_noqa", "test/core/linter_test.py::test__linter__empty_file", "test/core/linter_test.py::test__linter__mask_templated_violations[True-check_tuples0]", "test/core/linter_test.py::test__linter__mask_templated_violations[False-check_tuples1]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-autodetect-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-True]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8.sql-utf-8-sig-False]", "test/core/linter_test.py::test__linter__encoding[test/fixtures/linter/encoding-utf-8-sig.sql-utf-8-sig-False]", "test/core/linter_test.py::test_parse_noqa[-None]", "test/core/linter_test.py::test_parse_noqa[noqa-expected1]", "test/core/linter_test.py::test_parse_noqa[noqa?-SQLParseError]", "test/core/linter_test.py::test_parse_noqa[noqa:-expected3]", "test/core/linter_test.py::test_parse_noqa[noqa:L001,L002-expected4]", "test/core/linter_test.py::test_parse_noqa[noqa:", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_no_ignore]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_line]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_different_specific_rule]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_enable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_ignore_disable_this_range]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_specific_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_1_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_2_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_3_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[1_violation_line_4_ignore_disable_all_2_3]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_specific_enable_all]", "test/core/linter_test.py::test_linted_file_ignore_masked_violations[4_violations_two_types_disable_all_enable_specific]", "test/core/linter_test.py::test_linter_noqa", "test/core/linter_test.py::test_linter_noqa_with_templating", "test/core/linter_test.py::test_delayed_exception", "test/core/linter_test.py::test__attempt_to_change_templater_warning", "test/core/linter_test.py::test_safe_create_replace_file[incorrect_encoding]"], "environment_setup_commit": "67023b85c41d23d6c6d69812a41b207c4f8a9331"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-4084", "base_commit": "181918e9c2840dc3f5ff1c713bf6b5a00d0725b5", "patch": "diff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py\n--- a/src/sqlfluff/core/linter/linter.py\n+++ b/src/sqlfluff/core/linter/linter.py\n@@ -1103,17 +1103,39 @@ def lint_path(\n processes: Optional[int] = None,\n ) -> LintedDir:\n \"\"\"Lint a path.\"\"\"\n- linted_path = LintedDir(path)\n- if self.formatter:\n- self.formatter.dispatch_path(path)\n- fnames = list(\n- self.paths_from_path(\n+ return self.lint_paths(\n+ (path,), fix, ignore_non_existent_files, ignore_files, processes\n+ ).paths[0]\n+\n+ def lint_paths(\n+ self,\n+ paths: Tuple[str, ...],\n+ fix: bool = False,\n+ ignore_non_existent_files: bool = False,\n+ ignore_files: bool = True,\n+ processes: Optional[int] = None,\n+ ) -> LintingResult:\n+ \"\"\"Lint an iterable of paths.\"\"\"\n+ # If no paths specified - assume local\n+ if not paths: # pragma: no cover\n+ paths = (os.getcwd(),)\n+ # Set up the result to hold what we get back\n+ result = LintingResult()\n+\n+ expanded_paths: List[str] = []\n+ expanded_path_to_linted_dir = {}\n+ for path in paths:\n+ linted_dir = LintedDir(path)\n+ result.add(linted_dir)\n+ for fname in self.paths_from_path(\n path,\n ignore_non_existent_files=ignore_non_existent_files,\n ignore_files=ignore_files,\n- )\n- )\n+ ):\n+ expanded_paths.append(fname)\n+ expanded_path_to_linted_dir[fname] = linted_dir\n \n+ files_count = len(expanded_paths)\n if processes is None:\n processes = self.config.get(\"processes\", default=1)\n \n@@ -1131,72 +1153,29 @@ def lint_path(\n self.formatter.dispatch_processing_header(effective_processes)\n \n # Show files progress bar only when there is more than one.\n- files_count = len(fnames)\n+ first_path = expanded_paths[0] if expanded_paths else \"\"\n progress_bar_files = tqdm(\n total=files_count,\n- desc=f\"file {os.path.basename(fnames[0] if fnames else '')}\",\n+ desc=f\"file {first_path}\",\n leave=False,\n disable=files_count <= 1 or progress_bar_configuration.disable_progress_bar,\n )\n \n- for i, linted_file in enumerate(runner.run(fnames, fix), start=1):\n- linted_path.add(linted_file)\n+ for i, linted_file in enumerate(runner.run(expanded_paths, fix), start=1):\n+ linted_dir = expanded_path_to_linted_dir[linted_file.path]\n+ linted_dir.add(linted_file)\n # If any fatal errors, then stop iteration.\n if any(v.fatal for v in linted_file.violations): # pragma: no cover\n linter_logger.error(\"Fatal linting error. Halting further linting.\")\n break\n \n # Progress bar for files is rendered only when there is more than one file.\n- # Additionally as it's updated after each loop, we need to get file name\n+ # Additionally, as it's updated after each loop, we need to get file name\n # from the next loop. This is why `enumerate` starts with `1` and there\n # is `i < len` to not exceed files list length.\n progress_bar_files.update(n=1)\n- if i < len(fnames):\n- progress_bar_files.set_description(\n- f\"file {os.path.basename(fnames[i])}\"\n- )\n-\n- return linted_path\n-\n- def lint_paths(\n- self,\n- paths: Tuple[str, ...],\n- fix: bool = False,\n- ignore_non_existent_files: bool = False,\n- ignore_files: bool = True,\n- processes: Optional[int] = None,\n- ) -> LintingResult:\n- \"\"\"Lint an iterable of paths.\"\"\"\n- paths_count = len(paths)\n-\n- # If no paths specified - assume local\n- if not paths_count: # pragma: no cover\n- paths = (os.getcwd(),)\n- # Set up the result to hold what we get back\n- result = LintingResult()\n-\n- progress_bar_paths = tqdm(\n- total=paths_count,\n- desc=\"path\",\n- leave=False,\n- disable=paths_count <= 1 or progress_bar_configuration.disable_progress_bar,\n- )\n- for path in paths:\n- progress_bar_paths.set_description(f\"path {path}\")\n-\n- # Iterate through files recursively in the specified directory (if it's a\n- # directory) or read the file directly if it's not\n- result.add(\n- self.lint_path(\n- path,\n- fix=fix,\n- ignore_non_existent_files=ignore_non_existent_files,\n- ignore_files=ignore_files,\n- processes=processes,\n- )\n- )\n-\n- progress_bar_paths.update(1)\n+ if i < len(expanded_paths):\n+ progress_bar_files.set_description(f\"file {expanded_paths[i]}\")\n \n result.stop_timer()\n return result\n", "test_patch": "diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py\n--- a/test/cli/commands_test.py\n+++ b/test/cli/commands_test.py\n@@ -1272,15 +1272,16 @@ def test__cli__command_lint_nocolor(isatty, should_strip_ansi, capsys, tmpdir):\n )\n @pytest.mark.parametrize(\"write_file\", [None, \"outfile\"])\n def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_path):\n- \"\"\"Test the output output formats for multiple files.\n+ \"\"\"Test the output formats for multiple files.\n \n This tests runs both stdout checking and file checking.\n \"\"\"\n- fpath = \"test/fixtures/linter/indentation_errors.sql\"\n+ fpath1 = \"test/fixtures/linter/indentation_errors.sql\"\n+ fpath2 = \"test/fixtures/linter/multiple_sql_errors.sql\"\n \n cmd_args = (\n- fpath,\n- fpath,\n+ fpath1,\n+ fpath2,\n \"--format\",\n serialize,\n \"--disable-progress-bar\",\n@@ -1313,7 +1314,7 @@ def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_\n print(\"## End Payload\")\n \n if serialize == \"human\":\n- assert payload_length == 31 if write_file else 32\n+ assert payload_length == 26 if write_file else 32\n elif serialize == \"json\":\n result = json.loads(result_payload)\n assert len(result) == 2\n@@ -1323,13 +1324,13 @@ def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_\n elif serialize == \"github-annotation\":\n result = json.loads(result_payload)\n filepaths = {r[\"file\"] for r in result}\n- assert len(filepaths) == 1\n+ assert len(filepaths) == 2\n elif serialize == \"github-annotation-native\":\n result = result_payload.split(\"\\n\")\n # SQLFluff produces trailing newline\n if result[-1] == \"\":\n del result[-1]\n- assert len(result) == 24\n+ assert len(result) == 17\n else:\n raise Exception\n \n@@ -1721,8 +1722,16 @@ def test_cli_lint_enabled_progress_bar_multiple_paths(\n )\n raw_output = repr(result.output)\n \n- assert r\"\\rpath test/fixtures/linter/passing.sql:\" in raw_output\n- assert r\"\\rpath test/fixtures/linter/indentation_errors.sql:\" in raw_output\n+ sep = os.sep\n+ if sys.platform == \"win32\":\n+ sep *= 2\n+ assert (\n+ r\"\\rfile test/fixtures/linter/passing.sql:\".replace(\"/\", sep) in raw_output\n+ )\n+ assert (\n+ r\"\\rfile test/fixtures/linter/indentation_errors.sql:\".replace(\"/\", sep)\n+ in raw_output\n+ )\n assert r\"\\rlint by rules:\" in raw_output\n assert r\"\\rrule L001:\" in raw_output\n assert r\"\\rrule L049:\" in raw_output\n@@ -1741,9 +1750,27 @@ def test_cli_lint_enabled_progress_bar_multiple_files(\n )\n raw_output = repr(result.output)\n \n- assert r\"\\rfile passing.1.sql:\" in raw_output\n- assert r\"\\rfile passing.2.sql:\" in raw_output\n- assert r\"\\rfile passing.3.sql:\" in raw_output\n+ sep = os.sep\n+ if sys.platform == \"win32\":\n+ sep *= 2\n+ assert (\n+ r\"\\rfile test/fixtures/linter/multiple_files/passing.1.sql:\".replace(\n+ \"/\", sep\n+ )\n+ in raw_output\n+ )\n+ assert (\n+ r\"\\rfile test/fixtures/linter/multiple_files/passing.2.sql:\".replace(\n+ \"/\", sep\n+ )\n+ in raw_output\n+ )\n+ assert (\n+ r\"\\rfile test/fixtures/linter/multiple_files/passing.3.sql:\".replace(\n+ \"/\", sep\n+ )\n+ in raw_output\n+ )\n assert r\"\\rlint by rules:\" in raw_output\n assert r\"\\rrule L001:\" in raw_output\n assert r\"\\rrule L049:\" in raw_output\n", "problem_statement": "Multiple processes not used when list of explicit filenames is passed\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### What Happened\n\nWhen providing a long list of file names to `sqlfluff lint -p -1`, only a single CPU is used. This seems to stem from the fact that https://github.com/sqlfluff/sqlfluff/blob/a006378af8b670f9235653694dbcddd4c62d1ab9/src/sqlfluff/core/linter/linter.py#L1190 is iterating over the list of files. For each listed path there, it would run the found files in parallel. As we are inputting whole filenames here, a path equals a single file and thus `sqlfluff` would only process one file at a time.\r\n\r\nThe context here is the execution of `sqlfluff lint` inside a `pre-commit` hook.\n\n### Expected Behaviour\n\nAll CPU cores are used as `-p -1` is passed on the commandline.\n\n### Observed Behaviour\n\nOnly a single CPU core is used.\n\n### How to reproduce\n\nRun `sqlfluff lint -p -1` with a long list of files.\n\n### Dialect\n\nAffects all. \n\n### Version\n\n1.4.2\n\n### Configuration\n\nNone.\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "I have been wondering for some time why sqlfluff never manages to use 100% of CPU. Running it on my Code base takes about 90 minutes. Though never more than 30% of cpu is used\u2026 maybe this sis the reason\u2026\nYeah - this looks like an accurate diagnosis. Most of the testing for the multiprocessing feature was done on large projects of multiple files, but _where a single path was passed_ e.g. `sqlfluff lint .`.\r\n\r\nThis seems like a very sensible improvement for people using the commit hook.\r\n\r\n@barrywhart - you did a lot of the original multiprocessing work. Reckon you could take this one on?\nI'll take a look, sure!", "created_at": "2022-11-18T22:49:21Z", "version": "1.3", "FAIL_TO_PASS": ["test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files"], "PASS_TO_PASS": ["test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_render_stdin", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/cli/commands_test.py::test__cli__command_lint_parse[command25]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command4-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_lint_warning", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__render_fail", "test/cli/commands_test.py::test__cli__render_pass"], "environment_setup_commit": "dc59c2a5672aacedaf91f0e6129b467eefad331b"}, {"repo": "sqlfluff/sqlfluff", "instance_id": "sqlfluff__sqlfluff-3330", "base_commit": "c2b1ec442131a70ac5b1560396ce1bbe636e4864", "patch": "diff --git a/src/sqlfluff/rules/L065.py b/src/sqlfluff/rules/L065.py\nnew file mode 100644\n--- /dev/null\n+++ b/src/sqlfluff/rules/L065.py\n@@ -0,0 +1,156 @@\n+\"\"\"Implementation of Rule L065.\"\"\"\n+from typing import List, Optional, Iterable\n+\n+import sqlfluff.core.rules.functional.segment_predicates as sp\n+from sqlfluff.core.parser import BaseSegment, NewlineSegment\n+from sqlfluff.core.rules.base import BaseRule, LintFix, LintResult, RuleContext\n+from sqlfluff.core.rules.doc_decorators import document_fix_compatible, document_groups\n+\n+\n+@document_groups\n+@document_fix_compatible\n+class Rule_L065(BaseRule):\n+ \"\"\"Set operators should be surrounded by newlines.\n+\n+ **Anti-pattern**\n+\n+ In this example, `UNION ALL` is not on a line ifself.\n+\n+ .. code-block:: sql\n+\n+ SELECT 'a' AS col UNION ALL\n+ SELECT 'b' AS col\n+\n+ **Best practice**\n+\n+ .. code-block:: sql\n+\n+ SELECT 'a' AS col\n+ UNION ALL\n+ SELECT 'b' AS col\n+\n+ \"\"\"\n+\n+ groups = (\"all\",)\n+\n+ _target_elems = (\"set_operator\",)\n+\n+ def _eval(self, context: RuleContext) -> List[LintResult]:\n+ \"\"\"Set operators should be surrounded by newlines.\n+\n+ For any set operator we check if there is any NewLineSegment in the non-code\n+ segments preceeding or following it.\n+\n+ In particular, as part of this rule we allow multiple NewLineSegments.\n+ \"\"\"\n+ segment = context.functional.segment\n+\n+ expression = segment.children()\n+ set_operator_segments = segment.children(sp.is_type(*self._target_elems))\n+ results: List[LintResult] = []\n+\n+ # If len(set_operator) == 0 this will essentially not run\n+ for set_operator in set_operator_segments:\n+ preceeding_code = (\n+ expression.reversed().select(start_seg=set_operator).first(sp.is_code())\n+ )\n+ following_code = expression.select(start_seg=set_operator).first(\n+ sp.is_code()\n+ )\n+ res = {\n+ \"before\": expression.select(\n+ start_seg=preceeding_code.get(), stop_seg=set_operator\n+ ),\n+ \"after\": expression.select(\n+ start_seg=set_operator, stop_seg=following_code.get()\n+ ),\n+ }\n+\n+ newline_before_set_operator = res[\"before\"].first(sp.is_type(\"newline\"))\n+ newline_after_set_operator = res[\"after\"].first(sp.is_type(\"newline\"))\n+\n+ # If there is a whitespace directly preceeding/following the set operator we\n+ # are replacing it with a newline later.\n+ preceeding_whitespace = res[\"before\"].first(sp.is_type(\"whitespace\")).get()\n+ following_whitespace = res[\"after\"].first(sp.is_type(\"whitespace\")).get()\n+\n+ if newline_before_set_operator and newline_after_set_operator:\n+ continue\n+ elif not newline_before_set_operator and newline_after_set_operator:\n+ results.append(\n+ LintResult(\n+ anchor=set_operator,\n+ description=(\n+ \"Set operators should be surrounded by newlines. \"\n+ f\"Missing newline before set operator {set_operator.raw}.\"\n+ ),\n+ fixes=_generate_fixes(whitespace_segment=preceeding_whitespace),\n+ )\n+ )\n+ elif newline_before_set_operator and not newline_after_set_operator:\n+ results.append(\n+ LintResult(\n+ anchor=set_operator,\n+ description=(\n+ \"Set operators should be surrounded by newlines. \"\n+ f\"Missing newline after set operator {set_operator.raw}.\"\n+ ),\n+ fixes=_generate_fixes(whitespace_segment=following_whitespace),\n+ )\n+ )\n+ else:\n+ preceeding_whitespace_fixes = _generate_fixes(\n+ whitespace_segment=preceeding_whitespace\n+ )\n+ following_whitespace_fixes = _generate_fixes(\n+ whitespace_segment=following_whitespace\n+ )\n+\n+ # make mypy happy\n+ assert isinstance(preceeding_whitespace_fixes, Iterable)\n+ assert isinstance(following_whitespace_fixes, Iterable)\n+\n+ fixes = []\n+ fixes.extend(preceeding_whitespace_fixes)\n+ fixes.extend(following_whitespace_fixes)\n+\n+ results.append(\n+ LintResult(\n+ anchor=set_operator,\n+ description=(\n+ \"Set operators should be surrounded by newlines. \"\n+ \"Missing newline before and after set operator \"\n+ f\"{set_operator.raw}.\"\n+ ),\n+ fixes=fixes,\n+ )\n+ )\n+\n+ return results\n+\n+\n+def _generate_fixes(\n+ whitespace_segment: BaseSegment,\n+) -> Optional[List[LintFix]]:\n+\n+ if whitespace_segment:\n+ return [\n+ LintFix.replace(\n+ anchor_segment=whitespace_segment,\n+ # NB: Currently we are just inserting a Newline here. This alone will\n+ # produce not properly indented SQL. We rely on L003 to deal with\n+ # indentation later.\n+ # As a future improvement we could maybe add WhitespaceSegment( ... )\n+ # here directly.\n+ edit_segments=[NewlineSegment()],\n+ )\n+ ]\n+ else:\n+ # We should rarely reach here as set operators are always surrounded by either\n+ # WhitespaceSegment or NewlineSegment.\n+ # However, in exceptional cases the WhitespaceSegment might be enclosed in the\n+ # surrounding segment hierachy and not accessible by the rule logic.\n+ # At the time of writing this is true for `tsql` as covered in the test\n+ # `test_fail_autofix_in_tsql_disabled`. If we encounter such case, we skip\n+ # fixing.\n+ return []\n", "test_patch": "diff --git a/test/fixtures/rules/std_rule_cases/L065.yml b/test/fixtures/rules/std_rule_cases/L065.yml\nnew file mode 100644\n--- /dev/null\n+++ b/test/fixtures/rules/std_rule_cases/L065.yml\n@@ -0,0 +1,122 @@\n+rule: L065\n+\n+test_fail_simple_fix_union_all_before:\n+ fail_str: |\n+ SELECT 'a' UNION ALL\n+ SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ UNION ALL\n+ SELECT 'b'\n+\n+test_fail_simple_fix_union_all_after:\n+ fail_str: |\n+ SELECT 'a'\n+ UNION ALL SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ UNION ALL\n+ SELECT 'b'\n+\n+test_fail_simple_fix_union_all_before_and_after:\n+ fail_str: |\n+ SELECT 'a' UNION ALL SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ UNION ALL\n+ SELECT 'b'\n+\n+test_pass_multiple_newlines_are_allowed:\n+ pass_str: |\n+ SELECT 'a'\n+\n+\n+ UNION ALL\n+\n+\n+ SELECT 'b'\n+\n+# The autofix of L065 doesn't respect indentation of the surrounding query.\n+# Hence, the fix result of only L065 looks ugly. But L003 will fix the indentation\n+# in a second step.\n+# See the test blow.\n+test_fail_fix_works_in_subqueries:\n+ fail_str: |\n+ SELECT * FROM (\n+ SELECT 'g' UNION ALL\n+ SELECT 'h'\n+ UNION ALL SELECT 'j'\n+ )\n+ fix_str: |\n+ SELECT * FROM (\n+ SELECT 'g'\n+ UNION ALL\n+ SELECT 'h'\n+ UNION ALL\n+ SELECT 'j'\n+ )\n+\n+# Test autofix after L003 passes L065\n+test_pass_fix_works_in_subqueries_after_L003_fix:\n+ pass_str: |\n+ SELECT * FROM (\n+ SELECT 'g'\n+ UNION ALL\n+ SELECT 'h'\n+ UNION ALL\n+ SELECT 'j'\n+ )\n+\n+test_fail_simple_fix_union_before_and_after:\n+ fail_str: |\n+ SELECT 'a' UNION SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ UNION\n+ SELECT 'b'\n+\n+test_fail_simple_fix_intersect_before_and_after:\n+ fail_str: |\n+ SELECT 'a' INTERSECT SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ INTERSECT\n+ SELECT 'b'\n+\n+test_fail_simple_fix_except_before_and_after:\n+ fail_str: |\n+ SELECT 'a' EXCEPT SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ EXCEPT\n+ SELECT 'b'\n+\n+test_fail_simple_fix_minus_before_and_after:\n+ fail_str: |\n+ SELECT 'a' EXCEPT SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ EXCEPT\n+ SELECT 'b'\n+\n+test_fail_simple_fix_bigquery_intersect_distinct_before_and_after:\n+ fail_str: |\n+ SELECT 'a' INTERSECT DISTINCT SELECT 'b'\n+ fix_str: |\n+ SELECT 'a'\n+ INTERSECT DISTINCT\n+ SELECT 'b'\n+ configs:\n+ core:\n+ dialect: bigquery\n+\n+test_fail_autofix_in_tsql_disabled:\n+ fail_str: |\n+ SELECT supplyID, supplier\n+ FROM dbo.SUPPLY1\n+ UNION ALL\n+ SELECT supplyID, supplier\n+ FROM dbo.SUPPLY2\n+ configs:\n+ core:\n+ dialect: tsql\ndiff --git a/test/rules/std_L003_L065_combo_test.py b/test/rules/std_L003_L065_combo_test.py\nnew file mode 100644\n--- /dev/null\n+++ b/test/rules/std_L003_L065_combo_test.py\n@@ -0,0 +1,46 @@\n+\"\"\"Tests the combination of L003 and L065.\n+\n+L003: Indentation not consistent with previous lines\n+L065: Set operators should be surrounded by newlines\n+\n+Auto fix of L065 does not insert correct indentation but just Newlines. It relies on\n+L003 to sort out the indentation later. This is what is getting tested here.\n+\"\"\"\n+\n+import sqlfluff\n+\n+\n+def test__rules__std_L003_L065_union_all_in_subquery_lint():\n+ \"\"\"Verify a that L065 reports lint errors in subqueries.\"\"\"\n+ sql = (\n+ \"SELECT * FROM (\\n\"\n+ \" SELECT 'g' UNION ALL\\n\"\n+ \" SELECT 'h'\\n\"\n+ \" UNION ALL SELECT 'j'\\n\"\n+ \")\\n\"\n+ )\n+ result = sqlfluff.lint(sql)\n+\n+ assert \"L065\" in [r[\"code\"] for r in result]\n+\n+\n+def test__rules__std_L003_L065_union_all_in_subquery_fix():\n+ \"\"\"Verify combination of rules L003 and L065 produces a correct indentation.\"\"\"\n+ sql = (\n+ \"SELECT * FROM (\\n\"\n+ \" SELECT 'g' UNION ALL\\n\"\n+ \" SELECT 'h'\\n\"\n+ \" UNION ALL SELECT 'j'\\n\"\n+ \")\\n\"\n+ )\n+ fixed_sql = (\n+ \"SELECT * FROM (\\n\"\n+ \" SELECT 'g'\\n\"\n+ \" UNION ALL\\n\"\n+ \" SELECT 'h'\\n\"\n+ \" UNION ALL\\n\"\n+ \" SELECT 'j'\\n\"\n+ \")\\n\"\n+ )\n+ result = sqlfluff.fix(sql)\n+ assert result == fixed_sql\n", "problem_statement": "Rule suggestion: `UNION [ALL|DISTINCT]` on new line\n### Search before asking\n\n- [X] I searched the [issues](https://github.com/sqlfluff/sqlfluff/issues) and found no similar issues.\n\n\n### Description\n\nI would like to suggest a new rule that puts `UNION [ALL|DISTINCT]` statements on their own line, aligned to the surrounding `SELECT` statements.\r\n\r\nFor example, currently \r\n\r\n```sql\r\nSELECT 1 UNION ALL\r\nSELECT 2\r\n```\r\n\r\npasses without errors. This new rule could fix that to\r\n\r\n```sql\r\nSELECT 1 \r\nUNION ALL\r\nSELECT 2\r\n```\r\n\r\nOr in a more complex example\r\n\r\n```sql\r\nSELECT * FROM (\r\n SELECT 1 UNION ALL\r\n SELECT 2\r\n)\r\n```\r\n\r\nfixed to\r\n\r\n```sql\r\nSELECT * FROM (\r\n SELECT 1 \r\n UNION ALL\r\n SELECT 2\r\n)\r\n```\n\n### Use case\n\nI have looked at a few SQL style guides and they don't really seem to mention any policy regarding `UNION` statements. However, in 99% of the SQL I have encountered `UNION` statements always seemed to be on a new line. It would be great to have an option to lint the remaining 1% \ud83d\ude09 \n\n### Dialect\n\nansi\n\n### Are you willing to work on and submit a PR to address the issue?\n\n- [ ] Yes I am willing to submit a PR!\n\n### Code of Conduct\n\n- [X] I agree to follow this project's [Code of Conduct](https://github.com/sqlfluff/sqlfluff/blob/main/CODE_OF_CONDUCT.md)\n\n", "hints_text": "", "created_at": "2022-05-12T05:50:48Z", "version": "0.12", "FAIL_TO_PASS": ["test/rules/std_L003_L065_combo_test.py::test__rules__std_L003_L065_union_all_in_subquery_lint", "test/rules/std_L003_L065_combo_test.py::test__rules__std_L003_L065_union_all_in_subquery_fix"], "PASS_TO_PASS": [], "environment_setup_commit": "8f6fd1d8a8d69b2c463fbcf5bd1131c47f12ad88"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1164", "base_commit": "1e26d14facab213df5009300b997481aa43df80a", "patch": "diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\n--- a/src/marshmallow/fields.py\n+++ b/src/marshmallow/fields.py\n@@ -443,6 +443,8 @@ def _serialize(self, nested_obj, attr, obj):\n schema = self.schema\n if nested_obj is None:\n return None\n+ if self.many and utils.is_iterable_but_not_string(nested_obj):\n+ nested_obj = list(nested_obj)\n if not self.__updated_fields:\n schema._update_fields(obj=nested_obj, many=self.many)\n self.__updated_fields = True\ndiff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py\n--- a/src/marshmallow/schema.py\n+++ b/src/marshmallow/schema.py\n@@ -816,23 +816,14 @@ def __filter_fields(self, field_names, obj, many=False):\n \n :param set field_names: Field names to include in the final\n return dictionary.\n+ :param object|Mapping|list obj The object to base filtered fields on.\n :returns: An dict of field_name:field_obj pairs.\n \"\"\"\n if obj and many:\n- try: # Homogeneous collection\n- # Prefer getitem over iter to prevent breaking serialization\n- # of objects for which iter will modify position in the collection\n- # e.g. Pymongo cursors\n- if hasattr(obj, '__getitem__') and callable(getattr(obj, '__getitem__')):\n- try:\n- obj_prototype = obj[0]\n- except KeyError:\n- obj_prototype = next(iter(obj))\n- else:\n- obj_prototype = next(iter(obj))\n- except (StopIteration, IndexError): # Nothing to serialize\n+ try: # list\n+ obj = obj[0]\n+ except IndexError: # Nothing to serialize\n return dict((k, v) for k, v in self.declared_fields.items() if k in field_names)\n- obj = obj_prototype\n ret = self.dict_class()\n for key in field_names:\n if key in self.declared_fields:\n", "test_patch": "diff --git a/tests/test_serialization.py b/tests/test_serialization.py\n--- a/tests/test_serialization.py\n+++ b/tests/test_serialization.py\n@@ -782,3 +782,21 @@ class ValueSchema(Schema):\n \n serialized = ValueSchema(many=True).dump(slice).data\n assert serialized == values\n+\n+\n+# https://github.com/marshmallow-code/marshmallow/issues/1163\n+def test_nested_field_many_serializing_generator():\n+ class MySchema(Schema):\n+ name = fields.Str()\n+\n+ class OtherSchema(Schema):\n+ objects = fields.Nested(MySchema, many=True)\n+\n+ def gen():\n+ yield {'name': 'foo'}\n+ yield {'name': 'bar'}\n+\n+ obj = {'objects': gen()}\n+ data, _ = OtherSchema().dump(obj)\n+\n+ assert data.get('objects') == [{'name': 'foo'}, {'name': 'bar'}]\n", "problem_statement": "2.x: Nested(many=True) eats first element from generator value when dumping\nAs reproduced in Python 3.6.8:\r\n\r\n```py\r\nfrom marshmallow import Schema, fields\r\n\r\nclass O(Schema):\r\n i = fields.Int()\r\n\r\nclass P(Schema):\r\n os = fields.Nested(O, many=True)\r\n\r\ndef gen():\r\n yield {'i': 1}\r\n yield {'i': 0}\r\n\r\np = P()\r\np.dump({'os': gen()})\r\n# MarshalResult(data={'os': [{'i': 0}]}, errors={})\r\n```\r\n\r\nProblematic code is here:\r\n\r\nhttps://github.com/marshmallow-code/marshmallow/blob/2.x-line/src/marshmallow/fields.py#L447\r\n\r\nAnd here:\r\n\r\nhttps://github.com/marshmallow-code/marshmallow/blob/2.x-line/src/marshmallow/schema.py#L832\r\n\r\nThe easiest solution would be to cast `nested_obj` to list before calling `schema._update_fields`, just like a normal Schema with `many=True` does.\n", "hints_text": "I confirmed that this is no longer an issue in marshmallow 3. I was able to reproduce this with python 2 and 3 using the latest version of marshmallow 2.\n`next(iter(...))` is not a safe operation for generators.\r\n\r\n```py\r\ndef gen():\r\n yield 1\r\n yield 2\r\n\r\nx = gen()\r\nnext(iter(x))\r\n# 1\r\nlist(x)\r\n# [2]\r\n```\r\n\r\nI suspect `list` would be an acceptable solution. If it was a performance concern we could use `itertools.tee` to copy the generator before peeking at the first item.\n`next(iter(...))` is apparently fine because `obj` is guaranteed to be a list here:\r\n\r\nhttps://github.com/marshmallow-code/marshmallow/blob/2.x-line/src/marshmallow/schema.py#L489\r\n\r\nIt's just that usage of `Schema._update_fileds` in `Nested` ignores the requirement.\r\n", "created_at": "2019-03-01T17:03:05Z", "version": "2.18", "FAIL_TO_PASS": ["tests/test_serialization.py::test_nested_field_many_serializing_generator"], "PASS_TO_PASS": ["tests/test_serialization.py::TestFieldSerialization::test_default", "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", "tests/test_serialization.py::TestFieldSerialization::test_callable_default", "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func_is_deprecated", "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", "tests/test_serialization.py::TestFieldSerialization::test_integer_field", "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", "tests/test_serialization.py::TestFieldSerialization::test_callable_field", "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", "tests/test_serialization.py::TestFieldSerialization::test_function_with_uncallable_param", "tests/test_serialization.py::TestFieldSerialization::test_email_field_validates", "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", "tests/test_serialization.py::TestFieldSerialization::test_dict_field_invalid_dict_but_okay", "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", "tests/test_serialization.py::TestFieldSerialization::test_url_field_validates", "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", "tests/test_serialization.py::TestFieldSerialization::test_method_prefers_serialize_over_method_name", "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_dump_to_param", "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_dump_to_uses_dump_to", "tests/test_serialization.py::TestFieldSerialization::test_datetime_serializes_to_iso_by_default", "tests/test_serialization.py::TestFieldSerialization::test_datetime_invalid_serialization[invalid]", "tests/test_serialization.py::TestFieldSerialization::test_datetime_invalid_serialization[value1]", "tests/test_serialization.py::TestFieldSerialization::test_datetime_invalid_serialization[24]", "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_rfc822[rfc]", "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_rfc822[rfc822]", "tests/test_serialization.py::TestFieldSerialization::test_localdatetime_rfc_field", "tests/test_serialization.py::TestFieldSerialization::test_datetime_iso8601[iso]", "tests/test_serialization.py::TestFieldSerialization::test_datetime_iso8601[iso8601]", "tests/test_serialization.py::TestFieldSerialization::test_localdatetime_iso", "tests/test_serialization.py::TestFieldSerialization::test_datetime_format", "tests/test_serialization.py::TestFieldSerialization::test_string_field", "tests/test_serialization.py::TestFieldSerialization::test_formattedstring_field", "tests/test_serialization.py::TestFieldSerialization::test_formattedstring_field_on_schema", "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", "tests/test_serialization.py::TestFieldSerialization::test_time_field", "tests/test_serialization.py::TestFieldSerialization::test_invalid_time_field_serialization[badvalue]", "tests/test_serialization.py::TestFieldSerialization::test_invalid_time_field_serialization[]", "tests/test_serialization.py::TestFieldSerialization::test_invalid_time_field_serialization[in_data2]", "tests/test_serialization.py::TestFieldSerialization::test_invalid_time_field_serialization[42]", "tests/test_serialization.py::TestFieldSerialization::test_date_field", "tests/test_serialization.py::TestFieldSerialization::test_invalid_date_field_serialization[badvalue]", "tests/test_serialization.py::TestFieldSerialization::test_invalid_date_field_serialization[]", "tests/test_serialization.py::TestFieldSerialization::test_invalid_date_field_serialization[in_data2]", "tests/test_serialization.py::TestFieldSerialization::test_invalid_date_field_serialization[42]", "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", "tests/test_serialization.py::TestFieldSerialization::test_list_field_with_error", "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_serialize_single_value", "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", "tests/test_serialization.py::TestFieldSerialization::test_list_field_respect_inner_attribute", "tests/test_serialization.py::TestFieldSerialization::test_list_field_respect_inner_attribute_single_value", "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_error", "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[LocalDateTime]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FormattedString]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", "tests/test_serialization.py::test_serializing_named_tuple", "tests/test_serialization.py::test_serializing_named_tuple_with_meta", "tests/test_serialization.py::test_serializing_slice"], "environment_setup_commit": "1e26d14facab213df5009300b997481aa43df80a"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1252", "base_commit": "b063a103ae5222a5953cd7453a1eb0d161dc5b52", "patch": "diff --git a/src/marshmallow/utils.py b/src/marshmallow/utils.py\n--- a/src/marshmallow/utils.py\n+++ b/src/marshmallow/utils.py\n@@ -285,6 +285,9 @@ def from_iso(datestring, use_dateutil=True):\n # Strip off timezone info.\n if '.' in datestring:\n # datestring contains microseconds\n+ (dt_nomstz, mstz) = datestring.split('.')\n+ ms_notz = mstz[:len(mstz) - len(mstz.lstrip('0123456789'))]\n+ datestring = '.'.join((dt_nomstz, ms_notz))\n return datetime.datetime.strptime(datestring[:26], '%Y-%m-%dT%H:%M:%S.%f')\n return datetime.datetime.strptime(datestring[:19], '%Y-%m-%dT%H:%M:%S')\n \n", "test_patch": "diff --git a/tests/test_utils.py b/tests/test_utils.py\n--- a/tests/test_utils.py\n+++ b/tests/test_utils.py\n@@ -200,6 +200,15 @@ def test_from_iso_datetime(use_dateutil, timezone):\n assert type(result) == dt.datetime\n assert_datetime_equal(result, d)\n \n+ # Test with 3-digit only microseconds\n+ #\u00a0Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251\n+ d = dt.datetime.now(tz=timezone).replace(microsecond=123000)\n+ formatted = d.isoformat()\n+ formatted = formatted[:23] + formatted[26:]\n+ result = utils.from_iso(formatted, use_dateutil=use_dateutil)\n+ assert type(result) == dt.datetime\n+ assert_datetime_equal(result, d)\n+\n def test_from_iso_with_tz():\n d = central.localize(dt.datetime.now())\n formatted = d.isoformat()\n", "problem_statement": "ISO8601 DateTimes ending with Z considered not valid in 2.19.4\nProbably related to #1247 and #1234 - in marshmallow `2.19.4`, with `python-dateutil` _not_ installed, it seems that loading a datetime in ISO8601 that ends in `Z` (UTC time) results in an error:\r\n\r\n```python\r\nclass Foo(Schema):\r\n date = DateTime(required=True)\r\n\r\n\r\nfoo_schema = Foo(strict=True)\r\n\r\na_date_with_z = '2019-06-17T00:57:41.000Z'\r\nfoo_schema.load({'date': a_date_with_z})\r\n```\r\n\r\n```\r\nmarshmallow.exceptions.ValidationError: {'date': ['Not a valid datetime.']}\r\n```\r\n\r\nDigging a bit deeper, it seems [`from_iso_datetime`](https://github.com/marshmallow-code/marshmallow/blob/dev/src/marshmallow/utils.py#L213-L215) is failing with a `unconverted data remains: Z` - my understanding of the spec is rather limited, but it seems that they are indeed valid ISO8601 dates (and in `marshmallow==2.19.3` and earlier, the previous snippet seems to work without raising validation errors).\r\n\n", "hints_text": "@lafrech Would you mind looking into this?\nThanks for reporting.\r\n\r\nThis is definitely a side effect of https://github.com/marshmallow-code/marshmallow/pull/1249/files. Sorry about that.\r\n\r\nI don't own a copy of the spec, so the work on this is based on examples... I assumed that microseconds always came as a six-pack. It seems only three digits (your example) is acceptable. From what I understand in the regex we copied from Django, we could even expect any number of digits in [1; 6].\r\n\r\nI see two solutions to this:\r\n\r\n- Split around `\".\"`, then in the right part, get all numbers and ignore letters/symbols.\r\n- Split around `\".\"`, then split the right part around anything that delimitates a timezone (`\"Z\"`, `\"+\"`, `\"-\"`, what else?).\r\n\r\n\nThanks both for the prompt reply! I don't have a copy of the spec myself either - for the timezone suffix, I have based my previous comment on [the Wikipedia entry](https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators), which seems to hint at the following designators being allowed:\r\n```\r\n<time>Z\r\n<time>\u00b1hh:mm\r\n<time>\u00b1hhmm\r\n<time>\u00b1hh\r\n```\nI also use this WP page, but it doesn't show much about milli/microseconds.", "created_at": "2019-06-17T13:44:50Z", "version": "2.19", "FAIL_TO_PASS": ["tests/test_utils.py::test_from_iso_datetime[timezone1-False]"], "PASS_TO_PASS": ["tests/test_utils.py::test_missing_singleton_copy", "tests/test_utils.py::test_to_marshallable_type", "tests/test_utils.py::test_to_marshallable_type_none", "tests/test_utils.py::test_to_marshallable_type_with_namedtuple", "tests/test_utils.py::test_get_value_from_object[obj0]", "tests/test_utils.py::test_get_value_from_object[obj1]", "tests/test_utils.py::test_get_value_from_object[obj2]", "tests/test_utils.py::test_get_value_from_namedtuple_with_default", "tests/test_utils.py::test_get_value_for_nested_object", "tests/test_utils.py::test_get_value_from_dict", "tests/test_utils.py::test_get_value", "tests/test_utils.py::test_set_value", "tests/test_utils.py::test_is_keyed_tuple", "tests/test_utils.py::test_to_marshallable_type_list", "tests/test_utils.py::test_to_marshallable_type_generator", "tests/test_utils.py::test_marshallable", "tests/test_utils.py::test_is_collection", "tests/test_utils.py::test_rfcformat_gmt_naive", "tests/test_utils.py::test_rfcformat_central", "tests/test_utils.py::test_rfcformat_central_localized", "tests/test_utils.py::test_isoformat", "tests/test_utils.py::test_isoformat_tzaware", "tests/test_utils.py::test_isoformat_localtime", "tests/test_utils.py::test_from_datestring", "tests/test_utils.py::test_from_rfc[True]", "tests/test_utils.py::test_from_rfc[False]", "tests/test_utils.py::test_from_iso_datetime[None-True]", "tests/test_utils.py::test_from_iso_datetime[None-False]", "tests/test_utils.py::test_from_iso_datetime[timezone1-True]", "tests/test_utils.py::test_from_iso_with_tz", "tests/test_utils.py::test_from_iso_time_with_microseconds[True]", "tests/test_utils.py::test_from_iso_time_with_microseconds[False]", "tests/test_utils.py::test_from_iso_time_without_microseconds[True]", "tests/test_utils.py::test_from_iso_time_without_microseconds[False]", "tests/test_utils.py::test_from_iso_date[True]", "tests/test_utils.py::test_from_iso_date[False]", "tests/test_utils.py::test_get_func_args"], "environment_setup_commit": "dd72a797ceeea63ee04d5e1838c3a5a1432347e3"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1359", "base_commit": "b40a0f4e33823e6d0f341f7e8684e359a99060d1", "patch": "diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\n--- a/src/marshmallow/fields.py\n+++ b/src/marshmallow/fields.py\n@@ -1114,7 +1114,7 @@ def _bind_to_schema(self, field_name, schema):\n super()._bind_to_schema(field_name, schema)\n self.format = (\n self.format\n- or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\n+ or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)\n or self.DEFAULT_FORMAT\n )\n \n", "test_patch": "diff --git a/tests/test_fields.py b/tests/test_fields.py\n--- a/tests/test_fields.py\n+++ b/tests/test_fields.py\n@@ -169,6 +169,20 @@ class OtherSchema(MySchema):\n assert schema2.fields[\"foo\"].key_field.root == schema2\n assert schema2.fields[\"foo\"].value_field.root == schema2\n \n+ # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1357\n+ def test_datetime_list_inner_format(self, schema):\n+ class MySchema(Schema):\n+ foo = fields.List(fields.DateTime())\n+ bar = fields.Tuple((fields.DateTime(),))\n+\n+ class Meta:\n+ datetimeformat = \"iso8601\"\n+ dateformat = \"iso8601\"\n+\n+ schema = MySchema()\n+ assert schema.fields[\"foo\"].inner.format == \"iso8601\"\n+ assert schema.fields[\"bar\"].tuple_fields[0].format == \"iso8601\"\n+\n \n class TestMetadata:\n @pytest.mark.parametrize(\"FieldClass\", ALL_FIELDS)\n", "problem_statement": "3.0: DateTime fields cannot be used as inner field for List or Tuple fields\nBetween releases 3.0.0rc8 and 3.0.0rc9, `DateTime` fields have started throwing an error when being instantiated as inner fields of container fields like `List` or `Tuple`. The snippet below works in <=3.0.0rc8 and throws the error below in >=3.0.0rc9 (and, worryingly, 3.0.0):\r\n\r\n```python\r\nfrom marshmallow import fields, Schema\r\n\r\nclass MySchema(Schema):\r\n times = fields.List(fields.DateTime())\r\n\r\ns = MySchema()\r\n```\r\n\r\nTraceback:\r\n```\r\nTraceback (most recent call last):\r\n File \"test-mm.py\", line 8, in <module>\r\n s = MySchema()\r\n File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py\", line 383, in __init__\r\n self.fields = self._init_fields()\r\n File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py\", line 913, in _init_fields\r\n self._bind_field(field_name, field_obj)\r\n File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/schema.py\", line 969, in _bind_field\r\n field_obj._bind_to_schema(field_name, self)\r\n File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py\", line 636, in _bind_to_schema\r\n self.inner._bind_to_schema(field_name, self)\r\n File \"/Users/victor/.pyenv/versions/marshmallow/lib/python3.6/site-packages/marshmallow/fields.py\", line 1117, in _bind_to_schema\r\n or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\r\nAttributeError: 'List' object has no attribute 'opts'\r\n```\r\n\r\nIt seems like it's treating the parent field as a Schema without checking that it is indeed a schema, so the `schema.opts` statement fails as fields don't have an `opts` attribute.\n", "hints_text": "Thanks for reporting. I don't think I'll have time to look into this until the weekend. Would you like to send a PR? \nI'm afraid I don't have any time either, and I don't really have enough context on the `_bind_to_schema` process to make sure I'm not breaking stuff.\nOK, no problem. @lafrech Will you have a chance to look into this?\nI've found the patch below to fix the minimal example above, but I'm not really sure what it's missing out on or how to test it properly:\r\n```patch\r\ndiff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\r\nindex 0b18e7d..700732e 100644\r\n--- a/src/marshmallow/fields.py\r\n+++ b/src/marshmallow/fields.py\r\n@@ -1114,7 +1114,7 @@ class DateTime(Field):\r\n super()._bind_to_schema(field_name, schema)\r\n self.format = (\r\n self.format\r\n- or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\r\n+ or getattr(getattr(schema, \"opts\", None), self.SCHEMA_OPTS_VAR_NAME, None)\r\n or self.DEFAULT_FORMAT\r\n )\r\n```\n git difftool 3.0.0rc8 3.0.0rc9 src/marshmallow/fields.py\r\n\r\nWhen reworking container stuff, I changed\r\n\r\n```py\r\n self.inner.parent = self\r\n self.inner.name = field_name\r\n```\r\ninto\r\n\r\n```py\r\n self.inner._bind_to_schema(field_name, self)\r\n```\r\n\r\nAFAIR, I did this merely to avoid duplication. On second thought, I think it was the right thing to do, not only for duplication but to actually bind inner fields to the `Schema`.\r\n\r\nReverting this avoids the error but the inner field's `_bind_to_schema` method is not called so I'm not sure it is desirable.\r\n\r\nI think we really mean to call that method, not only in this case but also generally.\r\n\r\nChanging\r\n\r\n```py\r\n or getattr(schema.opts, self.SCHEMA_OPTS_VAR_NAME)\r\n```\r\n\r\ninto\r\n\r\n```py\r\n or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)\r\n```\r\n\r\nmight be a better fix. Can anyone confirm (@sloria, @deckar01)?\r\n\r\nThe fix in https://github.com/marshmallow-code/marshmallow/issues/1357#issuecomment-523465528 removes the error but also the feature: `DateTime` fields buried into container fields won't respect the format set in the `Schema`.\r\n\r\nI didn't double-check that but AFAIU, the change I mentioned above (in container stuff rework) was the right thing to do. The feature was already broken (format set in `Schema` not respected if `DateTime` field in container field) and that's just one of the issues that may arise due to the inner field not being bound to the `Schema`. But I may be wrong.\nOn quick glance, your analysis and fix look correct @lafrech \nLet's do that, then.\r\n\r\nNot much time either. The first who gets the time can do it.\r\n\r\nFor the non-reg tests :\r\n\r\n1/ a test that checks the format set in the schema is respected if the `DateTime` field is in a container field\r\n\r\n2/ a set of tests asserting the `_bind_to_schema` method of inner fields `List`, `Dict`, `Tuple` is called from container fields (we can use `DateTime` with the same test case for that)\r\n\r\nPerhaps 1/ is useless if 2/ is done.", "created_at": "2019-08-21T15:45:13Z", "version": "3.0", "FAIL_TO_PASS": ["tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format"], "PASS_TO_PASS": ["tests/test_fields.py::test_field_aliases[Integer-Integer]", "tests/test_fields.py::test_field_aliases[String-String]", "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", "tests/test_fields.py::test_field_aliases[Url-Url]", "tests/test_fields.py::TestField::test_repr", "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_simple_field_root", "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", "tests/test_fields.py::TestErrorMessages::test_make_error[required-Missing", "tests/test_fields.py::TestErrorMessages::test_make_error[null-Field", "tests/test_fields.py::TestErrorMessages::test_make_error[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_make_error[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_fail[required-Missing", "tests/test_fields.py::TestErrorMessages::test_fail[null-Field", "tests/test_fields.py::TestErrorMessages::test_fail[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_fail[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[exclude-expected1]", "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested"], "environment_setup_commit": "8b3a32614fd4a74e93e9a63a042e74c1fea34466"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1343", "base_commit": "2be2d83a1a9a6d3d9b85804f3ab545cecc409bb0", "patch": "diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py\n--- a/src/marshmallow/schema.py\n+++ b/src/marshmallow/schema.py\n@@ -877,7 +877,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n for idx, item in enumerate(data):\n try:\n value = item[field_obj.attribute or field_name]\n- except KeyError:\n+ except (KeyError, TypeError):\n pass\n else:\n validated_value = unmarshal.call_and_store(\n@@ -892,7 +892,7 @@ def _invoke_field_validators(self, unmarshal, data, many):\n else:\n try:\n value = data[field_obj.attribute or field_name]\n- except KeyError:\n+ except (KeyError, TypeError):\n pass\n else:\n validated_value = unmarshal.call_and_store(\n", "test_patch": "diff --git a/tests/test_marshalling.py b/tests/test_marshalling.py\n--- a/tests/test_marshalling.py\n+++ b/tests/test_marshalling.py\n@@ -2,7 +2,7 @@\n \n import pytest\n \n-from marshmallow import fields, Schema\n+from marshmallow import fields, Schema, validates\n from marshmallow.marshalling import Marshaller, Unmarshaller, missing\n from marshmallow.exceptions import ValidationError\n \n@@ -283,3 +283,24 @@ class TestSchema(Schema):\n \n assert result is None\n assert excinfo.value.messages == {'foo': {'_schema': ['Invalid input type.']}}\n+\n+ # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1342\n+ def test_deserialize_wrong_nested_type_with_validates_method(self, unmarshal):\n+ class TestSchema(Schema):\n+ value = fields.String()\n+\n+ @validates('value')\n+ def validate_value(self, value):\n+ pass\n+\n+ data = {\n+ 'foo': 'not what we need'\n+ }\n+ fields_dict = {\n+ 'foo': fields.Nested(TestSchema, required=True)\n+ }\n+ with pytest.raises(ValidationError) as excinfo:\n+ result = unmarshal.deserialize(data, fields_dict)\n+\n+ assert result is None\n+ assert excinfo.value.messages == {'foo': {'_schema': ['Invalid input type.']}}\n", "problem_statement": "[version 2.20.0] TypeError: 'NoneType' object is not subscriptable\nAfter update from version 2.19.5 to 2.20.0 I got error for code like:\r\n\r\n```python\r\nfrom marshmallow import Schema, fields, validates\r\n\r\n\r\nclass Bar(Schema):\r\n value = fields.String()\r\n\r\n @validates('value') # <- issue here\r\n def validate_value(self, value):\r\n pass\r\n\r\n\r\nclass Foo(Schema):\r\n bar = fields.Nested(Bar)\r\n\r\n\r\nsch = Foo()\r\n\r\nsch.validate({\r\n 'bar': 'invalid',\r\n})\r\n```\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"/_/bug_mschema.py\", line 19, in <module>\r\n 'bar': 'invalid',\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 628, in validate\r\n _, errors = self._do_load(data, many, partial=partial, postprocess=False)\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 670, in _do_load\r\n index_errors=self.opts.index_errors,\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py\", line 292, in deserialize\r\n index=(index if index_errors else None)\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py\", line 65, in call_and_store\r\n value = getter_func(data)\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/marshalling.py\", line 285, in <lambda>\r\n data\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/fields.py\", line 265, in deserialize\r\n output = self._deserialize(value, attr, data)\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/fields.py\", line 465, in _deserialize\r\n data, errors = self.schema.load(value)\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 588, in load\r\n result, errors = self._do_load(data, many, partial=partial, postprocess=True)\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 674, in _do_load\r\n self._invoke_field_validators(unmarshal, data=result, many=many)\r\n File \"/_/env/lib/python3.7/site-packages/marshmallow/schema.py\", line 894, in _invoke_field_validators\r\n value = data[field_obj.attribute or field_name]\r\nTypeError: 'NoneType' object is not subscriptable\r\n```\n", "hints_text": "Thanks for reporting. I was able to reproduce this on 2.20.0. This is likely a regression from https://github.com/marshmallow-code/marshmallow/pull/1323 . I don't have time to look into it now. Would appreciate a PR.", "created_at": "2019-08-13T04:36:01Z", "version": "2.20", "FAIL_TO_PASS": ["tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_nested_type_with_validates_method"], "PASS_TO_PASS": ["tests/test_marshalling.py::test_missing_is_falsy", "tests/test_marshalling.py::TestMarshaller::test_prefix", "tests/test_marshalling.py::TestMarshaller::test_marshalling_generator", "tests/test_marshalling.py::TestMarshaller::test_default_to_missing", "tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_load_only_param", "tests/test_marshalling.py::TestMarshaller::test_missing_data_are_skipped", "tests/test_marshalling.py::TestMarshaller::test_serialize_with_load_only_doesnt_validate", "tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_dump_to_param", "tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_dump_to_and_prefix_params", "tests/test_marshalling.py::TestMarshaller::test_stores_indices_of_errors_when_many_equals_true", "tests/test_marshalling.py::TestMarshaller::test_doesnt_store_errors_when_index_errors_equals_false", "tests/test_marshalling.py::TestUnmarshaller::test_extra_data_is_ignored", "tests/test_marshalling.py::TestUnmarshaller::test_stores_errors", "tests/test_marshalling.py::TestUnmarshaller::test_stores_indices_of_errors_when_many_equals_true", "tests/test_marshalling.py::TestUnmarshaller::test_doesnt_store_errors_when_index_errors_equals_false", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize", "tests/test_marshalling.py::TestUnmarshaller::test_extra_fields", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_many", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_stores_errors", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_attribute_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_load_from_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_dump_only_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_type_root_data", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_wrong_type_nested_data"], "environment_setup_commit": "7015fc4333a2f32cd58c3465296e834acd4496ff"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-2123", "base_commit": "5a10e83c557d2ee97799c2b85bec49fc90381656", "patch": "diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\n--- a/src/marshmallow/fields.py\n+++ b/src/marshmallow/fields.py\n@@ -1710,6 +1710,7 @@ def __init__(\n self,\n *,\n relative: bool = False,\n+ absolute: bool = True,\n schemes: types.StrSequenceOrSet | None = None,\n require_tld: bool = True,\n **kwargs,\n@@ -1717,10 +1718,12 @@ def __init__(\n super().__init__(**kwargs)\n \n self.relative = relative\n+ self.absolute = absolute\n self.require_tld = require_tld\n # Insert validation into self.validators so that multiple errors can be stored.\n validator = validate.URL(\n relative=self.relative,\n+ absolute=self.absolute,\n schemes=schemes,\n require_tld=self.require_tld,\n error=self.error_messages[\"invalid\"],\ndiff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py\n--- a/src/marshmallow/validate.py\n+++ b/src/marshmallow/validate.py\n@@ -94,6 +94,7 @@ class URL(Validator):\n \"\"\"Validate a URL.\n \n :param relative: Whether to allow relative URLs.\n+ :param absolute: Whether to allow absolute URLs.\n :param error: Error message to raise in case of a validation error.\n Can be interpolated with `{input}`.\n :param schemes: Valid schemes. By default, ``http``, ``https``,\n@@ -105,38 +106,68 @@ class RegexMemoizer:\n def __init__(self):\n self._memoized = {}\n \n- def _regex_generator(self, relative: bool, require_tld: bool) -> typing.Pattern:\n- return re.compile(\n- r\"\".join(\n- (\n- r\"^\",\n- r\"(\" if relative else r\"\",\n- r\"(?:[a-z0-9\\.\\-\\+]*)://\", # scheme is validated separately\n- r\"(?:[^:@]+?(:[^:@]*?)?@|)\", # basic auth\n- r\"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+\",\n- r\"(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|\", # domain...\n- r\"localhost|\", # localhost...\n- (\n- r\"(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.?)|\"\n- if not require_tld\n- else r\"\"\n- ), # allow dotless hostnames\n- r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\", # ...or ipv4\n- r\"\\[[A-F0-9]*:[A-F0-9:]+\\])\", # ...or ipv6\n- r\"(?::\\d+)?\", # optional port\n- r\")?\"\n- if relative\n- else r\"\", # host is optional, allow for relative URLs\n- r\"(?:/?|[/?]\\S+)\\Z\",\n- )\n+ def _regex_generator(\n+ self, relative: bool, absolute: bool, require_tld: bool\n+ ) -> typing.Pattern:\n+ hostname_variants = [\n+ # a normal domain name, expressed in [A-Z0-9] chars with hyphens allowed only in the middle\n+ # note that the regex will be compiled with IGNORECASE, so these are upper and lowercase chars\n+ (\n+ r\"(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+\"\n+ r\"(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)\"\n ),\n- re.IGNORECASE,\n+ # or the special string 'localhost'\n+ r\"localhost\",\n+ # or IPv4\n+ r\"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\",\n+ # or IPv6\n+ r\"\\[[A-F0-9]*:[A-F0-9:]+\\]\",\n+ ]\n+ if not require_tld:\n+ # allow dotless hostnames\n+ hostname_variants.append(r\"(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.?)\")\n+\n+ absolute_part = \"\".join(\n+ (\n+ # scheme (e.g. 'https://', 'ftp://', etc)\n+ # this is validated separately against allowed schemes, so in the regex\n+ # we simply want to capture its existence\n+ r\"(?:[a-z0-9\\.\\-\\+]*)://\",\n+ # basic_auth, for URLs encoding a username:password\n+ # e.g. 'ftp://foo:[email protected]/'\n+ r\"(?:[^:@]+?(:[^:@]*?)?@|)\",\n+ # netloc, the hostname/domain part of the URL plus the optional port\n+ r\"(?:\",\n+ \"|\".join(hostname_variants),\n+ r\")\",\n+ r\"(?::\\d+)?\",\n+ )\n )\n+ relative_part = r\"(?:/?|[/?]\\S+)\\Z\"\n+\n+ if relative:\n+ if absolute:\n+ parts: tuple[str, ...] = (\n+ r\"^(\",\n+ absolute_part,\n+ r\")?\",\n+ relative_part,\n+ )\n+ else:\n+ parts = (r\"^\", relative_part)\n+ else:\n+ parts = (r\"^\", absolute_part, relative_part)\n \n- def __call__(self, relative: bool, require_tld: bool) -> typing.Pattern:\n- key = (relative, require_tld)\n+ return re.compile(\"\".join(parts), re.IGNORECASE)\n+\n+ def __call__(\n+ self, relative: bool, absolute: bool, require_tld: bool\n+ ) -> typing.Pattern:\n+ key = (relative, absolute, require_tld)\n if key not in self._memoized:\n- self._memoized[key] = self._regex_generator(relative, require_tld)\n+ self._memoized[key] = self._regex_generator(\n+ relative, absolute, require_tld\n+ )\n \n return self._memoized[key]\n \n@@ -149,17 +180,23 @@ def __init__(\n self,\n *,\n relative: bool = False,\n+ absolute: bool = True,\n schemes: types.StrSequenceOrSet | None = None,\n require_tld: bool = True,\n error: str | None = None,\n ):\n+ if not relative and not absolute:\n+ raise ValueError(\n+ \"URL validation cannot set both relative and absolute to False.\"\n+ )\n self.relative = relative\n+ self.absolute = absolute\n self.error = error or self.default_message # type: str\n self.schemes = schemes or self.default_schemes\n self.require_tld = require_tld\n \n def _repr_args(self) -> str:\n- return f\"relative={self.relative!r}\"\n+ return f\"relative={self.relative!r}, absolute={self.absolute!r}\"\n \n def _format_error(self, value) -> str:\n return self.error.format(input=value)\n@@ -175,7 +212,7 @@ def __call__(self, value: str) -> str:\n if scheme not in self.schemes:\n raise ValidationError(message)\n \n- regex = self._regex(self.relative, self.require_tld)\n+ regex = self._regex(self.relative, self.absolute, self.require_tld)\n \n if not regex.search(value):\n raise ValidationError(message)\n", "test_patch": "diff --git a/tests/test_validate.py b/tests/test_validate.py\n--- a/tests/test_validate.py\n+++ b/tests/test_validate.py\n@@ -75,6 +75,9 @@ def test_url_absolute_invalid(invalid_url):\n \"http://example.com/./icons/logo.gif\",\n \"ftp://example.com/../../../../g\",\n \"http://example.com/g?y/./x\",\n+ \"/foo/bar\",\n+ \"/foo?bar\",\n+ \"/foo?bar#baz\",\n ],\n )\n def test_url_relative_valid(valid_url):\n@@ -104,6 +107,48 @@ def test_url_relative_invalid(invalid_url):\n validator(invalid_url)\n \n \[email protected](\n+ \"valid_url\",\n+ [\n+ \"/foo/bar\",\n+ \"/foo?bar\",\n+ \"?bar\",\n+ \"/foo?bar#baz\",\n+ ],\n+)\n+def test_url_relative_only_valid(valid_url):\n+ validator = validate.URL(relative=True, absolute=False)\n+ assert validator(valid_url) == valid_url\n+\n+\[email protected](\n+ \"invalid_url\",\n+ [\n+ \"http//example.org\",\n+ \"http://example.org\\n\",\n+ \"suppliers.html\",\n+ \"../icons/logo.gif\",\n+ \"icons/logo.gif\",\n+ \"../.../g\",\n+ \"...\",\n+ \"\\\\\",\n+ \" \",\n+ \"\",\n+ \"http://example.org\",\n+ \"http://123.45.67.8/\",\n+ \"http://example.com/foo/bar/../baz\",\n+ \"https://example.com/../icons/logo.gif\",\n+ \"http://example.com/./icons/logo.gif\",\n+ \"ftp://example.com/../../../../g\",\n+ \"http://example.com/g?y/./x\",\n+ ],\n+)\n+def test_url_relative_only_invalid(invalid_url):\n+ validator = validate.URL(relative=True, absolute=False)\n+ with pytest.raises(ValidationError):\n+ validator(invalid_url)\n+\n+\n @pytest.mark.parametrize(\n \"valid_url\",\n [\n@@ -170,10 +215,21 @@ def test_url_custom_message():\n def test_url_repr():\n assert repr(\n validate.URL(relative=False, error=None)\n- ) == \"<URL(relative=False, error={!r})>\".format(\"Not a valid URL.\")\n+ ) == \"<URL(relative=False, absolute=True, error={!r})>\".format(\"Not a valid URL.\")\n assert repr(\n validate.URL(relative=True, error=\"foo\")\n- ) == \"<URL(relative=True, error={!r})>\".format(\"foo\")\n+ ) == \"<URL(relative=True, absolute=True, error={!r})>\".format(\"foo\")\n+ assert repr(\n+ validate.URL(relative=True, absolute=False, error=\"foo\")\n+ ) == \"<URL(relative=True, absolute=False, error={!r})>\".format(\"foo\")\n+\n+\n+def test_url_rejects_invalid_relative_usage():\n+ with pytest.raises(\n+ ValueError,\n+ match=\"URL validation cannot set both relative and absolute to False\",\n+ ):\n+ validate.URL(relative=False, absolute=False)\n \n \n @pytest.mark.parametrize(\n", "problem_statement": "fields.URL should allow relative-only validation\nRelative URLs may be used to redirect the user within the site, such as to sign in, and allowing absolute URLs without extra validation opens up a possibility of nefarious redirects.\r\n\r\nCurrent `fields.URL(relative = True)` allows relative URLs _in addition_ to absolute URLs, so one must set up extra validation to catch either all absolute URLs or just those that don't have a valid domain names.\r\n\r\nIt would be helpful if there was a way to set up URL validation to allow only relative URLs. \r\n\r\n~One quick and dirty way to do this would be if there was a `validate.Not` operator, then at the expense of matching the value twice, it would be possible to use something like this:~\r\n\r\n~`fields.URL(relative = True, validate=validate.Not(validate.URL()))`~\r\n\r\nEDIT: Never mind the crossed out thought above - failed validations are handled only via exceptions and while failing the inner validator works in general, it requires suppressing exception handlers and is just not a good way to go about it. \n", "hints_text": "Maybe an additional flag `absolute` that would default to `True`?\r\n\r\nWould you like to work on this?\n@lafrech Thank you for commenting. \r\n\r\nMy thinking would be that flavors could be selected individually, as if flags are used, so they could be combined. Something along these lines:\r\n\r\n```\r\nargs = {\r\n \"ref\": fields.URL(kind=fields.URL.absolute | fields.URL.relative)\r\n # OR\r\n \"ref\": fields.URL(kind=[\"absolute\", \"relative\"])\r\n```\r\n\r\nThis also would allow to retain backward compatibility for existing `relative=True|False`, which would be translated to these flags combined or just absolute flag being used.\r\n\r\nAn extra Boolean would work fine as well. It would be similar to how Joi handles it:\r\n\r\nhttps://joi.dev/api/?v=17.9.1#stringurioptions\r\n\r\nAs for me fixing it, I'm not sure - the evaluation of the attribute for relative URLs is integrated in a pretty intricate regex construction with those Booleans used as keys. This change sounds bigger than I could commit to at this point. My apologies. Please feel free to close this issue if there's no one else interested in it.\nI'm not very proficient with regexes, although the change involved here should be marginal (the regex is already conditional due to the absolute flag).\r\n\r\nI won't take the time to do it but I don't mind keeping this open for now.", "created_at": "2023-04-26T19:13:12Z", "version": "3.19", "FAIL_TO_PASS": ["tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", "tests/test_validate.py::test_url_relative_only_valid[?bar]", "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", "tests/test_validate.py::test_url_relative_only_invalid[...]", "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", "tests/test_validate.py::test_url_relative_only_invalid[", "tests/test_validate.py::test_url_relative_only_invalid[]", "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", "tests/test_validate.py::test_url_repr", "tests/test_validate.py::test_url_rejects_invalid_relative_usage"], "PASS_TO_PASS": ["tests/test_validate.py::test_url_absolute_valid[http://example.org]", "tests/test_validate.py::test_url_absolute_valid[https://example.org]", "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", "tests/test_validate.py::test_url_absolute_valid[http://[email protected]]", "tests/test_validate.py::test_url_absolute_valid[http://user:[email protected]]", "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", "tests/test_validate.py::test_url_absolute_invalid[http:///]", "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", "tests/test_validate.py::test_url_absolute_invalid[abc]", "tests/test_validate.py::test_url_absolute_invalid[..]", "tests/test_validate.py::test_url_absolute_invalid[/]", "tests/test_validate.py::test_url_absolute_invalid[", "tests/test_validate.py::test_url_absolute_invalid[]", "tests/test_validate.py::test_url_absolute_invalid[None]", "tests/test_validate.py::test_url_relative_valid[http://example.org]", "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", "tests/test_validate.py::test_url_relative_valid[/foo/bar]", "tests/test_validate.py::test_url_relative_valid[/foo?bar]", "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", "tests/test_validate.py::test_url_relative_invalid[http//example.org]", "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", "tests/test_validate.py::test_url_relative_invalid[../.../g]", "tests/test_validate.py::test_url_relative_invalid[...]", "tests/test_validate.py::test_url_relative_invalid[\\\\]", "tests/test_validate.py::test_url_relative_invalid[", "tests/test_validate.py::test_url_relative_invalid[]", "tests/test_validate.py::test_url_relative_invalid[None]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http://", "tests/test_validate.py::test_url_dont_require_tld_invalid[]", "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", "tests/test_validate.py::test_url_custom_scheme", "tests/test_validate.py::test_url_relative_and_custom_schemes", "tests/test_validate.py::test_url_custom_message", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[\"[email protected]\"@example.com]", "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|[email protected]]", "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", "tests/test_validate.py::test_email_valid[jos\\[email protected]]", "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", "tests/test_validate.py::test_email_invalid[niceandsimple\\[email protected]]", "tests/test_validate.py::test_email_invalid[[email protected]\\n]", "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;g<h>i[j\\\\k][email protected]]", "tests/test_validate.py::test_email_invalid[just\"not\"[email protected]]", "tests/test_validate.py::test_email_invalid[this", "tests/test_validate.py::test_email_invalid[this\\\\", "tests/test_validate.py::test_email_invalid[\"much.more", "tests/test_validate.py::test_email_invalid[\"very.(),:;<>[]\".VERY.\"very@\\\\", "tests/test_validate.py::test_email_invalid[\"", "tests/test_validate.py::test_email_invalid[user@example]", "tests/test_validate.py::test_email_invalid[@nouser.com]", "tests/test_validate.py::test_email_invalid[example.com]", "tests/test_validate.py::test_email_invalid[user]", "tests/test_validate.py::test_email_invalid[]", "tests/test_validate.py::test_email_invalid[None]", "tests/test_validate.py::test_email_custom_message", "tests/test_validate.py::test_email_repr", "tests/test_validate.py::test_range_min", "tests/test_validate.py::test_range_max", "tests/test_validate.py::test_range_custom_message", "tests/test_validate.py::test_range_repr", "tests/test_validate.py::test_length_min", "tests/test_validate.py::test_length_max", "tests/test_validate.py::test_length_equal", "tests/test_validate.py::test_length_custom_message", "tests/test_validate.py::test_length_repr", "tests/test_validate.py::test_equal", "tests/test_validate.py::test_equal_custom_message", "tests/test_validate.py::test_equal_repr", "tests/test_validate.py::test_regexp_str", "tests/test_validate.py::test_regexp_compile", "tests/test_validate.py::test_regexp_custom_message", "tests/test_validate.py::test_regexp_repr", "tests/test_validate.py::test_predicate", "tests/test_validate.py::test_predicate_custom_message", "tests/test_validate.py::test_predicate_repr", "tests/test_validate.py::test_noneof", "tests/test_validate.py::test_noneof_custom_message", "tests/test_validate.py::test_noneof_repr", "tests/test_validate.py::test_oneof", "tests/test_validate.py::test_oneof_options", "tests/test_validate.py::test_oneof_text", "tests/test_validate.py::test_oneof_custom_message", "tests/test_validate.py::test_oneof_repr", "tests/test_validate.py::test_containsonly_in_list", "tests/test_validate.py::test_contains_only_unhashable_types", "tests/test_validate.py::test_containsonly_in_tuple", "tests/test_validate.py::test_contains_only_in_string", "tests/test_validate.py::test_containsonly_custom_message", "tests/test_validate.py::test_containsonly_repr", "tests/test_validate.py::test_containsnoneof_error_message", "tests/test_validate.py::test_containsnoneof_in_list", "tests/test_validate.py::test_containsnoneof_unhashable_types", "tests/test_validate.py::test_containsnoneof_in_tuple", "tests/test_validate.py::test_containsnoneof_in_string", "tests/test_validate.py::test_containsnoneof_custom_message", "tests/test_validate.py::test_containsnoneof_mixing_types", "tests/test_validate.py::test_and"], "environment_setup_commit": "819749204b9a7271c189401e5f5aa00cab624514"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1229", "base_commit": "456bacbbead4fa30a1a82892c9446ac9efb8055b", "patch": "diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\n--- a/src/marshmallow/fields.py\n+++ b/src/marshmallow/fields.py\n@@ -576,12 +576,18 @@ def __init__(self, cls_or_instance, **kwargs):\n 'The list elements must be a subclass or instance of '\n 'marshmallow.base.FieldABC.',\n )\n+ if isinstance(self.container, Nested):\n+ self.only = self.container.only\n+ self.exclude = self.container.exclude\n \n def _bind_to_schema(self, field_name, schema):\n super()._bind_to_schema(field_name, schema)\n self.container = copy.deepcopy(self.container)\n self.container.parent = self\n self.container.name = field_name\n+ if isinstance(self.container, Nested):\n+ self.container.only = self.only\n+ self.container.exclude = self.exclude\n \n def _serialize(self, value, attr, obj, **kwargs):\n if value is None:\n@@ -656,10 +662,11 @@ def _bind_to_schema(self, field_name, schema):\n super()._bind_to_schema(field_name, schema)\n new_tuple_fields = []\n for container in self.tuple_fields:\n- new_container = copy.deepcopy(container)\n- new_container.parent = self\n- new_container.name = field_name\n- new_tuple_fields.append(new_container)\n+ container = copy.deepcopy(container)\n+ container.parent = self\n+ container.name = field_name\n+ new_tuple_fields.append(container)\n+\n self.tuple_fields = new_tuple_fields\n \n def _serialize(self, value, attr, obj, **kwargs):\n@@ -1288,6 +1295,9 @@ def __init__(self, keys=None, values=None, **kwargs):\n '\"values\" must be a subclass or instance of '\n 'marshmallow.base.FieldABC.',\n )\n+ if isinstance(self.value_container, Nested):\n+ self.only = self.value_container.only\n+ self.exclude = self.value_container.exclude\n \n def _bind_to_schema(self, field_name, schema):\n super()._bind_to_schema(field_name, schema)\n@@ -1295,6 +1305,9 @@ def _bind_to_schema(self, field_name, schema):\n self.value_container = copy.deepcopy(self.value_container)\n self.value_container.parent = self\n self.value_container.name = field_name\n+ if isinstance(self.value_container, Nested):\n+ self.value_container.only = self.only\n+ self.value_container.exclude = self.exclude\n if self.key_container:\n self.key_container = copy.deepcopy(self.key_container)\n self.key_container.parent = self\n", "test_patch": "diff --git a/tests/test_fields.py b/tests/test_fields.py\n--- a/tests/test_fields.py\n+++ b/tests/test_fields.py\n@@ -247,6 +247,36 @@ class MySchema(Schema):\n \n class TestListNested:\n \n+ @pytest.mark.parametrize('param', ('only', 'exclude', 'dump_only', 'load_only'))\n+ def test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested(self, param):\n+\n+ class Child(Schema):\n+ name = fields.String()\n+ age = fields.Integer()\n+\n+ class Family(Schema):\n+ children = fields.List(fields.Nested(Child))\n+\n+ schema = Family(**{param: ['children.name']})\n+ assert getattr(schema.fields['children'].container.schema, param) == {'name'}\n+\n+ @pytest.mark.parametrize(\n+ ('param', 'expected'),\n+ (('only', {'name'}), ('exclude', {'name', 'surname', 'age'})),\n+ )\n+ def test_list_nested_only_and_exclude_merged_with_nested(self, param, expected):\n+\n+ class Child(Schema):\n+ name = fields.String()\n+ surname = fields.String()\n+ age = fields.Integer()\n+\n+ class Family(Schema):\n+ children = fields.List(fields.Nested(Child, **{param: ('name', 'surname')}))\n+\n+ schema = Family(**{param: ['children.name', 'children.age']})\n+ assert getattr(schema.fields['children'].container, param) == expected\n+\n def test_list_nested_partial_propagated_to_nested(self):\n \n class Child(Schema):\n@@ -279,6 +309,20 @@ class Family(Schema):\n \n class TestTupleNested:\n \n+ @pytest.mark.parametrize('param', ('dump_only', 'load_only'))\n+ def test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested(self, param):\n+\n+ class Child(Schema):\n+ name = fields.String()\n+ age = fields.Integer()\n+\n+ class Family(Schema):\n+ children = fields.Tuple((fields.Nested(Child), fields.Nested(Child)))\n+\n+ schema = Family(**{param: ['children.name']})\n+ assert getattr(schema.fields['children'].tuple_fields[0].schema, param) == {'name'}\n+ assert getattr(schema.fields['children'].tuple_fields[1].schema, param) == {'name'}\n+\n def test_tuple_nested_partial_propagated_to_nested(self):\n \n class Child(Schema):\n@@ -311,6 +355,36 @@ class Family(Schema):\n \n class TestDictNested:\n \n+ @pytest.mark.parametrize('param', ('only', 'exclude', 'dump_only', 'load_only'))\n+ def test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested(self, param):\n+\n+ class Child(Schema):\n+ name = fields.String()\n+ age = fields.Integer()\n+\n+ class Family(Schema):\n+ children = fields.Dict(values=fields.Nested(Child))\n+\n+ schema = Family(**{param: ['children.name']})\n+ assert getattr(schema.fields['children'].value_container.schema, param) == {'name'}\n+\n+ @pytest.mark.parametrize(\n+ ('param', 'expected'),\n+ (('only', {'name'}), ('exclude', {'name', 'surname', 'age'})),\n+ )\n+ def test_dict_nested_only_and_exclude_merged_with_nested(self, param, expected):\n+\n+ class Child(Schema):\n+ name = fields.String()\n+ surname = fields.String()\n+ age = fields.Integer()\n+\n+ class Family(Schema):\n+ children = fields.Dict(values=fields.Nested(Child, **{param: ('name', 'surname')}))\n+\n+ schema = Family(**{param: ['children.name', 'children.age']})\n+ assert getattr(schema.fields['children'].value_container, param) == expected\n+\n def test_dict_nested_partial_propagated_to_nested(self):\n \n class Child(Schema):\n", "problem_statement": "`only` argument inconsistent between Nested(S, many=True) and List(Nested(S))\n```python\r\nfrom pprint import pprint\r\n\r\nfrom marshmallow import Schema\r\nfrom marshmallow.fields import Integer, List, Nested, String\r\n\r\n\r\nclass Child(Schema):\r\n name = String()\r\n age = Integer()\r\n\r\n\r\nclass Family(Schema):\r\n children = List(Nested(Child))\r\n\r\n\r\nclass Family2(Schema):\r\n children = Nested(Child, many=True)\r\n\r\nfamily = {'children':[\r\n {'name': 'Tommy', 'age': 12},\r\n {'name': 'Lily', 'age': 15},\r\n]}\r\n\r\npprint(Family( only=['children.name']).dump(family).data)\r\npprint(Family2( only=['children.name']).dump(family).data)\r\n```\r\nreturns\r\n```\r\n{'children': [{'age': 12, 'name': 'Tommy'}, {'age': 15, 'name': 'Lily'}]}\r\n{'children': [{'name': 'Tommy'}, {'name': 'Lily'}]}\r\n```\r\n\r\ntested with marshmallow 2.15.4\r\n\r\nThe same applies to `exclude` argument.\n", "hints_text": "For now I'm using following workaround:\r\n```python\r\nclass ListFix(List):\r\n @property\r\n def only(self):\r\n return getattr(self.container, 'only')\r\n\r\n @only.setter\r\n def only(self, new_options):\r\n original_options = getattr(self.container, 'only', ())\r\n if original_options:\r\n new_options &= type(new_options)(original_options)\r\n setattr(self.container, 'only', new_options)\r\n\r\n\r\nclass Child(Schema):\r\n name = String()\r\n age = Integer()\r\n\r\n\r\nclass Family(Schema):\r\n children = ListFix(Nested(Child))\r\n```\r\n\r\nthe option propagation code was taken from `BaseSchema.__apply_nested_option`\r\n\r\nmaybe apply option code (the part I have copied to ListFix property) should be moved to field?\r\n\r\n**Edited:** Just found a nasty side effect of my \"fix\"\r\n\r\n```python\r\nfamily = {'children': [\r\n {'name': 'Tommy', 'age': 12},\r\n {'name': 'Lily', 'age': 15},\r\n]}\r\n\r\nfor family_schema in (\r\n Family(),\r\n Family(only=['children.name']),\r\n Family2(),\r\n Family2(only=['children.name']),\r\n):\r\n pprint(family_schema.dump(family).data)\r\n```\r\nprints\r\n```\r\n{'children': [{'name': 'Tommy'}, {'name': 'Lily'}]}\r\n{'children': [{'name': 'Tommy'}, {'name': 'Lily'}]}\r\n{'children': [{'age': 12, 'name': 'Tommy'}, {'age': 15, 'name': 'Lily'}]}\r\n{'children': [{'name': 'Tommy'}, {'name': 'Lily'}]}\r\n```\nThanks @rooterkyberian . Let's continue discussion of this in #779.", "created_at": "2019-06-04T07:29:21Z", "version": "3.0", "FAIL_TO_PASS": ["tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestListNested::test_list_nested_only_and_exclude_merged_with_nested[exclude-expected1]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]"], "PASS_TO_PASS": ["tests/test_fields.py::test_field_aliases[Integer-Integer]", "tests/test_fields.py::test_field_aliases[String-String]", "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", "tests/test_fields.py::test_field_aliases[Url-Url]", "tests/test_fields.py::TestField::test_repr", "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", "tests/test_fields.py::TestField::test_number_fields_prohbits_boolean", "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_simple_field_root", "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[LocalDateTime]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", "tests/test_fields.py::TestErrorMessages::test_fail", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested"], "environment_setup_commit": "8b3a32614fd4a74e93e9a63a042e74c1fea34466"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1810", "base_commit": "23d0551569d748460c504af85996451edd685371", "patch": "diff --git a/src/marshmallow/base.py b/src/marshmallow/base.py\n--- a/src/marshmallow/base.py\n+++ b/src/marshmallow/base.py\n@@ -15,6 +15,7 @@ class FieldABC:\n \n parent = None\n name = None\n+ root = None\n \n def serialize(self, attr, obj, accessor=None):\n raise NotImplementedError\ndiff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\n--- a/src/marshmallow/fields.py\n+++ b/src/marshmallow/fields.py\n@@ -352,10 +352,13 @@ def _bind_to_schema(self, field_name, schema):\n :meth:`Schema._bind_field <marshmallow.Schema._bind_field>`.\n \n :param str field_name: Field name set in schema.\n- :param Schema schema: Parent schema.\n+ :param Schema|Field schema: Parent object.\n \"\"\"\n self.parent = self.parent or schema\n self.name = self.name or field_name\n+ self.root = self.root or (\n+ self.parent.root if isinstance(self.parent, FieldABC) else self.parent\n+ )\n \n def _serialize(self, value: typing.Any, attr: str, obj: typing.Any, **kwargs):\n \"\"\"Serializes ``value`` to a basic Python datatype. Noop by default.\n@@ -408,17 +411,6 @@ def context(self):\n \"\"\"The context dictionary for the parent :class:`Schema`.\"\"\"\n return self.parent.context\n \n- @property\n- def root(self):\n- \"\"\"Reference to the `Schema` that this field belongs to even if it is buried in a\n- container field (e.g. `List`).\n- Return `None` for unbound fields.\n- \"\"\"\n- ret = self\n- while hasattr(ret, \"parent\"):\n- ret = ret.parent\n- return ret if isinstance(ret, SchemaABC) else None\n-\n \n class Raw(Field):\n \"\"\"Field that applies no formatting.\"\"\"\n", "test_patch": "diff --git a/tests/test_fields.py b/tests/test_fields.py\n--- a/tests/test_fields.py\n+++ b/tests/test_fields.py\n@@ -187,6 +187,14 @@ class Meta:\n for field_name in (\"bar\", \"qux\"):\n assert schema.fields[field_name].tuple_fields[0].format == \"iso8601\"\n \n+ # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1808\n+ def test_field_named_parent_has_root(self, schema):\n+ class MySchema(Schema):\n+ parent = fields.Field()\n+\n+ schema = MySchema()\n+ assert schema.fields[\"parent\"].root == schema\n+\n \n class TestMetadata:\n @pytest.mark.parametrize(\"FieldClass\", ALL_FIELDS)\n", "problem_statement": "3.12 no longer supports fields named `parent`\nPretty sure that #1631 broke it. Reproducible example:\r\n\r\n```py\r\nfrom marshmallow import INCLUDE\r\nfrom marshmallow.fields import Nested\r\nfrom sqlalchemy import Column, DATE, create_engine, ForeignKey\r\nfrom sqlalchemy.dialects.postgresql import UUID\r\nfrom sqlalchemy.orm import declarative_base, relationship\r\nfrom marshmallow_sqlalchemy import SQLAlchemyAutoSchema\r\nfrom testing.postgresql import Postgresql\r\n\r\n\r\nBase = declarative_base()\r\n\r\n\r\nclass Author(Base):\r\n __tablename__ = 'author'\r\n id = Column(UUID(as_uuid=True), primary_key=True)\r\n docs = relationship('Document', back_populates='parent')\r\n\r\n\r\nclass Document(Base):\r\n __tablename__ = 'document'\r\n id = Column(UUID(as_uuid=True), primary_key=True)\r\n parent_id = Column(UUID(as_uuid=True), ForeignKey('author.id'))\r\n parent = relationship(Author, back_populates='docs')\r\n last_updated = Column(DATE)\r\n\r\n\r\nclass AuthorSchema(SQLAlchemyAutoSchema):\r\n class Meta(SQLAlchemyAutoSchema.Meta):\r\n model = Author\r\n\r\n\r\nclass DocumentSchema(SQLAlchemyAutoSchema):\r\n parent = Nested(AuthorSchema)\r\n\r\n class Meta(SQLAlchemyAutoSchema.Meta):\r\n model = Document\r\n\r\n\r\nwith Postgresql() as postgresql:\r\n url = postgresql.url(drivername='postgresql+psycopg2')\r\n engine = create_engine(url, echo=True)\r\n Base.metadata.create_all(engine)\r\n\r\n DocumentSchema(unknown=INCLUDE)\r\n```\r\n\r\nResults in:\r\n\r\n```pytb\r\nTraceback (most recent call last):\r\n File \"/home/phil/.config/JetBrains/PyCharm2021.1/scratches/sqlalchemy-marshmallow-reprex.py\", line 44, in <module>\r\n DocumentSchema(unknown=INCLUDE)\r\n File \"/home/phil/Dev/Python/venvs/cellarity/lib/python3.9/site-packages/marshmallow_sqlalchemy/schema/load_instance_mixin.py\", line 43, in __init__\r\n super().__init__(*args, **kwargs)\r\n File \"/home/phil/Dev/Python/venvs/cellarity/lib/python3.9/site-packages/marshmallow/schema.py\", line 392, in __init__\r\n self._init_fields()\r\n File \"/home/phil/Dev/Python/venvs/cellarity/lib/python3.9/site-packages/marshmallow/schema.py\", line 971, in _init_fields\r\n self._bind_field(field_name, field_obj)\r\n File \"/home/phil/Dev/Python/venvs/cellarity/lib/python3.9/site-packages/marshmallow/schema.py\", line 1030, in _bind_field\r\n field_obj._bind_to_schema(field_name, self)\r\n File \"/home/phil/Dev/Python/venvs/cellarity/lib/python3.9/site-packages/marshmallow/fields.py\", line 1201, in _bind_to_schema\r\n or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME)\r\nAttributeError: 'NoneType' object has no attribute 'opts'\r\n```\r\n\r\nHere, `self.root` resolves to `None` for the `last_updated` field:\r\n\r\nhttps://github.com/marshmallow-code/marshmallow/blob/69270215ab9275dc566b010ecdb8777c186aa776/src/marshmallow/fields.py#L411-L420\r\n\r\nThis happens since that field\u2019s `.parent` is the `DocumentSchema` class, which *does* have a `.parent` attribute. However that attribute is a `Nested` instance, not another schema as expected\nReturn a field\u2019s root schema as soon as it is found\nThis prevents accessing a schema\u2019s `.parent` attribute if it has one (e.g. a field called `parent`)\r\n\r\nFixes #1808, I think.\n", "hints_text": "\nThanks @flying-sheep. This looks correct. Do you have time to write a regression test for this? If not, I can do it myself when I'm off the clock (this weekend, probably). Let me know either way", "created_at": "2021-05-10T18:53:41Z", "version": "3.12", "FAIL_TO_PASS": ["tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root"], "PASS_TO_PASS": ["tests/test_fields.py::test_field_aliases[Integer-Integer]", "tests/test_fields.py::test_field_aliases[String-String]", "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", "tests/test_fields.py::test_field_aliases[Url-Url]", "tests/test_fields.py::TestField::test_repr", "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_simple_field_root", "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", "tests/test_fields.py::TestErrorMessages::test_make_error[required-Missing", "tests/test_fields.py::TestErrorMessages::test_make_error[null-Field", "tests/test_fields.py::TestErrorMessages::test_make_error[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_make_error[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_fail[required-Missing", "tests/test_fields.py::TestErrorMessages::test_fail[null-Field", "tests/test_fields.py::TestErrorMessages::test_fail[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_fail[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", "tests/test_fields.py::TestNestedField::test_ordered_instanced_nested_schema_only_and_exclude[only-fields_list0]", "tests/test_fields.py::TestNestedField::test_ordered_instanced_nested_schema_only_and_exclude[exclude-fields_list1]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested"], "environment_setup_commit": "23d0551569d748460c504af85996451edd685371"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1702", "base_commit": "fa6c7379468f59d4568e29cbbeb06b797d656215", "patch": "diff --git a/src/marshmallow/fields.py b/src/marshmallow/fields.py\n--- a/src/marshmallow/fields.py\n+++ b/src/marshmallow/fields.py\n@@ -101,7 +101,7 @@ class Field(FieldABC):\n its value will be present in the deserialized object. In the context of an\n HTTP API, this effectively marks the field as \"read-only\".\n :param dict error_messages: Overrides for `Field.default_error_messages`.\n- :param metadata: Extra arguments to be stored as metadata.\n+ :param metadata: Extra information to be stored as field metadata.\n \n .. versionchanged:: 2.0.0\n Removed `error` parameter. Use ``error_messages`` instead.\n@@ -160,7 +160,8 @@ def __init__(\n load_only: bool = False,\n dump_only: bool = False,\n error_messages: typing.Optional[typing.Dict[str, str]] = None,\n- **metadata\n+ metadata: typing.Optional[typing.Mapping[str, typing.Any]] = None,\n+ **additional_metadata\n ) -> None:\n self.default = default\n self.attribute = attribute\n@@ -187,7 +188,16 @@ def __init__(\n raise ValueError(\"'missing' must not be set for required fields.\")\n self.required = required\n self.missing = missing\n- self.metadata = metadata\n+\n+ metadata = metadata or {}\n+ self.metadata = {**metadata, **additional_metadata}\n+ if additional_metadata:\n+ warnings.warn(\n+ \"Passing field metadata as a keyword arg is deprecated. Use the \"\n+ \"explicit `metadata=...` argument instead.\",\n+ RemovedInMarshmallow4Warning,\n+ )\n+\n self._creation_index = Field._creation_index\n Field._creation_index += 1\n \n", "test_patch": "diff --git a/tests/test_fields.py b/tests/test_fields.py\n--- a/tests/test_fields.py\n+++ b/tests/test_fields.py\n@@ -197,11 +197,27 @@ def test_extra_metadata_may_be_added_to_field(self, FieldClass): # noqa\n required=True,\n default=None,\n validate=lambda v: True,\n- description=\"foo\",\n- widget=\"select\",\n+ metadata={\"description\": \"foo\", \"widget\": \"select\"},\n )\n assert field.metadata == {\"description\": \"foo\", \"widget\": \"select\"}\n \n+ @pytest.mark.parametrize(\"FieldClass\", ALL_FIELDS)\n+ def test_field_metadata_added_in_deprecated_style_warns(self, FieldClass): # noqa\n+ # just the old style\n+ with pytest.warns(DeprecationWarning):\n+ field = FieldClass(description=\"Just a normal field.\")\n+ assert field.metadata[\"description\"] == \"Just a normal field.\"\n+ # mixed styles\n+ with pytest.warns(DeprecationWarning):\n+ field = FieldClass(\n+ required=True,\n+ default=None,\n+ validate=lambda v: True,\n+ description=\"foo\",\n+ metadata={\"widget\": \"select\"},\n+ )\n+ assert field.metadata == {\"description\": \"foo\", \"widget\": \"select\"}\n+\n \n class TestErrorMessages:\n class MyField(fields.Field):\n", "problem_statement": "RFC: Change the way we store metadata?\nUsers are often bit by the fact that fields store arbitrary keyword arguments as metadata. See https://github.com/marshmallow-code/marshmallow/issues/683.\r\n\r\n> ...The reasons we use **kwargs instead of e.g. `metadata=` are mostly historical. The original decision was that storing kwargs 1) was more concise and 2) saved us from having to come up with an appropriate name... \"metadata\" didn't seem right because there are use cases where the things your storing aren't really metadata. At this point, it's not worth breaking the API.\r\n\r\n> Not the best reasons, but I think it's not terrible. We've discussed adding a [whitelist of metadata keys](https://github.com/marshmallow-code/marshmallow/issues/683#issuecomment-385113845) in the past, but we decided it wasn't worth the added API surface.\r\n\r\n_Originally posted by @sloria in https://github.com/marshmallow-code/marshmallow/issues/779#issuecomment-522283135_\r\n\r\nPossible solutions:\r\n\r\n1. Use `metadata=`.\r\n2. Specify a whitelist of allowed metadata arguments.\r\n\r\nFeedback welcome!\n", "hints_text": "Solution 1. is preferable to 2., I think. That said, there are some use cases where it's awkward to call additional kwargs \"metadata\". `location` in webargs is one that comes to mind.\r\n\r\n```python\r\n# current API\r\n\"some_query_param\": fields.Bool(location=\"query\")\r\n```\r\n\r\nthough we could probably wrap all the fields in webargs to take the additional `location` argument. \ud83e\udd14 \nI wanted to note that even webargs' `location` doesn't necessarily make the case against `metadata=...`. I was surprised/confused at first when I went looking for `location` in marshmallow and found no mention of it. At the cost of a little bit of verbosity, it would make it easier to understand how marshmallow is functioning.\r\n\r\nRelatedly, the plan in https://github.com/marshmallow-code/webargs/issues/419 includes making `location=...` for webargs a thing of the past.\ncc @jtrakk . This was your suggestion in https://github.com/marshmallow-code/marshmallow/issues/779#issuecomment-522282845 . I'm leaning towards this more and more.\n+1 on this, IMHO biggest problem of `self.metadata=kwargs` is not that it's unexpected, but that it's not generating errors on wrong keyword arguments, which is pretty annoying due frequent api changes :-) so - you can find mistakes only later, all your typos in metadata field...\nOne one hand, I think it is better to specify `metadata=`. More explicit.\r\n\r\nOTOH, this will make my models a bit more verbose:\r\n\r\n```py\r\nclass MyModel(ma.Schema:\r\n some_int = ma.fields.Int(\r\n required=True,\r\n validate=ma.validate.OneOf([1, 2, 3]),\r\n metadata={\"description\": \"This string explains what this is all about\"}\r\n )\r\n```\r\n\r\nFor such a use case, the shortcut of using extra kwargs as metadata is nice.\r\n\r\nIf we went with solution 2, users would be able to extend the whitelist with their own stuff. Apispec could extend it with the keyword arguments it expects (valid OpenAPI attributes) and we could even catch typos inside metadata, while solution 1 blindly accepts anything in metadata.\r\n\r\nHowever, this would prevent accepting arbitrary attributes in metadata, which sucks. E.g. in apispec, we also accept any `\"x-...\"` attribute. So we'd need to genericize the whitelist to a callable mechanism. And we end up with a gas factory feature while we wanted to make thing simple.\r\n\r\nOverall, perhaps the downside of 1 (model verbosity) is not that bad.\nAgreed. Consider this accepted.\r\n\r\nMy plan is to deprecate `metadata=kwargs` in a later 3.x release. Let's let the dust settle on v3 before bombarding users with DeprecationWarnings \ud83d\ude05 ", "created_at": "2020-12-02T20:37:47Z", "version": "3.9", "FAIL_TO_PASS": ["tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]"], "PASS_TO_PASS": ["tests/test_fields.py::test_field_aliases[Integer-Integer]", "tests/test_fields.py::test_field_aliases[String-String]", "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", "tests/test_fields.py::test_field_aliases[Url-Url]", "tests/test_fields.py::TestField::test_repr", "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", "tests/test_fields.py::TestParentAndName::test_simple_field_root", "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", "tests/test_fields.py::TestErrorMessages::test_make_error[required-Missing", "tests/test_fields.py::TestErrorMessages::test_make_error[null-Field", "tests/test_fields.py::TestErrorMessages::test_make_error[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_make_error[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_fail[required-Missing", "tests/test_fields.py::TestErrorMessages::test_fail[null-Field", "tests/test_fields.py::TestErrorMessages::test_fail[custom-Custom", "tests/test_fields.py::TestErrorMessages::test_fail[validator_failed-Invalid", "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", "tests/test_fields.py::TestNestedField::test_ordered_instanced_nested_schema_only_and_exclude[only-fields_list0]", "tests/test_fields.py::TestNestedField::test_ordered_instanced_nested_schema_only_and_exclude[exclude-fields_list1]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested"], "environment_setup_commit": "fa6c7379468f59d4568e29cbbeb06b797d656215"}, {"repo": "marshmallow-code/marshmallow", "instance_id": "marshmallow-code__marshmallow-1524", "base_commit": "7015fc4333a2f32cd58c3465296e834acd4496ff", "patch": "diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py\n--- a/src/marshmallow/validate.py\n+++ b/src/marshmallow/validate.py\n@@ -65,7 +65,7 @@ def _regex_generator(self, relative, require_tld):\n r'\\[?[A-F0-9]*:[A-F0-9:]+\\]?)', # ...or ipv6\n r'(?::\\d+)?', # optional port\n r')?' if relative else r'', # host is optional, allow for relative URLs\n- r'(?:/?|[/?]\\S+)$',\n+ r'(?:/?|[/?]\\S+)\\Z',\n )), re.IGNORECASE)\n \n def __call__(self, relative, require_tld):\n@@ -120,18 +120,18 @@ class Email(Validator):\n \"\"\"\n \n USER_REGEX = re.compile(\n- r\"(^[-!#$%&'*+/=?^`{}|~\\w]+(\\.[-!#$%&'*+/=?^`{}|~\\w]+)*$\" # dot-atom\n+ r\"(^[-!#$%&'*+/=?^`{}|~\\w]+(\\.[-!#$%&'*+/=?^`{}|~\\w]+)*\\Z\" # dot-atom\n # quoted-string\n r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]'\n- r'|\\\\[\\001-\\011\\013\\014\\016-\\177])*\"$)', re.IGNORECASE | re.UNICODE)\n+ r'|\\\\[\\001-\\011\\013\\014\\016-\\177])*\"\\Z)', re.IGNORECASE | re.UNICODE)\n \n DOMAIN_REGEX = re.compile(\n # domain\n r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+'\n- r'(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$'\n+ r'(?:[A-Z]{2,6}|[A-Z0-9-]{2,})\\Z'\n # literal form, ipv4 address (SMTP 4.1.3)\n r'|^\\[(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)'\n- r'(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\]$', re.IGNORECASE | re.UNICODE)\n+ r'(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\]\\Z', re.IGNORECASE | re.UNICODE)\n \n DOMAIN_WHITELIST = ('localhost',)\n \n", "test_patch": "diff --git a/tests/test_validate.py b/tests/test_validate.py\n--- a/tests/test_validate.py\n+++ b/tests/test_validate.py\n@@ -41,6 +41,7 @@ def test_url_absolute_valid(valid_url):\n 'http:/example.org',\n 'foo://example.org',\n '../icons/logo.gif',\n+ 'https://example.org\\n',\n 'abc',\n '..',\n '/',\n@@ -71,6 +72,7 @@ def test_url_relative_valid(valid_url):\n 'suppliers.html',\n '../icons/logo.gif',\n 'icons/logo.gif',\n+ 'http://example.org\\n',\n '../.../g',\n '...',\n '\\\\',\n@@ -98,6 +100,7 @@ def test_url_dont_require_tld_valid(valid_url):\n \n @pytest.mark.parametrize('invalid_url', [\n 'http//example',\n+ 'http://example\\n',\n 'http://.example.org',\n 'http:///foo/bar',\n 'http:// /foo/bar',\n@@ -165,6 +168,8 @@ def test_email_valid(valid_email):\n assert validator(valid_email) == valid_email\n \n @pytest.mark.parametrize('invalid_email', [\n+ 'niceandsimple\\[email protected]',\n+ '[email protected]\\n',\n 'a\"b(c)d,e:f;g<h>i[j\\\\k][email protected]',\n 'just\"not\"[email protected]',\n 'this is\"not\\[email protected]',\n", "problem_statement": "Incorrect Email Validation\nhttps://github.com/marshmallow-code/marshmallow/blob/fbe22eb47db5df64b2c4133f9a5cb6c6920e8dd2/src/marshmallow/validate.py#L136-L151\r\n\r\nThe email validation regex will match `[email protected]\\n`, `email\\[email protected]`, and `email\\[email protected]\\n`.\r\n\r\nThe issue is that `$` is used to match until the end of a string. Instead, `\\Z` should be used. - https://stackoverflow.com/a/48730645\r\n\r\nIt is possible that other validators might suffer from the same bug, so it would be good if other regexes were also checked.\r\n\r\nIt is unclear, but this may lead to a security vulnerability in some projects that use marshmallow (depending on how the validator is used), so a quick fix here might be helpful. In my quick look around I didn't notice anything critical, however, so I figured it would be fine to open this issue.\n", "hints_text": "`^` behaves as expected, but `$` also matches a \"string-ending newline\". This appears to be a holdover from POSIX that most languages have long abandoned as default behavior.\r\n\r\nThanks for reporting this @nbanmp. If you are interesting in contributing a MR, I would be happy to review it, otherwise I can pick this up as soon as I get a chance.\r\n\r\nAlso, can you provide any examples of using an email address in a way that would make this issue a security vulnerability? The best I can come up with is that it will terminate the email headers early and cause an email to be malformed or undeliverable, which would be a standard bug. Since the newline can only be at the very end of the string, this would not allow injecting additional headers into an email. If it does have security implications I can submit a CVE and flag the vulnerable versions on TideLift.\nI don't know if I would call this a vulnerability in marshmallow, but it might - in rare cases - allow for exploitation of certain vulnerabilities in other tools.\r\n\r\nThe most likely place this might result in a vulnerability is when verifying an email for authentication, and allowing multiple accounts with the same, but different emails.\r\n\r\nA minor form of this would be allowing the same email to be used multiple times in sites that want to prevent that.\r\n\r\nA more serious, but unlikely form of this would be something like:\r\n\r\nDepending on how emails are stored / used, whitespace around them might be stripped or not between sending emails, and checking emails. It's not a vulnerability in marshmallow itself, but it might result in inconsistencies in other apps lead to actual vulnerabilities.\r\n\r\n```python\r\nvalidateemail(email)\r\n\r\nif email in database:\r\n error()\r\nelse:\r\n saveaccount(email.strip(), password) # This might overwrite an account with the correct email\r\n```\r\n\r\nThis example is actually what I was thinking of, because I was looking through the code for CTFd, which had a similar vulnerability occurring with the username, and, if not for dumb luck (a random lack of .strip() / it being in a different place), the same vulnerability would have also been possible using the email, even though the email was invalid.\r\n", "created_at": "2020-02-26T20:55:30Z", "version": "2.20", "FAIL_TO_PASS": ["tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", "tests/test_validate.py::test_email_invalid[niceandsimple\\[email protected]]", "tests/test_validate.py::test_email_invalid[[email protected]\\n]"], "PASS_TO_PASS": ["tests/test_validate.py::test_url_absolute_valid[http://example.org]", "tests/test_validate.py::test_url_absolute_valid[https://example.org]", "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", "tests/test_validate.py::test_url_absolute_valid[http://2001:db8::ff00:42:8329]", "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", "tests/test_validate.py::test_url_absolute_valid[http://[email protected]]", "tests/test_validate.py::test_url_absolute_valid[http://user:[email protected]]", "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", "tests/test_validate.py::test_url_absolute_invalid[http:///]", "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", "tests/test_validate.py::test_url_absolute_invalid[abc]", "tests/test_validate.py::test_url_absolute_invalid[..]", "tests/test_validate.py::test_url_absolute_invalid[/]", "tests/test_validate.py::test_url_absolute_invalid[", "tests/test_validate.py::test_url_absolute_invalid[]", "tests/test_validate.py::test_url_absolute_invalid[None]", "tests/test_validate.py::test_url_relative_valid[http://example.org]", "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", "tests/test_validate.py::test_url_relative_invalid[http//example.org]", "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", "tests/test_validate.py::test_url_relative_invalid[../.../g]", "tests/test_validate.py::test_url_relative_invalid[...]", "tests/test_validate.py::test_url_relative_invalid[\\\\]", "tests/test_validate.py::test_url_relative_invalid[", "tests/test_validate.py::test_url_relative_invalid[]", "tests/test_validate.py::test_url_relative_invalid[None]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", "tests/test_validate.py::test_url_dont_require_tld_invalid[http://", "tests/test_validate.py::test_url_dont_require_tld_invalid[]", "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", "tests/test_validate.py::test_url_custom_scheme", "tests/test_validate.py::test_url_relative_and_custom_schemes", "tests/test_validate.py::test_url_custom_message", "tests/test_validate.py::test_url_repr", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[[email protected]]", "tests/test_validate.py::test_email_valid[\"[email protected]\"@example.com]", "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|[email protected]]", "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", "tests/test_validate.py::test_email_valid[jos\\[email protected]]", "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;g<h>i[j\\\\k][email protected]]", "tests/test_validate.py::test_email_invalid[just\"not\"[email protected]]", "tests/test_validate.py::test_email_invalid[this", "tests/test_validate.py::test_email_invalid[this\\\\", "tests/test_validate.py::test_email_invalid[\"much.more", "tests/test_validate.py::test_email_invalid[\"very.(),:;<>[]\".VERY.\"very@\\\\", "tests/test_validate.py::test_email_invalid[\"", "tests/test_validate.py::test_email_invalid[user@example]", "tests/test_validate.py::test_email_invalid[@nouser.com]", "tests/test_validate.py::test_email_invalid[example.com]", "tests/test_validate.py::test_email_invalid[user]", "tests/test_validate.py::test_email_invalid[]", "tests/test_validate.py::test_email_invalid[None]", "tests/test_validate.py::test_email_custom_message", "tests/test_validate.py::test_email_repr", "tests/test_validate.py::test_range_min", "tests/test_validate.py::test_range_max", "tests/test_validate.py::test_range_custom_message", "tests/test_validate.py::test_range_repr", "tests/test_validate.py::test_length_min", "tests/test_validate.py::test_length_max", "tests/test_validate.py::test_length_equal", "tests/test_validate.py::test_length_custom_message", "tests/test_validate.py::test_length_repr", "tests/test_validate.py::test_equal", "tests/test_validate.py::test_equal_custom_message", "tests/test_validate.py::test_equal_repr", "tests/test_validate.py::test_regexp_str", "tests/test_validate.py::test_regexp_compile", "tests/test_validate.py::test_regexp_custom_message", "tests/test_validate.py::test_regexp_repr", "tests/test_validate.py::test_predicate", "tests/test_validate.py::test_predicate_custom_message", "tests/test_validate.py::test_predicate_repr", "tests/test_validate.py::test_noneof", "tests/test_validate.py::test_noneof_custom_message", "tests/test_validate.py::test_noneof_repr", "tests/test_validate.py::test_oneof", "tests/test_validate.py::test_oneof_options", "tests/test_validate.py::test_oneof_text", "tests/test_validate.py::test_oneof_custom_message", "tests/test_validate.py::test_oneof_repr", "tests/test_validate.py::test_containsonly_in_list", "tests/test_validate.py::test_contains_only_unhashable_types", "tests/test_validate.py::test_containsonly_in_tuple", "tests/test_validate.py::test_contains_only_in_string", "tests/test_validate.py::test_contains_only_invalid", "tests/test_validate.py::test_containsonly_custom_message", "tests/test_validate.py::test_containsonly_repr"], "environment_setup_commit": "7015fc4333a2f32cd58c3465296e834acd4496ff"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1160", "base_commit": "47654a073e0eb2b48b2ccdadb5cade9be0484b73", "patch": "diff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -2,7 +2,7 @@\n import pandas as pd\n \n from pvlib.tools import cosd, sind, tand\n-from pvlib.pvsystem import PVSystem\n+from pvlib.pvsystem import PVSystem, _unwrap_single_value\n from pvlib import irradiance, atmosphere\n \n \n@@ -169,6 +169,7 @@ def get_aoi(self, surface_tilt, surface_azimuth, solar_zenith,\n solar_zenith, solar_azimuth)\n return aoi\n \n+ @_unwrap_single_value\n def get_irradiance(self, surface_tilt, surface_azimuth,\n solar_zenith, solar_azimuth, dni, ghi, dhi,\n dni_extra=None, airmass=None, model='haydavies',\n@@ -221,16 +222,29 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n if airmass is None:\n airmass = atmosphere.get_relative_airmass(solar_zenith)\n \n- return irradiance.get_total_irradiance(surface_tilt,\n- surface_azimuth,\n- solar_zenith,\n- solar_azimuth,\n- dni, ghi, dhi,\n- dni_extra=dni_extra,\n- airmass=airmass,\n- model=model,\n- albedo=self.albedo,\n- **kwargs)\n+ # SingleAxisTracker only supports a single Array, but we need the\n+ # validate/iterate machinery so that single length tuple input/output\n+ # is handled the same as PVSystem.get_irradiance. GH 1159\n+ dni = self._validate_per_array(dni, system_wide=True)\n+ ghi = self._validate_per_array(ghi, system_wide=True)\n+ dhi = self._validate_per_array(dhi, system_wide=True)\n+\n+ return tuple(\n+ irradiance.get_total_irradiance(\n+ surface_tilt,\n+ surface_azimuth,\n+ solar_zenith,\n+ solar_azimuth,\n+ dni, ghi, dhi,\n+ dni_extra=dni_extra,\n+ airmass=airmass,\n+ model=model,\n+ albedo=self.albedo,\n+ **kwargs)\n+ for array, dni, ghi, dhi in zip(\n+ self.arrays, dni, ghi, dhi\n+ )\n+ )\n \n \n def singleaxis(apparent_zenith, apparent_azimuth,\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -726,6 +726,29 @@ def test_run_model_tracker(sapm_dc_snl_ac_system, location, weather, mocker):\n 'surface_tilt']).all()\n assert mc.results.ac[0] > 0\n assert np.isnan(mc.results.ac[1])\n+ assert isinstance(mc.results.dc, pd.DataFrame)\n+\n+\n+def test_run_model_tracker_list(\n+ sapm_dc_snl_ac_system, location, weather, mocker):\n+ system = SingleAxisTracker(\n+ module_parameters=sapm_dc_snl_ac_system.module_parameters,\n+ temperature_model_parameters=(\n+ sapm_dc_snl_ac_system.temperature_model_parameters\n+ ),\n+ inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters)\n+ mocker.spy(system, 'singleaxis')\n+ mc = ModelChain(system, location)\n+ mc.run_model([weather])\n+ assert system.singleaxis.call_count == 1\n+ assert (mc.results.tracking.columns == ['tracker_theta',\n+ 'aoi',\n+ 'surface_azimuth',\n+ 'surface_tilt']).all()\n+ assert mc.results.ac[0] > 0\n+ assert np.isnan(mc.results.ac[1])\n+ assert isinstance(mc.results.dc, tuple)\n+ assert len(mc.results.dc) == 1\n \n \n def test__assign_total_irrad(sapm_dc_snl_ac_system, location, weather,\n", "problem_statement": "ValueError: SingleAxisTracker, Array, and running the model on a tuple/list of weather\n**Describe the bug**\r\nI know a refactoring of the Array with single axis tracking is in the works #1146. In the meantime, a `ValueError` is raised when trying to run a SingleAxisTracker defined with an array and supplying (ghi, dni, dhi) weather as a tuple/list. I would expect calling `run_model([weather])` would work similarly to a modelchain for a fixed system with an array singleton. The error stems from `pvlib.tracking.SingleAxisTracker.get_irradiance` because most inputs are `pandas.Series`, but ghi, dhi, dni are `Tuple[Series]`.\r\n\r\n**To Reproduce**\r\n```python\r\nimport pandas as pd\r\nfrom pvlib.location import Location\r\nfrom pvlib.pvsystem import Array\r\nfrom pvlib.tracking import SingleAxisTracker\r\nfrom pvlib.modelchain import ModelChain\r\n\r\n\r\narray_params = {\r\n \"surface_tilt\": None,\r\n \"surface_azimuth\": None,\r\n \"module\": \"Canadian_Solar_Inc__CS5P_220M\",\r\n \"albedo\": 0.2,\r\n \"temperature_model_parameters\": {\r\n \"u_c\": 29.0,\r\n \"u_v\": 0.0,\r\n \"eta_m\": 0.1,\r\n \"alpha_absorption\": 0.9,\r\n },\r\n \"strings\": 5,\r\n \"modules_per_string\": 7,\r\n \"module_parameters\": {\r\n \"alpha_sc\": 0.004539,\r\n \"gamma_ref\": 1.2,\r\n \"mu_gamma\": -0.003,\r\n \"I_L_ref\": 5.11426,\r\n \"I_o_ref\": 8.10251e-10,\r\n \"R_sh_ref\": 381.254,\r\n \"R_sh_0\": 400.0,\r\n \"R_s\": 1.06602,\r\n \"cells_in_series\": 96,\r\n \"R_sh_exp\": 5.5,\r\n \"EgRef\": 1.121,\r\n },\r\n}\r\ninverter_parameters = {\r\n \"Paco\": 250.0,\r\n \"Pdco\": 259.589,\r\n \"Vdco\": 40.0,\r\n \"Pso\": 2.08961,\r\n \"C0\": -4.1e-05,\r\n \"C1\": -9.1e-05,\r\n \"C2\": 0.000494,\r\n \"C3\": -0.013171,\r\n \"Pnt\": 0.075,\r\n}\r\n\r\n\r\nlocation = Location(latitude=33.98, longitude=-115.323, altitude=2300)\r\n\r\n\r\ntracking = SingleAxisTracker(\r\n arrays=[Array(**array_params, name=0)],\r\n axis_tilt=0,\r\n axis_azimuth=180,\r\n gcr=0.1,\r\n backtrack=True,\r\n inverter_parameters=inverter_parameters,\r\n)\r\n\r\nweather = pd.DataFrame(\r\n {\r\n \"ghi\": [1100.0, 1101.0],\r\n \"dni\": [1000.0, 1001],\r\n \"dhi\": [100.0, 100],\r\n \"module_temperature\": [25.0, 25],\r\n },\r\n index=pd.DatetimeIndex(\r\n [pd.Timestamp(\"2021-01-20T12:00-05:00\"), pd.Timestamp(\"2021-01-20T12:05-05:00\")]\r\n ),\r\n)\r\nmc = ModelChain(\r\n tracking,\r\n location,\r\n aoi_model=\"no_loss\",\r\n spectral_model=\"no_loss\",\r\n)\r\nmc.run_model(weather) # OK\r\nmc.run_model([weather]) # ValueError\r\n\r\n```\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.9.0-alpha.2+2.g47654a0\r\n\n", "hints_text": "", "created_at": "2021-02-05T03:27:29Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_run_model_tracker_list"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_missing_poa", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1738", "base_commit": "275e6718caf7486cb5b7dcf29acd59499ad51f7f", "patch": "diff --git a/pvlib/soiling.py b/pvlib/soiling.py\n--- a/pvlib/soiling.py\n+++ b/pvlib/soiling.py\n@@ -10,7 +10,7 @@\n from pvlib.tools import cosd\n \n \n-def hsu(rainfall, cleaning_threshold, tilt, pm2_5, pm10,\n+def hsu(rainfall, cleaning_threshold, surface_tilt, pm2_5, pm10,\n depo_veloc=None, rain_accum_period=pd.Timedelta('1h')):\n \"\"\"\n Calculates soiling ratio given particulate and rain data using the\n@@ -30,7 +30,7 @@ def hsu(rainfall, cleaning_threshold, tilt, pm2_5, pm10,\n Amount of rain in an accumulation period needed to clean the PV\n modules. [mm]\n \n- tilt : float\n+ surface_tilt : numeric\n Tilt of the PV panels from horizontal. [degree]\n \n pm2_5 : numeric\n@@ -83,7 +83,7 @@ def hsu(rainfall, cleaning_threshold, tilt, pm2_5, pm10,\n horiz_mass_rate = (\n pm2_5 * depo_veloc['2_5'] + np.maximum(pm10 - pm2_5, 0.)\n * depo_veloc['10']) * dt_sec\n- tilted_mass_rate = horiz_mass_rate * cosd(tilt) # assuming no rain\n+ tilted_mass_rate = horiz_mass_rate * cosd(surface_tilt) # assuming no rain\n \n # tms -> tilt_mass_rate\n tms_cumsum = np.cumsum(tilted_mass_rate * np.ones(rainfall.shape))\n", "test_patch": "diff --git a/pvlib/tests/test_soiling.py b/pvlib/tests/test_soiling.py\n--- a/pvlib/tests/test_soiling.py\n+++ b/pvlib/tests/test_soiling.py\n@@ -92,7 +92,7 @@ def test_hsu_no_cleaning(rainfall_input, expected_output):\n tilt = 0.\n expected_no_cleaning = expected_output\n \n- result = hsu(rainfall=rainfall, cleaning_threshold=10., tilt=tilt,\n+ result = hsu(rainfall=rainfall, cleaning_threshold=10., surface_tilt=tilt,\n pm2_5=pm2_5, pm10=pm10, depo_veloc=depo_veloc,\n rain_accum_period=pd.Timedelta('1h'))\n assert_series_equal(result, expected_no_cleaning)\n@@ -108,7 +108,7 @@ def test_hsu(rainfall_input, expected_output_2):\n tilt = 0.\n \n # three cleaning events at 4:00-6:00, 8:00-11:00, and 17:00-20:00\n- result = hsu(rainfall=rainfall, cleaning_threshold=0.5, tilt=tilt,\n+ result = hsu(rainfall=rainfall, cleaning_threshold=0.5, surface_tilt=tilt,\n pm2_5=pm2_5, pm10=pm10, depo_veloc=depo_veloc,\n rain_accum_period=pd.Timedelta('3h'))\n \n@@ -120,8 +120,8 @@ def test_hsu_defaults(rainfall_input, expected_output_1):\n Test Soiling HSU function with default deposition velocity and default rain\n accumulation period.\n \"\"\"\n- result = hsu(rainfall=rainfall_input, cleaning_threshold=0.5, tilt=0.0,\n- pm2_5=1.0e-2, pm10=2.0e-2)\n+ result = hsu(rainfall=rainfall_input, cleaning_threshold=0.5,\n+ surface_tilt=0.0, pm2_5=1.0e-2, pm10=2.0e-2)\n assert np.allclose(result.values, expected_output_1)\n \n \n@@ -138,7 +138,7 @@ def test_hsu_variable_time_intervals(rainfall_input, expected_output_3):\n rain['new_time'] = rain.index + rain['mins_added']\n rain_var_times = rain.set_index('new_time').iloc[:, 0]\n result = hsu(\n- rainfall=rain_var_times, cleaning_threshold=0.5, tilt=50.0,\n+ rainfall=rain_var_times, cleaning_threshold=0.5, surface_tilt=50.0,\n pm2_5=1, pm10=2, depo_veloc=depo_veloc,\n rain_accum_period=pd.Timedelta('2h'))\n assert np.allclose(result, expected_output_3)\n", "problem_statement": "`pvlib.soiling.hsu` takes `tilt` instead of `surface_tilt`\n`pvlib.soiling.hsu` takes a `tilt` parameter representing the same thing we normally call `surface_tilt`:\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/7a2ec9b4765124463bf0ddd0a49dcfedc4cbcad7/pvlib/soiling.py#L13-L14\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/7a2ec9b4765124463bf0ddd0a49dcfedc4cbcad7/pvlib/soiling.py#L33-L34\r\n\r\nI don't see any good reason for this naming inconsistency (I suspect `tilt` just got copied from the matlab implementation) and suggest we rename the parameter to `surface_tilt` with a deprecation.\r\n\r\nAlso, the docstring parameter type description says it must be `float`, but the model's reference explicitly says time series tilt is allowed: \r\n\r\n> The angle is variable for tracking systems and is taken as the average angle over the time step.\r\n\r\n\n", "hints_text": "On second thought, I'm not seeing how this can be deprecated without reordering the parameters, which doesn't seem worth it to me. I'm inclined to rename it without deprecation in 0.10.0. ", "created_at": "2023-05-16T21:31:11Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_soiling.py::test_hsu_no_cleaning", "pvlib/tests/test_soiling.py::test_hsu", "pvlib/tests/test_soiling.py::test_hsu_defaults", "pvlib/tests/test_soiling.py::test_hsu_variable_time_intervals"], "PASS_TO_PASS": ["pvlib/tests/test_soiling.py::test_kimber_nowash", "pvlib/tests/test_soiling.py::test_kimber_manwash", "pvlib/tests/test_soiling.py::test_kimber_norain", "pvlib/tests/test_soiling.py::test_kimber_initial_soil"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1782", "base_commit": "0bc5a53dedd8aa9e553c732a31003ce020bc2f54", "patch": "diff --git a/pvlib/singlediode.py b/pvlib/singlediode.py\n--- a/pvlib/singlediode.py\n+++ b/pvlib/singlediode.py\n@@ -794,6 +794,13 @@ def _lambertw(photocurrent, saturation_current, resistance_series,\n # Compute open circuit voltage\n v_oc = _lambertw_v_from_i(0., **params)\n \n+ # Set small elements <0 in v_oc to 0\n+ if isinstance(v_oc, np.ndarray):\n+ v_oc[(v_oc < 0) & (v_oc > -1e-12)] = 0.\n+ elif isinstance(v_oc, (float, int)):\n+ if v_oc < 0 and v_oc > -1e-12:\n+ v_oc = 0.\n+\n # Find the voltage, v_mp, where the power is maximized.\n # Start the golden section search at v_oc * 1.14\n p_mp, v_mp = _golden_sect_DataFrame(params, 0., v_oc * 1.14, _pwr_optfcn)\n", "test_patch": "diff --git a/pvlib/tests/test_singlediode.py b/pvlib/tests/test_singlediode.py\n--- a/pvlib/tests/test_singlediode.py\n+++ b/pvlib/tests/test_singlediode.py\n@@ -168,6 +168,19 @@ def test_singlediode_precision(method, precise_iv_curves):\n assert np.allclose(pc['i_xx'], outs['i_xx'], atol=1e-6, rtol=0)\n \n \n+def test_singlediode_lambert_negative_voc():\n+\n+ # Those values result in a negative v_oc out of `_lambertw_v_from_i`\n+ x = np.array([0., 1.480501e-11, 0.178, 8000., 1.797559])\n+ outs = pvsystem.singlediode(*x, method='lambertw')\n+ assert outs['v_oc'] == 0\n+\n+ # Testing for an array\n+ x = np.array([x, x]).T\n+ outs = pvsystem.singlediode(*x, method='lambertw')\n+ assert np.array_equal(outs['v_oc'], [0, 0])\n+\n+\n @pytest.mark.parametrize('method', ['lambertw'])\n def test_ivcurve_pnts_precision(method, precise_iv_curves):\n \"\"\"\n", "problem_statement": "_golden_sect_DataFrame changes in 0.9.4\n**Describe the bug**\r\n\r\n`0.9.4` introduced the following changes in the `_golden_sect_DataFrame`: We are checking `upper` and `lower` parameters and raise an error if `lower > upper`.\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/81598e4fa8a9bd8fadaa7544136579c44885b3d1/pvlib/tools.py#L344-L345\r\n\r\n`_golden_sect_DataFrame` is used by `_lambertw`:\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/81598e4fa8a9bd8fadaa7544136579c44885b3d1/pvlib/singlediode.py#L644-L649\r\n\r\nI often have slightly negative `v_oc` values (really close to 0) when running simulations (second number in the array below):\r\n```\r\narray([ 9.46949758e-16, -8.43546518e-15, 2.61042547e-15, 3.82769773e-15,\r\n 1.01292315e-15, 4.81308106e+01, 5.12484772e+01, 5.22675087e+01,\r\n 5.20708941e+01, 5.16481028e+01, 5.12364071e+01, 5.09209060e+01,\r\n 5.09076598e+01, 5.10187680e+01, 5.11328118e+01, 5.13997628e+01,\r\n 5.15121386e+01, 5.05621451e+01, 4.80488068e+01, 7.18224446e-15,\r\n 1.21386700e-14, 6.40136698e-16, 4.36081007e-16, 6.51236255e-15])\r\n```\r\n\r\nIf we have one negative number in a large timeseries, the simulation will crash which seems too strict.\r\n\r\n**Expected behavior**\r\n\r\nThat would be great to either:\r\n* Have this data check be less strict and allow for slightly negative numbers, which are not going to affect the quality of the results.\r\n* On `_lambertw`: Do not allow negative `v_oc` and set negative values to `np.nan`, so that the error is not triggered. It will be up to the upstream code (user) to manage those `np.nan`.\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: >= 0.9.4\r\n - ``pandas.__version__``: 1.5.3\r\n - python: 3.10.11\r\n\nsinglediode error with very low effective_irradiance\n**Describe the bug**\r\n\r\nSince pvlib 0.9.4 release (https://github.com/pvlib/pvlib-python/pull/1606) I get an error while running the single-diode model with some very low effective irradiance values.\r\n\r\n**To Reproduce**\r\n\r\n```python\r\nfrom pvlib import pvsystem\r\n\r\neffective_irradiance=1.341083e-17\r\ntemp_cell=13.7 \r\n\r\ncec_modules = pvsystem.retrieve_sam('CECMod')\r\ncec_module = cec_modules['Trina_Solar_TSM_300DEG5C_07_II_']\r\n\r\nmount = pvsystem.FixedMount()\r\narray = pvsystem.Array(mount=mount,\r\n module_parameters=cec_module)\r\n\r\nsystem = pvsystem.PVSystem(arrays=[array])\r\n\r\nparams = system.calcparams_cec(effective_irradiance, \r\n temp_cell)\r\n\r\nsystem.singlediode(*params)\r\n```\r\n\r\n```in _golden_sect_DataFrame(params, lower, upper, func, atol)\r\n 303 \"\"\"\r\n 304 Vectorized golden section search for finding maximum of a function of a\r\n 305 single variable.\r\n (...)\r\n 342 pvlib.singlediode._pwr_optfcn\r\n 343 \"\"\"\r\n 344 if np.any(upper - lower < 0.):\r\n--> 345 raise ValueError('upper >= lower is required')\r\n 347 phim1 = (np.sqrt(5) - 1) / 2\r\n 349 df = params\r\n\r\nValueError: upper >= lower is required\r\n```\r\n\r\n**Expected behavior**\r\nThis complicates the bifacial modeling procedure as `run_model_from_effective_irradiance` can be called with very low irradiance values estimated by pvfactors (at sunrise or sunset for instance). \r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.9.4\r\n - ``pandas.__version__``: 1.5.3\r\n - python: 3.10\r\n\r\n**Additional context**\r\n\r\nv_oc is negative in this case which causes the error. \r\n\r\n```python\r\nfrom pvlib.singlediode import _lambertw_v_from_i\r\nphotocurrent = params[0]\r\nsaturation_current = params[1]\r\nresistance_series = params[2]\r\nresistance_shunt = params[3]\r\nnNsVth = params[4]\r\nv_oc = _lambertw_v_from_i(resistance_shunt, resistance_series, nNsVth, 0.,\r\n saturation_current, photocurrent)\r\n```\r\n\n", "hints_text": "See #1673 \n@cedricleroy can you provide the inputs and function call that produced the negative `v_oc` shown above?\n@echedey-ls Thanks! I thought I checked for related issues, but apparently not enough \ud83d\ude04 \r\n\r\n@cwhanse Sure thing:\r\n\r\nRunning [`_lambertw_v_from_i` in `_lambertw`](https://github.com/pvlib/pvlib-python/blob/v0.9.4/pvlib/singlediode.py#L639-L641) with the following data:\r\n\r\n```\r\n resistance_shunt resistance_series nNsVth current saturation_current photocurrent v_oc\r\n0 8000.000000 0.178 1.797559 0.0 1.480501e-11 0.000000 8.306577e-16\r\n1 8000.000000 0.178 1.797048 0.0 1.456894e-11 0.000000 -7.399531e-15\r\n2 8000.000000 0.178 1.791427 0.0 1.220053e-11 0.000000 2.289847e-15\r\n3 8000.000000 0.178 1.789892 0.0 1.162201e-11 0.000000 3.357630e-15\r\n4 8000.000000 0.178 1.790915 0.0 1.200467e-11 0.000000 8.885291e-16\r\n5 7384.475098 0.178 1.796786 0.0 1.444902e-11 0.237291 4.222001e+01\r\n6 5023.829590 0.178 1.814643 0.0 2.524836e-11 1.458354 4.495480e+01\r\n7 2817.370605 0.178 1.841772 0.0 5.803733e-11 3.774055 4.584869e+01\r\n8 1943.591919 0.178 1.877364 0.0 1.682954e-10 6.225446 4.567622e+01\r\n9 1609.391479 0.178 1.910984 0.0 4.479085e-10 8.887444 4.530535e+01\r\n10 1504.273193 0.178 1.937034 0.0 9.402419e-10 11.248103 4.494422e+01\r\n11 1482.143799 0.178 1.951216 0.0 1.399556e-09 12.272360 4.466746e+01\r\n12 1485.013794 0.178 1.950762 0.0 1.381967e-09 12.114989 4.465584e+01\r\n13 1506.648315 0.178 1.942643 0.0 1.100982e-09 11.167084 4.475331e+01\r\n14 1580.780029 0.178 1.928508 0.0 7.387948e-10 9.350249 4.485334e+01\r\n15 1832.828735 0.178 1.901971 0.0 3.453772e-10 6.842797 4.508751e+01\r\n16 2604.075684 0.178 1.869294 0.0 1.325485e-10 4.191604 4.518609e+01\r\n17 4594.301270 0.178 1.844949 0.0 6.390201e-11 1.771347 4.435276e+01\r\n18 6976.270996 0.178 1.829467 0.0 3.987927e-11 0.409881 4.214808e+01\r\n19 8000.000000 0.178 1.821491 0.0 3.120619e-11 0.000000 6.300214e-15\r\n20 8000.000000 0.178 1.813868 0.0 2.464867e-11 0.000000 1.064796e-14\r\n21 8000.000000 0.178 1.809796 0.0 2.171752e-11 0.000000 5.615234e-16\r\n22 8000.000000 0.178 1.808778 0.0 2.103918e-11 0.000000 3.825272e-16\r\n23 8000.000000 0.178 1.806231 0.0 1.943143e-11 0.000000 5.712599e-15\r\n```\r\n\r\n[data.csv](https://github.com/pvlib/pvlib-python/files/11807543/data.csv)\r\n\r\n\n> If we have one negative number in a large timeseries, the simulation will crash which seems too strict.\r\n\r\nAgree this is not desirable.\r\n\r\nMy thoughts:\r\n\r\n1. We could insert `v_oc = np.maximum(v_oc, 0)` above this [line](https://github.com/pvlib/pvlib-python/blob/e643dc3f835c29b12b13d7375e33885dcb5d07c7/pvlib/singlediode.py#L649). That would preserve nan.\r\n2. I am reluctant to change `_lambertw_v_from_i`. That function's job is to solve the diode equation, which is valid for negative current. I don't think this function should make decisions about its solution. There will always be some degree of imprecision (currently it's around 10-13 or smaller, I think).\r\n3. I am also reluctant to change `_golden_sect_DataFrame` for similar reasons - the function's job should be to find a minimum using the golden section search. Complying with the `lower < upper` requirement is the job of the code that calls this function.\r\n\r\n\n1/ makes sense to me. I agree with the CONS for 2/ and 3/\r\n\r\nHappy to open a PR with 1. if that helps. \n> Happy to open a PR with 1. if that helps.\r\n\r\nThat is welcome. Because I'm cautious about junk values with larger magnitude being covered up by 0s, maybe \r\n\r\n```\r\nv_oc[(v_oc < 0) & (v_oc > 1e-12)] = 0.\r\n```\r\n\r\n\nThat's unexpected, thanks for reporting. \r\n\r\nI'll note that the negative Voc results from taking the difference of two very large but nearly equal numbers. It's likely limited to the CEC model, where the shunt resistance is inversely proportional to irradiance, which would be about 1e19 at photocurrent of 1e-17 for this case.\nNow this gets strange: the Voc value is positive with pvlib v0.9.3. The function involved `pvlib.singlediode._lambertw_v_from_i` hasn't changed for many releases. In both pvlib v0.9.3 and v0.9.4, in this calculation of Voc, the lambertw term overflows so the Voc value is computed using only python arithmetic operators and numpy.log.\r\n\r\nI'm starting to think the error depends on python and numpy versions.\nThe difference between 0.9.3 and 0.9.4 here may be due to slightly different values returned by `calcparams_cec`. Compare the output of `print(list(map(str, params)))`; I get slightly different saturation current values for the given example. Maybe the changed Boltzmann constant in #1617 is the cause?\n+1 to #1617 as the likely culprit. I get the positive/negative Voc values with the same python and numpy versions but different pvlib versions.\nTo illustrate the challenge, [this line](https://github.com/pvlib/pvlib-python/blob/f4d7c6e1c17b3fddba7cc49d39feed2a6fa0f30e/pvlib/singlediode.py#L566) computes the Voc.\r\n\r\nStripping out the indexing the computation is\r\n\r\n```\r\n V = (IL + I0 - I) / Gsh - \\\r\n I * Rs - a * lambertwterm\r\n```\r\nWith pvlib v0.9.4, Io is 7.145289906185543e-12. a is not affected, since a value of the Boltzmann contant is inherent in the a_ref value from the database. (IL + I0 - I) / Gsh is 107825185636.40567, I * Rs is 0, and a * lambertwterm is 107825185636.40569\r\n\r\nWith pvlib v0.9.3, Io is 7.145288699667595e-12. (IL + I0 - I) / Gsh is 107825167429.58397, I * Rs is 0, and a * lambertwterm is 107825167429.58395\r\n\r\nThe difference defining Voc is in the least significant digit.\r\n\nIncreasing the iterations that solve for lambertwterm doesn't fix this issue.\nThis smells to me like the inevitable error from accumulated round-off. \r\n\r\nFWIW, negative Voc can be achieved in 0.9.3 as well -- try the given example but with `effective_irradiance=1.e-18`. The difference is that before #1606, it led to nans and warnings instead of raising an error. \r\n\r\n\n@pasquierjb I recommend intercepting the effective irradiance and setting values to 0 which are below a minimum on the order of 1e-9 W/m2. That will propagate to shunt resistance = np.inf, which changes the calculation path in pvlib.singlediode and gives Voc=0.\r\n\r\nI'm not sure we'll be able to extend the numerical solution of the single diode equation to be accurate at very low but non-zero values of photocurrent (and/or enormous but finite values of shunt resistance.)\r\n\r\nI note that `pvlib.pvsystem.calcparams_desoto` doesn't like `effective_irradiance=0.` but is OK with `effective_irradiance=np.array([0.])`. Has to do with trapping and ignoring division by zero warnings and errors.\nHave you tried setting `method='newton'` instead of `'lambertw'`? https://pvlib-python.readthedocs.io/en/stable/reference/generated/pvlib.pvsystem.singlediode.html#pvlib-pvsystem-singlediode\nSetting `method='newton'` gets a solution to this case. `method` isn't available as a parameter of the `PVSystem.singlediode` method so @pasquierjb would need to change his workflow to use it. Something for us to consider adding.\nMy workaround for this issue was to first filter very low `effective_irradiance` values (`<1e-8`), and then filter `photocurrent` and `saturation_current` parameters when `effective_irradiance=0` and made them `=0`. This assures that you won't get negative `v_oc` values.", "created_at": "2023-06-26T14:46:54Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_singlediode.py::test_singlediode_lambert_negative_voc"], "PASS_TO_PASS": ["pvlib/tests/test_singlediode.py::test_method_spr_e20_327[brentq]", "pvlib/tests/test_singlediode.py::test_method_spr_e20_327[newton]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[brentq]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params1-recomb_params1-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params1-recomb_params1-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_transfer[newton-method_kwargs0]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_transfer[brentq-method_kwargs1]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_fails[newton-method_kwargs0]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_fails[brentq-method_kwargs1]", "pvlib/tests/test_singlediode.py::test_bishop88_full_output_kwarg[newton]", "pvlib/tests/test_singlediode.py::test_bishop88_full_output_kwarg[brentq]"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1719", "base_commit": "30c62e368529df01faa609d6b38456a7b0db9b53", "patch": "diff --git a/pvlib/ivtools/sdm.py b/pvlib/ivtools/sdm.py\n--- a/pvlib/ivtools/sdm.py\n+++ b/pvlib/ivtools/sdm.py\n@@ -942,7 +942,7 @@ def _update_io(voc, iph, io, rs, rsh, nnsvth):\n \n while maxerr > eps and k < niter:\n # Predict Voc\n- pvoc = v_from_i(rsh, rs, nnsvth, 0., tio, iph)\n+ pvoc = v_from_i(0., iph, tio, rs, rsh, nnsvth)\n \n # Difference in Voc\n dvoc = pvoc - voc\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -944,14 +944,17 @@ def singlediode(self, photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth,\n ivcurve_pnts=ivcurve_pnts)\n \n- def i_from_v(self, resistance_shunt, resistance_series, nNsVth, voltage,\n- saturation_current, photocurrent):\n+ def i_from_v(self, voltage, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth):\n \"\"\"Wrapper around the :py:func:`pvlib.pvsystem.i_from_v` function.\n \n- See :py:func:`pvsystem.i_from_v` for details\n+ See :py:func:`pvlib.pvsystem.i_from_v` for details.\n+\n+ .. versionchanged:: 0.10.0\n+ The function's arguments have been reordered.\n \"\"\"\n- return i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n- saturation_current, photocurrent)\n+ return i_from_v(voltage, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth)\n \n def get_ac(self, model, p_dc, v_dc=None):\n r\"\"\"Calculates AC power from p_dc using the inverter model indicated\n@@ -2962,8 +2965,8 @@ def max_power_point(photocurrent, saturation_current, resistance_series,\n return out\n \n \n-def v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n- saturation_current, photocurrent, method='lambertw'):\n+def v_from_i(current, photocurrent, saturation_current, resistance_series,\n+ resistance_shunt, nNsVth, method='lambertw'):\n '''\n Device voltage at the given device current for the single diode model.\n \n@@ -2977,18 +2980,34 @@ def v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n the caller's responsibility to ensure that the arguments are all float64\n and within the proper ranges.\n \n+ .. versionchanged:: 0.10.0\n+ The function's arguments have been reordered.\n+\n Parameters\n ----------\n- resistance_shunt : numeric\n- Shunt resistance in ohms under desired IV curve conditions.\n- Often abbreviated ``Rsh``.\n- 0 < resistance_shunt <= numpy.inf\n+ current : numeric\n+ The current in amperes under desired IV curve conditions.\n+\n+ photocurrent : numeric\n+ Light-generated current (photocurrent) in amperes under desired\n+ IV curve conditions. Often abbreviated ``I_L``.\n+ 0 <= photocurrent\n+\n+ saturation_current : numeric\n+ Diode saturation current in amperes under desired IV curve\n+ conditions. Often abbreviated ``I_0``.\n+ 0 < saturation_current\n \n resistance_series : numeric\n Series resistance in ohms under desired IV curve conditions.\n Often abbreviated ``Rs``.\n 0 <= resistance_series < numpy.inf\n \n+ resistance_shunt : numeric\n+ Shunt resistance in ohms under desired IV curve conditions.\n+ Often abbreviated ``Rsh``.\n+ 0 < resistance_shunt <= numpy.inf\n+\n nNsVth : numeric\n The product of three components. 1) The usual diode ideal factor\n (n), 2) the number of cells in series (Ns), and 3) the cell\n@@ -2999,19 +3018,6 @@ def v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n q is the charge of an electron (coulombs).\n 0 < nNsVth\n \n- current : numeric\n- The current in amperes under desired IV curve conditions.\n-\n- saturation_current : numeric\n- Diode saturation current in amperes under desired IV curve\n- conditions. Often abbreviated ``I_0``.\n- 0 < saturation_current\n-\n- photocurrent : numeric\n- Light-generated current (photocurrent) in amperes under desired\n- IV curve conditions. Often abbreviated ``I_L``.\n- 0 <= photocurrent\n-\n method : str\n Method to use: ``'lambertw'``, ``'newton'``, or ``'brentq'``. *Note*:\n ``'brentq'`` is limited to 1st quadrant only.\n@@ -3028,8 +3034,8 @@ def v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n '''\n if method.lower() == 'lambertw':\n return _singlediode._lambertw_v_from_i(\n- resistance_shunt, resistance_series, nNsVth, current,\n- saturation_current, photocurrent\n+ current, photocurrent, saturation_current, resistance_series,\n+ resistance_shunt, nNsVth\n )\n else:\n # Calculate points on the IV curve using either 'newton' or 'brentq'\n@@ -3050,33 +3056,49 @@ def v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n return V\n \n \n-def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n- saturation_current, photocurrent, method='lambertw'):\n+def i_from_v(voltage, photocurrent, saturation_current, resistance_series,\n+ resistance_shunt, nNsVth, method='lambertw'):\n '''\n Device current at the given device voltage for the single diode model.\n \n Uses the single diode model (SDM) as described in, e.g.,\n- Jain and Kapoor 2004 [1]_.\n+ Jain and Kapoor 2004 [1]_.\n The solution is per Eq 2 of [1] except when resistance_series=0,\n- in which case the explict solution for current is used.\n+ in which case the explict solution for current is used.\n Ideal device parameters are specified by resistance_shunt=np.inf and\n- resistance_series=0.\n+ resistance_series=0.\n Inputs to this function can include scalars and pandas.Series, but it is\n- the caller's responsibility to ensure that the arguments are all float64\n- and within the proper ranges.\n+ the caller's responsibility to ensure that the arguments are all float64\n+ and within the proper ranges.\n+\n+ .. versionchanged:: 0.10.0\n+ The function's arguments have been reordered.\n \n Parameters\n ----------\n- resistance_shunt : numeric\n- Shunt resistance in ohms under desired IV curve conditions.\n- Often abbreviated ``Rsh``.\n- 0 < resistance_shunt <= numpy.inf\n+ voltage : numeric\n+ The voltage in Volts under desired IV curve conditions.\n+\n+ photocurrent : numeric\n+ Light-generated current (photocurrent) in amperes under desired\n+ IV curve conditions. Often abbreviated ``I_L``.\n+ 0 <= photocurrent\n+\n+ saturation_current : numeric\n+ Diode saturation current in amperes under desired IV curve\n+ conditions. Often abbreviated ``I_0``.\n+ 0 < saturation_current\n \n resistance_series : numeric\n Series resistance in ohms under desired IV curve conditions.\n Often abbreviated ``Rs``.\n 0 <= resistance_series < numpy.inf\n \n+ resistance_shunt : numeric\n+ Shunt resistance in ohms under desired IV curve conditions.\n+ Often abbreviated ``Rsh``.\n+ 0 < resistance_shunt <= numpy.inf\n+\n nNsVth : numeric\n The product of three components. 1) The usual diode ideal factor\n (n), 2) the number of cells in series (Ns), and 3) the cell\n@@ -3087,19 +3109,6 @@ def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n q is the charge of an electron (coulombs).\n 0 < nNsVth\n \n- voltage : numeric\n- The voltage in Volts under desired IV curve conditions.\n-\n- saturation_current : numeric\n- Diode saturation current in amperes under desired IV curve\n- conditions. Often abbreviated ``I_0``.\n- 0 < saturation_current\n-\n- photocurrent : numeric\n- Light-generated current (photocurrent) in amperes under desired\n- IV curve conditions. Often abbreviated ``I_L``.\n- 0 <= photocurrent\n-\n method : str\n Method to use: ``'lambertw'``, ``'newton'``, or ``'brentq'``. *Note*:\n ``'brentq'`` is limited to 1st quadrant only.\n@@ -3116,8 +3125,8 @@ def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n '''\n if method.lower() == 'lambertw':\n return _singlediode._lambertw_i_from_v(\n- resistance_shunt, resistance_series, nNsVth, voltage,\n- saturation_current, photocurrent\n+ voltage, photocurrent, saturation_current, resistance_series,\n+ resistance_shunt, nNsVth\n )\n else:\n # Calculate points on the IV curve using either 'newton' or 'brentq'\ndiff --git a/pvlib/singlediode.py b/pvlib/singlediode.py\n--- a/pvlib/singlediode.py\n+++ b/pvlib/singlediode.py\n@@ -495,12 +495,12 @@ def _prepare_newton_inputs(i_or_v_tup, args, v0):\n return args, v0\n \n \n-def _lambertw_v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n- saturation_current, photocurrent):\n+def _lambertw_v_from_i(current, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth):\n # Record if inputs were all scalar\n output_is_scalar = all(map(np.isscalar,\n- [resistance_shunt, resistance_series, nNsVth,\n- current, saturation_current, photocurrent]))\n+ (current, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth)))\n \n # This transforms Gsh=1/Rsh, including ideal Rsh=np.inf into Gsh=0., which\n # is generally more numerically stable\n@@ -509,9 +509,9 @@ def _lambertw_v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n # Ensure that we are working with read-only views of numpy arrays\n # Turns Series into arrays so that we don't have to worry about\n # multidimensional broadcasting failing\n- Gsh, Rs, a, I, I0, IL = \\\n- np.broadcast_arrays(conductance_shunt, resistance_series, nNsVth,\n- current, saturation_current, photocurrent)\n+ I, IL, I0, Rs, Gsh, a = \\\n+ np.broadcast_arrays(current, photocurrent, saturation_current,\n+ resistance_series, conductance_shunt, nNsVth)\n \n # Intitalize output V (I might not be float64)\n V = np.full_like(I, np.nan, dtype=np.float64)\n@@ -572,12 +572,12 @@ def _lambertw_v_from_i(resistance_shunt, resistance_series, nNsVth, current,\n return V\n \n \n-def _lambertw_i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n- saturation_current, photocurrent):\n+def _lambertw_i_from_v(voltage, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth):\n # Record if inputs were all scalar\n output_is_scalar = all(map(np.isscalar,\n- [resistance_shunt, resistance_series, nNsVth,\n- voltage, saturation_current, photocurrent]))\n+ (voltage, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth)))\n \n # This transforms Gsh=1/Rsh, including ideal Rsh=np.inf into Gsh=0., which\n # is generally more numerically stable\n@@ -586,9 +586,9 @@ def _lambertw_i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n # Ensure that we are working with read-only views of numpy arrays\n # Turns Series into arrays so that we don't have to worry about\n # multidimensional broadcasting failing\n- Gsh, Rs, a, V, I0, IL = \\\n- np.broadcast_arrays(conductance_shunt, resistance_series, nNsVth,\n- voltage, saturation_current, photocurrent)\n+ V, IL, I0, Rs, Gsh, a = \\\n+ np.broadcast_arrays(voltage, photocurrent, saturation_current,\n+ resistance_series, conductance_shunt, nNsVth)\n \n # Intitalize output I (V might not be float64)\n I = np.full_like(V, np.nan, dtype=np.float64) # noqa: E741, N806\n@@ -632,36 +632,29 @@ def _lambertw_i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n \n def _lambertw(photocurrent, saturation_current, resistance_series,\n resistance_shunt, nNsVth, ivcurve_pnts=None):\n+ # collect args\n+ params = {'photocurrent': photocurrent,\n+ 'saturation_current': saturation_current,\n+ 'resistance_series': resistance_series,\n+ 'resistance_shunt': resistance_shunt, 'nNsVth': nNsVth}\n+\n # Compute short circuit current\n- i_sc = _lambertw_i_from_v(resistance_shunt, resistance_series, nNsVth, 0.,\n- saturation_current, photocurrent)\n+ i_sc = _lambertw_i_from_v(0., **params)\n \n # Compute open circuit voltage\n- v_oc = _lambertw_v_from_i(resistance_shunt, resistance_series, nNsVth, 0.,\n- saturation_current, photocurrent)\n-\n- params = {'r_sh': resistance_shunt,\n- 'r_s': resistance_series,\n- 'nNsVth': nNsVth,\n- 'i_0': saturation_current,\n- 'i_l': photocurrent}\n+ v_oc = _lambertw_v_from_i(0., **params)\n \n # Find the voltage, v_mp, where the power is maximized.\n # Start the golden section search at v_oc * 1.14\n- p_mp, v_mp = _golden_sect_DataFrame(params, 0., v_oc * 1.14,\n- _pwr_optfcn)\n+ p_mp, v_mp = _golden_sect_DataFrame(params, 0., v_oc * 1.14, _pwr_optfcn)\n \n # Find Imp using Lambert W\n- i_mp = _lambertw_i_from_v(resistance_shunt, resistance_series, nNsVth,\n- v_mp, saturation_current, photocurrent)\n+ i_mp = _lambertw_i_from_v(v_mp, **params)\n \n # Find Ix and Ixx using Lambert W\n- i_x = _lambertw_i_from_v(resistance_shunt, resistance_series, nNsVth,\n- 0.5 * v_oc, saturation_current, photocurrent)\n+ i_x = _lambertw_i_from_v(0.5 * v_oc, **params)\n \n- i_xx = _lambertw_i_from_v(resistance_shunt, resistance_series, nNsVth,\n- 0.5 * (v_oc + v_mp), saturation_current,\n- photocurrent)\n+ i_xx = _lambertw_i_from_v(0.5 * (v_oc + v_mp), **params)\n \n out = (i_sc, v_oc, i_mp, v_mp, p_mp, i_x, i_xx)\n \n@@ -670,9 +663,7 @@ def _lambertw(photocurrent, saturation_current, resistance_series,\n ivcurve_v = (np.asarray(v_oc)[..., np.newaxis] *\n np.linspace(0, 1, ivcurve_pnts))\n \n- ivcurve_i = _lambertw_i_from_v(resistance_shunt, resistance_series,\n- nNsVth, ivcurve_v.T, saturation_current,\n- photocurrent).T\n+ ivcurve_i = _lambertw_i_from_v(ivcurve_v.T, **params).T\n \n out += (ivcurve_i, ivcurve_v)\n \n@@ -684,7 +675,9 @@ def _pwr_optfcn(df, loc):\n Function to find power from ``i_from_v``.\n '''\n \n- I = _lambertw_i_from_v(df['r_sh'], df['r_s'], # noqa: E741, N806\n- df['nNsVth'], df[loc], df['i_0'], df['i_l'])\n+ current = _lambertw_i_from_v(df[loc], df['photocurrent'],\n+ df['saturation_current'],\n+ df['resistance_series'],\n+ df['resistance_shunt'], df['nNsVth'])\n \n- return I * df[loc]\n+ return current * df[loc]\ndiff --git a/pvlib/tools.py b/pvlib/tools.py\n--- a/pvlib/tools.py\n+++ b/pvlib/tools.py\n@@ -346,7 +346,7 @@ def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8):\n \n phim1 = (np.sqrt(5) - 1) / 2\n \n- df = params\n+ df = params.copy() # shallow copy to avoid modifying caller's dict\n df['VH'] = upper\n df['VL'] = lower\n \n", "test_patch": "diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -1079,11 +1079,12 @@ def test_v_from_i(fixture_v_from_i, method, atol):\n IL = fixture_v_from_i['IL']\n V_expected = fixture_v_from_i['V_expected']\n \n- V = pvsystem.v_from_i(Rsh, Rs, nNsVth, I, I0, IL, method=method)\n- assert(isinstance(V, type(V_expected)))\n- if isinstance(V, type(np.ndarray)):\n- assert(isinstance(V.dtype, type(V_expected.dtype)))\n- assert(V.shape == V_expected.shape)\n+ V = pvsystem.v_from_i(I, IL, I0, Rs, Rsh, nNsVth, method=method)\n+\n+ assert isinstance(V, type(V_expected))\n+ if isinstance(V, np.ndarray):\n+ assert isinstance(V.dtype, type(V_expected.dtype))\n+ assert V.shape == V_expected.shape\n assert_allclose(V, V_expected, atol=atol)\n \n \n@@ -1092,7 +1093,7 @@ def test_i_from_v_from_i(fixture_v_from_i):\n Rsh = fixture_v_from_i['Rsh']\n Rs = fixture_v_from_i['Rs']\n nNsVth = fixture_v_from_i['nNsVth']\n- I = fixture_v_from_i['I']\n+ current = fixture_v_from_i['I']\n I0 = fixture_v_from_i['I0']\n IL = fixture_v_from_i['IL']\n V = fixture_v_from_i['V_expected']\n@@ -1100,15 +1101,17 @@ def test_i_from_v_from_i(fixture_v_from_i):\n # Convergence criteria\n atol = 1.e-11\n \n- I_expected = pvsystem.i_from_v(Rsh, Rs, nNsVth, V, I0, IL,\n+ I_expected = pvsystem.i_from_v(V, IL, I0, Rs, Rsh, nNsVth,\n method='lambertw')\n- assert_allclose(I, I_expected, atol=atol)\n- I = pvsystem.i_from_v(Rsh, Rs, nNsVth, V, I0, IL)\n- assert(isinstance(I, type(I_expected)))\n- if isinstance(I, type(np.ndarray)):\n- assert(isinstance(I.dtype, type(I_expected.dtype)))\n- assert(I.shape == I_expected.shape)\n- assert_allclose(I, I_expected, atol=atol)\n+ assert_allclose(current, I_expected, atol=atol)\n+\n+ current = pvsystem.i_from_v(V, IL, I0, Rs, Rsh, nNsVth)\n+\n+ assert isinstance(current, type(I_expected))\n+ if isinstance(current, np.ndarray):\n+ assert isinstance(current.dtype, type(I_expected.dtype))\n+ assert current.shape == I_expected.shape\n+ assert_allclose(current, I_expected, atol=atol)\n \n \n @pytest.fixture(params=[\n@@ -1197,41 +1200,42 @@ def test_i_from_v(fixture_i_from_v, method, atol):\n IL = fixture_i_from_v['IL']\n I_expected = fixture_i_from_v['I_expected']\n \n- I = pvsystem.i_from_v(Rsh, Rs, nNsVth, V, I0, IL, method=method)\n- assert(isinstance(I, type(I_expected)))\n- if isinstance(I, type(np.ndarray)):\n- assert(isinstance(I.dtype, type(I_expected.dtype)))\n- assert(I.shape == I_expected.shape)\n- assert_allclose(I, I_expected, atol=atol)\n+ current = pvsystem.i_from_v(V, IL, I0, Rs, Rsh, nNsVth, method=method)\n+\n+ assert isinstance(current, type(I_expected))\n+ if isinstance(current, np.ndarray):\n+ assert isinstance(current.dtype, type(I_expected.dtype))\n+ assert current.shape == I_expected.shape\n+ assert_allclose(current, I_expected, atol=atol)\n \n \n def test_PVSystem_i_from_v(mocker):\n system = pvsystem.PVSystem()\n m = mocker.patch('pvlib.pvsystem.i_from_v', autospec=True)\n- args = (20, 0.1, 0.5, 7.5049875193450521, 6e-7, 7)\n+ args = (7.5049875193450521, 7, 6e-7, 0.1, 20, 0.5)\n system.i_from_v(*args)\n m.assert_called_once_with(*args)\n \n \n def test_i_from_v_size():\n with pytest.raises(ValueError):\n- pvsystem.i_from_v(20, [0.1] * 2, 0.5, [7.5] * 3, 6.0e-7, 7.0)\n+ pvsystem.i_from_v([7.5] * 3, 7., 6e-7, [0.1] * 2, 20, 0.5)\n with pytest.raises(ValueError):\n- pvsystem.i_from_v(20, [0.1] * 2, 0.5, [7.5] * 3, 6.0e-7, 7.0,\n+ pvsystem.i_from_v([7.5] * 3, 7., 6e-7, [0.1] * 2, 20, 0.5,\n method='brentq')\n with pytest.raises(ValueError):\n- pvsystem.i_from_v(20, 0.1, 0.5, [7.5] * 3, 6.0e-7, np.array([7., 7.]),\n+ pvsystem.i_from_v([7.5] * 3, np.array([7., 7.]), 6e-7, 0.1, 20, 0.5,\n method='newton')\n \n \n def test_v_from_i_size():\n with pytest.raises(ValueError):\n- pvsystem.v_from_i(20, [0.1] * 2, 0.5, [3.0] * 3, 6.0e-7, 7.0)\n+ pvsystem.v_from_i([3.] * 3, 7., 6e-7, [0.1] * 2, 20, 0.5)\n with pytest.raises(ValueError):\n- pvsystem.v_from_i(20, [0.1] * 2, 0.5, [3.0] * 3, 6.0e-7, 7.0,\n+ pvsystem.v_from_i([3.] * 3, 7., 6e-7, [0.1] * 2, 20, 0.5,\n method='brentq')\n with pytest.raises(ValueError):\n- pvsystem.v_from_i(20, [0.1], 0.5, [3.0] * 3, 6.0e-7, np.array([7., 7.]),\n+ pvsystem.v_from_i([3.] * 3, np.array([7., 7.]), 6e-7, [0.1], 20, 0.5,\n method='newton')\n \n \n@@ -1328,8 +1332,8 @@ def test_singlediode_array():\n \n sd = pvsystem.singlediode(photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth)\n- expected = pvsystem.i_from_v(resistance_shunt, resistance_series, nNsVth,\n- sd['v_mp'], saturation_current, photocurrent,\n+ expected = pvsystem.i_from_v(sd['v_mp'], photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth,\n method='lambertw')\n assert_allclose(sd['i_mp'], expected, atol=1e-8)\n \n@@ -1404,20 +1408,19 @@ def test_singlediode_series_ivcurve(cec_module_params):\n [3.0107985972, 2.8841320056, 0.],\n [6.0072629615, 5.7462022810, 0.]]))])\n \n-\n for k, v in out.items():\n assert_allclose(v, expected[k], atol=1e-2)\n \n out = pvsystem.singlediode(IL, I0, Rs, Rsh, nNsVth, ivcurve_pnts=3)\n \n- expected['i_mp'] = pvsystem.i_from_v(Rsh, Rs, nNsVth, out['v_mp'], I0, IL,\n+ expected['i_mp'] = pvsystem.i_from_v(out['v_mp'], IL, I0, Rs, Rsh, nNsVth,\n method='lambertw')\n- expected['v_mp'] = pvsystem.v_from_i(Rsh, Rs, nNsVth, out['i_mp'], I0, IL,\n+ expected['v_mp'] = pvsystem.v_from_i(out['i_mp'], IL, I0, Rs, Rsh, nNsVth,\n method='lambertw')\n- expected['i'] = pvsystem.i_from_v(Rsh, Rs, nNsVth, out['v'].T, I0, IL,\n- method='lambertw').T\n- expected['v'] = pvsystem.v_from_i(Rsh, Rs, nNsVth, out['i'].T, I0, IL,\n- method='lambertw').T\n+ expected['i'] = pvsystem.i_from_v(out['v'].T, IL, I0, Rs, Rsh, nNsVth,\n+ method='lambertw').T\n+ expected['v'] = pvsystem.v_from_i(out['i'].T, IL, I0, Rs, Rsh, nNsVth,\n+ method='lambertw').T\n \n for k, v in out.items():\n assert_allclose(v, expected[k], atol=1e-6)\ndiff --git a/pvlib/tests/test_singlediode.py b/pvlib/tests/test_singlediode.py\n--- a/pvlib/tests/test_singlediode.py\n+++ b/pvlib/tests/test_singlediode.py\n@@ -25,22 +25,16 @@ def test_method_spr_e20_327(method, cec_module_spr_e20_327):\n I_L_ref=spr_e20_327['I_L_ref'], I_o_ref=spr_e20_327['I_o_ref'],\n R_sh_ref=spr_e20_327['R_sh_ref'], R_s=spr_e20_327['R_s'],\n EgRef=1.121, dEgdT=-0.0002677)\n- il, io, rs, rsh, nnsvt = x\n pvs = pvsystem.singlediode(*x, method='lambertw')\n out = pvsystem.singlediode(*x, method=method)\n- isc, voc, imp, vmp, pmp, ix, ixx = out.values()\n- assert np.isclose(pvs['i_sc'], isc)\n- assert np.isclose(pvs['v_oc'], voc)\n- # the singlediode method doesn't actually get the MPP correct\n- pvs_imp = pvsystem.i_from_v(rsh, rs, nnsvt, vmp, io, il, method='lambertw')\n- pvs_vmp = pvsystem.v_from_i(rsh, rs, nnsvt, imp, io, il, method='lambertw')\n- assert np.isclose(pvs_imp, imp)\n- assert np.isclose(pvs_vmp, vmp)\n- assert np.isclose(pvs['p_mp'], pmp)\n- assert np.isclose(pvs['i_x'], ix)\n- pvs_ixx = pvsystem.i_from_v(rsh, rs, nnsvt, (voc + vmp)/2, io, il,\n- method='lambertw')\n- assert np.isclose(pvs_ixx, ixx)\n+\n+ assert np.isclose(pvs['i_sc'], out['i_sc'])\n+ assert np.isclose(pvs['v_oc'], out['v_oc'])\n+ assert np.isclose(pvs['i_mp'], out['i_mp'])\n+ assert np.isclose(pvs['v_mp'], out['v_mp'])\n+ assert np.isclose(pvs['p_mp'], out['p_mp'])\n+ assert np.isclose(pvs['i_x'], out['i_x'])\n+ assert np.isclose(pvs['i_xx'], out['i_xx'])\n \n \n @pytest.mark.parametrize('method', ['brentq', 'newton'])\n@@ -53,23 +47,16 @@ def test_newton_fs_495(method, cec_module_fs_495):\n I_L_ref=fs_495['I_L_ref'], I_o_ref=fs_495['I_o_ref'],\n R_sh_ref=fs_495['R_sh_ref'], R_s=fs_495['R_s'],\n EgRef=1.475, dEgdT=-0.0003)\n- il, io, rs, rsh, nnsvt = x\n- x += (101, )\n pvs = pvsystem.singlediode(*x, method='lambertw')\n out = pvsystem.singlediode(*x, method=method)\n- isc, voc, imp, vmp, pmp, ix, ixx, i, v = out.values()\n- assert np.isclose(pvs['i_sc'], isc)\n- assert np.isclose(pvs['v_oc'], voc)\n- # the singlediode method doesn't actually get the MPP correct\n- pvs_imp = pvsystem.i_from_v(rsh, rs, nnsvt, vmp, io, il, method='lambertw')\n- pvs_vmp = pvsystem.v_from_i(rsh, rs, nnsvt, imp, io, il, method='lambertw')\n- assert np.isclose(pvs_imp, imp)\n- assert np.isclose(pvs_vmp, vmp)\n- assert np.isclose(pvs['p_mp'], pmp)\n- assert np.isclose(pvs['i_x'], ix)\n- pvs_ixx = pvsystem.i_from_v(rsh, rs, nnsvt, (voc + vmp)/2, io, il,\n- method='lambertw')\n- assert np.isclose(pvs_ixx, ixx)\n+\n+ assert np.isclose(pvs['i_sc'], out['i_sc'])\n+ assert np.isclose(pvs['v_oc'], out['v_oc'])\n+ assert np.isclose(pvs['i_mp'], out['i_mp'])\n+ assert np.isclose(pvs['v_mp'], out['v_mp'])\n+ assert np.isclose(pvs['p_mp'], out['p_mp'])\n+ assert np.isclose(pvs['i_x'], out['i_x'])\n+ assert np.isclose(pvs['i_xx'], out['i_xx'])\n \n \n def build_precise_iv_curve_dataframe(file_csv, file_json):\n", "problem_statement": "Match `pvsystem.i_from_v`, `v_from_i` single diode parameters with `singlediode` order.\n**Is your feature request related to a problem? Please describe.**\r\nThe single diode model parameters for `i_from_v`, `v_from_i` in `pvsystem` are expected in a different order than `pvsystem.singlediode`.\r\nThis makes it difficult to pass the parameters to all of these functions using `*args`.\r\n\r\n**Describe the solution you'd like**\r\nGroup and reorder the single diode parameters of `i_from_v`, `v_from_i` to match the order of `singlediode`.\r\n\n", "hints_text": "", "created_at": "2023-04-27T14:29:30Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve"], "PASS_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_Array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_type]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[temperature_model_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[albedo]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_tilt]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_azimuth]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[racking_model]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[modules_per_string]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[strings_per_inverter]", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]", "pvlib/tests/test_singlediode.py::test_method_spr_e20_327[brentq]", "pvlib/tests/test_singlediode.py::test_method_spr_e20_327[newton]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[brentq]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params1-recomb_params1-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params1-recomb_params1-888-55-expected1-tol1]"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1426", "base_commit": "1893b20a7b755004f561037161c242db24e2870c", "patch": "diff --git a/pvlib/forecast.py b/pvlib/forecast.py\n--- a/pvlib/forecast.py\n+++ b/pvlib/forecast.py\n@@ -15,6 +15,7 @@\n from siphon.ncss import NCSS\n \n import warnings\n+from pvlib._deprecation import deprecated\n \n \n warnings.warn(\n@@ -22,7 +23,15 @@\n 'The API may change, the functionality may be consolidated into an io '\n 'module, or the module may be separated into its own package.')\n \n+_forecast_deprecated = deprecated(\n+ since='0.9.1',\n+ removal='a future release',\n+ addendum='For details, see https://pvlib-python.readthedocs.io/en/stable/user_guide/forecasts.html' # noqa: E501\n+)\n \n+# don't decorate the base class to prevent the subclasses from showing\n+# duplicate warnings:\n+# @_forecast_deprecated\n class ForecastModel:\n \"\"\"\n An object for querying and holding forecast model information for\n@@ -684,6 +693,7 @@ def gust_to_speed(self, data, scaling=1/1.4):\n return wind_speed\n \n \n+@_forecast_deprecated\n class GFS(ForecastModel):\n \"\"\"\n Subclass of the ForecastModel class representing GFS\n@@ -785,6 +795,7 @@ def process_data(self, data, cloud_cover='total_clouds', **kwargs):\n return data[self.output_variables]\n \n \n+@_forecast_deprecated\n class HRRR_ESRL(ForecastModel): # noqa: N801\n \"\"\"\n Subclass of the ForecastModel class representing\n@@ -875,6 +886,7 @@ def process_data(self, data, cloud_cover='total_clouds', **kwargs):\n return data[self.output_variables]\n \n \n+@_forecast_deprecated\n class NAM(ForecastModel):\n \"\"\"\n Subclass of the ForecastModel class representing NAM\n@@ -956,6 +968,7 @@ def process_data(self, data, cloud_cover='total_clouds', **kwargs):\n return data[self.output_variables]\n \n \n+@_forecast_deprecated\n class HRRR(ForecastModel):\n \"\"\"\n Subclass of the ForecastModel class representing HRRR\n@@ -1044,6 +1057,7 @@ def process_data(self, data, cloud_cover='total_clouds', **kwargs):\n return data[self.output_variables]\n \n \n+@_forecast_deprecated\n class NDFD(ForecastModel):\n \"\"\"\n Subclass of the ForecastModel class representing NDFD forecast\n@@ -1112,6 +1126,7 @@ def process_data(self, data, **kwargs):\n return data[self.output_variables]\n \n \n+@_forecast_deprecated\n class RAP(ForecastModel):\n \"\"\"\n Subclass of the ForecastModel class representing RAP forecast model.\n", "test_patch": "diff --git a/pvlib/tests/test_forecast.py b/pvlib/tests/test_forecast.py\n--- a/pvlib/tests/test_forecast.py\n+++ b/pvlib/tests/test_forecast.py\n@@ -14,6 +14,8 @@\n )\n from .conftest import RERUNS, RERUNS_DELAY\n \n+from pvlib._deprecation import pvlibDeprecationWarning\n+\n pytestmark = pytest.mark.skipif(not has_siphon, reason='requires siphon')\n \n \n@@ -52,7 +54,8 @@\n @requires_siphon\n @pytest.fixture(scope='module', params=_modelclasses)\n def model(request):\n- amodel = request.param()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = request.param()\n try:\n raw_data = amodel.get_data(_latitude, _longitude, _start, _end)\n except Exception as e:\n@@ -90,7 +93,8 @@ def test_process_data(model):\n def test_bad_kwarg_get_data():\n # For more information on why you would want to pass an unknown keyword\n # argument, see Github issue #745.\n- amodel = NAM()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = NAM()\n data = amodel.get_data(_latitude, _longitude, _start, _end,\n bad_kwarg=False)\n assert not data.empty\n@@ -103,7 +107,8 @@ def test_bad_kwarg_get_data():\n def test_bad_kwarg_get_processed_data():\n # For more information on why you would want to pass an unknown keyword\n # argument, see Github issue #745.\n- amodel = NAM()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = NAM()\n data = amodel.get_processed_data(_latitude, _longitude, _start, _end,\n bad_kwarg=False)\n assert not data.empty\n@@ -114,7 +119,8 @@ def test_bad_kwarg_get_processed_data():\n @pytest.mark.remote_data\n @pytest.mark.flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY)\n def test_how_kwarg_get_processed_data():\n- amodel = NAM()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = NAM()\n data = amodel.get_processed_data(_latitude, _longitude, _start, _end,\n how='clearsky_scaling')\n assert not data.empty\n@@ -125,7 +131,8 @@ def test_how_kwarg_get_processed_data():\n @pytest.mark.remote_data\n @pytest.mark.flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY)\n def test_vert_level():\n- amodel = NAM()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = NAM()\n vert_level = 5000\n amodel.get_processed_data(_latitude, _longitude, _start, _end,\n vert_level=vert_level)\n@@ -136,7 +143,8 @@ def test_vert_level():\n @pytest.mark.remote_data\n @pytest.mark.flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY)\n def test_datetime():\n- amodel = NAM()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = NAM()\n start = datetime.now(tz=timezone.utc)\n end = start + timedelta(days=1)\n amodel.get_processed_data(_latitude, _longitude, start, end)\n@@ -147,7 +155,8 @@ def test_datetime():\n @pytest.mark.remote_data\n @pytest.mark.flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY)\n def test_queryvariables():\n- amodel = GFS()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = GFS()\n new_variables = ['u-component_of_wind_height_above_ground']\n data = amodel.get_data(_latitude, _longitude, _start, _end,\n query_variables=new_variables)\n@@ -156,16 +165,19 @@ def test_queryvariables():\n \n @requires_siphon\n def test_latest():\n- GFS(set_type='latest')\n+ with pytest.warns(pvlibDeprecationWarning):\n+ GFS(set_type='latest')\n \n \n @requires_siphon\n def test_full():\n- GFS(set_type='full')\n+ with pytest.warns(pvlibDeprecationWarning):\n+ GFS(set_type='full')\n \n \n def test_temp_convert():\n- amodel = GFS()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = GFS()\n data = pd.DataFrame({'temp_air': [273.15]})\n data['temp_air'] = amodel.kelvin_to_celsius(data['temp_air'])\n \n@@ -183,27 +195,31 @@ def test_temp_convert():\n \n \n def test_set_location():\n- amodel = GFS()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = GFS()\n latitude, longitude = 32.2, -110.9\n time = 'UTC'\n amodel.set_location(time, latitude, longitude)\n \n \n def test_set_query_time_range_tzfail():\n- amodel = GFS()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = GFS()\n with pytest.raises(TypeError):\n amodel.set_query_time_range(datetime.now(), datetime.now())\n \n \n def test_cloud_cover_to_transmittance_linear():\n- amodel = GFS()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = GFS()\n assert_allclose(amodel.cloud_cover_to_transmittance_linear(0), 0.75)\n assert_allclose(amodel.cloud_cover_to_transmittance_linear(100), 0.0)\n assert_allclose(amodel.cloud_cover_to_transmittance_linear(0, 0.5), 0.5)\n \n \n def test_cloud_cover_to_ghi_linear():\n- amodel = GFS()\n+ with pytest.warns(pvlibDeprecationWarning):\n+ amodel = GFS()\n ghi_clear = 1000\n offset = 25\n out = amodel.cloud_cover_to_ghi_linear(0, ghi_clear, offset=offset)\n", "problem_statement": "deprecate existing code in forecast.py, possibly replace with solarforecastarbiter shim\n`forecast.py` is a burden to maintain. I haven't used it in years, I don't think any of the other pvlib maintainers are interested in it, and I don't see any users stepping up to volunteer to maintain it. The code is not up to my present standards and I don't see how I'd get it there without a complete rewrite. This leads to difficult to track bugs such as the one recently reported on the [google group](https://groups.google.com/g/pvlib-python/c/b9HdgWV6w6g). It also complicates the pvlib dependencies.\r\n\r\n[solarforecastarbiter](https://github.com/SolarArbiter/solarforecastarbiter-core) includes a [reference_forecasts](https://github.com/SolarArbiter/solarforecastarbiter-core/tree/master/solarforecastarbiter/reference_forecasts) package that is much more robust. See [documentation here](https://solarforecastarbiter-core.readthedocs.io/en/latest/reference-forecasts.html) and [example notebook here](https://github.com/SolarArbiter/workshop/blob/master/reference_forecasts.ipynb) (no promises that this works without modification for the latest version).\r\n\r\nThe main reason to prefer `forecast.py` to `solarforecastarbiter` is the data fetch process. `forecast.py` pulls point data from a Unidata THREDDS server. `solarforecastarbiter.reference_forecasts` assumes you already have gridded data stored in a netcdf file. `solarforecastarbiter.io.nwp` provides functions to fetch that gridded data from NCEP. We have very good reasons for that approach in `solarforecastarbiter`, but I doubt that many `forecast.py` users are interested in configuring that two step process for their application.\r\n\r\nI'm very tempted to stop here, remove `forecast.py` after deprecation, and say \"not my problem anymore\", but it seems to attract a fair number of people to pvlib, so I hesitate to remove it without some kind of replacement. Let's explore a few ideas.\r\n\r\n1. Within `forecast.py`, rewrite code to fetch relevant data from Unidata. Make this function compatible with the expectations for the [`load_forecast`](https://github.com/SolarArbiter/solarforecastarbiter-core/blob/6200ec067bf83bc198a3af59da1d924d4124d4ec/solarforecastarbiter/reference_forecasts/models.py#L16-L19) function passed into `solarforecastarbiter.reference_forecasts.models` functions.\r\n2. Same as 1., except put that code somewhere else. Could be a documentation example, could be in solarforecastarbiter, or could be in a gist.\r\n3. Copy/refactor solarforecastarbiter code into `forecast.py`.\r\n4. Do nothing and let the forecast.py bugs and technical debt pile up. \r\n\r\nOther thoughts?\n", "hints_text": "I used these forecast functions earlier in my career for production forecasting (getting forecasted irradiance data). But that said, everything I used it for can be done with different tools (some already in pvlib). There are some good free/paid weather services out there that return weather forecast data, and pvlib already has functions to determine irradiance from cloud_coverage. \r\n\r\nWhile it could be tough for some to deprecate `forecast.py`, you have other tools that provide solutions and inputs. I have no problem with it being removed, especially if the amount of work to maintain is greater than the number of users who utilize it.\nProbably not a solution but I recently started a weather data service to more easily access time-series reanalysis (ERA5) and forecast data (GFS) (see example here - https://oikolab.com/documentation). It's currently going through beta testing but I've been thinking about how to offer some of the service to the open-source / academic community. \r\n\r\nIf you have any suggestion, would be more than happy to discuss.\nI've looked at the `forecast.py` code and I'm here to report a bug on it, so yeah, I see the problem.\r\n\r\nI count myself as a newbie user attracted to pvlib in part because of the forecasting. Even so I have no problem with it going away, as long as we have some examples of how to use a different tool for forecasting, if only to be pointed at the existence of the other tool.\r\n\r\nRegarding the ideas posted by @wholmgren. If you have no time to work on it, (4) is your only option. If not, you're clearly not in love with `forecast.py` (\"I have no problem in it going away\"), so I suggest you work toward deprecation and removal. For that, (2) seems the best approach. I also think (2) is the best approach to promote \"separation of concerns\": Getting and formatting the data seems like a useful piece of functionality by itself so it would be good if it existed as such, rather than buried in the `ForecastModel` class.\nI\u2019ve used `forecast.py` and have found it to be the most straightforward way to get data for pv production forecasting.\r\nI played around with `solarforecastarbiter` for around a day. There appear to be lots of interesting functionality to it but I found the expectation of having externally downloaded data outside of the library\u2019s API stored locally a hurdle to using it. Maybe I didn\u2019t give it the chance it deserved or maybe this is something a documentation example can/does solve, but I\u2019m just echoing your point that part of the allure of `forecast.py` is that it pulls the data for you from an external source, eliminating the need to deal with file management yourself, and allows you to stay within pvlib the whole time.\r\n\r\nA complete and simple forecasting example within pvlib is a powerful use case for the library. All that said, If the example uses some \u201clean\u201d code from `solarforecastarbiter` that\u2019s probably fine too.\npossibly of interest as an alternative data source: https://azure.microsoft.com/en-us/services/open-datasets/catalog/noaa-global-forecast-system/\nAfter a year and half of mostly following option 4 (`Do nothing and let the forecast.py bugs and technical debt pile up.`), and another release around the corner, maybe it's time to restart this discussion. @wholmgren, has the arbiter evolved in a way that changes any of your thoughts at the top of this thread?\r\n\r\nIf the data fetching code needs to live on somewhere, maybe `pvlib.iotools` is as good a place as any. However I'm not sure that will relieve the maintenance burden much -- of the dozen or so forecast issues opened in the last year, seems like the majority have to do with fetching data. The dependency complication is for the data fetching as well.\nMy initial reaction to every `forecast.py` issue remains \"remove it.\" Short of that, putting the fetch in `pvlib.iotools` and copying SFA's [`forecast.py`](https://github.com/SolarArbiter/solarforecastarbiter-core/blob/master/solarforecastarbiter/reference_forecasts/forecast.py) (either as a whole module or putting contents in other places like irradiance.py) feels like the best approach. I have no time or interest to maintain the original or any refactored code.\nI also have no interest in maintaining the original, maintaining a refactored version, or doing the refactor itself. I would be willing to deprecate the contents of `forecast.py` because it's easy and means less maintenance in the long run.\r\n\r\nAny objections to deprecating without replacement? Any objection to including the deprecation in 0.9.1?\nMy vote would be to move the code to a its own package but I'm with @wholmgren and @kanderso-nrel I don't have the bandwidth to maintain another project. Maybe we can canvas the user community for volunteers. I support deprecating `forecast.py` perhaps that will encourage someone to come forward to pick it up.", "created_at": "2022-03-14T18:37:44Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_forecast.py::test_latest", "pvlib/tests/test_forecast.py::test_full", "pvlib/tests/test_forecast.py::test_temp_convert", "pvlib/tests/test_forecast.py::test_set_location", "pvlib/tests/test_forecast.py::test_set_query_time_range_tzfail", "pvlib/tests/test_forecast.py::test_cloud_cover_to_transmittance_linear", "pvlib/tests/test_forecast.py::test_cloud_cover_to_ghi_linear"], "PASS_TO_PASS": [], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-807", "base_commit": "e326fa53038f616d949e4f981dab6187d2ca9470", "patch": "diff --git a/pvlib/scaling.py b/pvlib/scaling.py\nnew file mode 100644\n--- /dev/null\n+++ b/pvlib/scaling.py\n@@ -0,0 +1,242 @@\n+\"\"\"\n+The ``scaling`` module contains functions for manipulating irradiance\n+or other variables to account for temporal or spatial characteristics.\n+\"\"\"\n+\n+import numpy as np\n+import pandas as pd\n+\n+\n+def wvm(clearsky_index, positions, cloud_speed, dt=None):\n+ \"\"\"\n+ Compute spatial aggregation time series smoothing on clear sky index based\n+ on the Wavelet Variability model of Lave et al [1-2]. Implementation is\n+ basically a port of the Matlab version of the code [3].\n+\n+ Parameters\n+ ----------\n+ clearsky_index : numeric or pandas.Series\n+ Clear Sky Index time series that will be smoothed.\n+\n+ positions : numeric\n+ Array of coordinate distances as (x,y) pairs representing the\n+ easting, northing of the site positions in meters [m]. Distributed\n+ plants could be simulated by gridded points throughout the plant\n+ footprint.\n+\n+ cloud_speed : numeric\n+ Speed of cloud movement in meters per second [m/s].\n+\n+ dt : float, default None\n+ The time series time delta. By default, is inferred from the\n+ clearsky_index. Must be specified for a time series that doesn't\n+ include an index. Units of seconds [s].\n+\n+ Returns\n+ -------\n+ smoothed : numeric or pandas.Series\n+ The Clear Sky Index time series smoothed for the described plant.\n+\n+ wavelet: numeric\n+ The individual wavelets for the time series before smoothing.\n+\n+ tmscales: numeric\n+ The timescales associated with the wavelets in seconds [s].\n+\n+ References\n+ ----------\n+ [1] M. Lave, J. Kleissl and J.S. Stein. A Wavelet-Based Variability\n+ Model (WVM) for Solar PV Power Plants. IEEE Transactions on Sustainable\n+ Energy, vol. 4, no. 2, pp. 501-509, 2013.\n+\n+ [2] M. Lave and J. Kleissl. Cloud speed impact on solar variability\n+ scaling - Application to the wavelet variability model. Solar Energy,\n+ vol. 91, pp. 11-21, 2013.\n+\n+ [3] Wavelet Variability Model - Matlab Code:\n+ https://pvpmc.sandia.gov/applications/wavelet-variability-model/\n+ \"\"\"\n+\n+ # Added by Joe Ranalli (@jranalli), Penn State Hazleton, 2019\n+\n+ try:\n+ import scipy.optimize\n+ from scipy.spatial.distance import pdist\n+ except ImportError:\n+ raise ImportError(\"The WVM function requires scipy.\")\n+\n+ pos = np.array(positions)\n+ dist = pdist(pos, 'euclidean')\n+ wavelet, tmscales = _compute_wavelet(clearsky_index, dt)\n+\n+ # Find effective length of position vector, 'dist' is full pairwise\n+ n_pairs = len(dist)\n+\n+ def fn(x):\n+ return np.abs((x ** 2 - x) / 2 - n_pairs)\n+ n_dist = np.round(scipy.optimize.fmin(fn, np.sqrt(n_pairs), disp=False))\n+\n+ # Compute VR\n+ A = cloud_speed / 2 # Resultant fit for A from [2]\n+ vr = np.zeros(tmscales.shape)\n+ for i, tmscale in enumerate(tmscales):\n+ rho = np.exp(-1 / A * dist / tmscale) # Eq 5 from [1]\n+\n+ # 2*rho is because rho_ij = rho_ji. +n_dist accounts for sum(rho_ii=1)\n+ denominator = 2 * np.sum(rho) + n_dist\n+ vr[i] = n_dist ** 2 / denominator # Eq 6 of [1]\n+\n+ # Scale each wavelet by VR (Eq 7 in [1])\n+ wavelet_smooth = np.zeros_like(wavelet)\n+ for i in np.arange(len(tmscales)):\n+ if i < len(tmscales) - 1: # Treat the lowest freq differently\n+ wavelet_smooth[i, :] = wavelet[i, :] / np.sqrt(vr[i])\n+ else:\n+ wavelet_smooth[i, :] = wavelet[i, :]\n+\n+ outsignal = np.sum(wavelet_smooth, 0)\n+\n+ try: # See if there's an index already, if so, return as a pandas Series\n+ smoothed = pd.Series(outsignal, index=clearsky_index.index)\n+ except AttributeError:\n+ smoothed = outsignal # just output the numpy signal\n+\n+ return smoothed, wavelet, tmscales\n+\n+\n+def latlon_to_xy(coordinates):\n+ \"\"\"\n+ Convert latitude and longitude in degrees to a coordinate system measured\n+ in meters from zero deg latitude, zero deg longitude.\n+\n+ This is a convenience method to support inputs to wvm. Note that the\n+ methodology used is only suitable for short distances. For conversions of\n+ longer distances, users should consider use of Universal Transverse\n+ Mercator (UTM) or other suitable cartographic projection. Consider\n+ packages built for cartographic projection such as pyproj (e.g.\n+ pyproj.transform()) [2].\n+\n+ Parameters\n+ ----------\n+\n+ coordinates : numeric\n+ Array or list of (latitude, longitude) coordinate pairs. Use decimal\n+ degrees notation.\n+\n+ Returns\n+ -------\n+ xypos : numeric\n+ Array of coordinate distances as (x,y) pairs representing the\n+ easting, northing of the position in meters [m].\n+\n+ References\n+ ----------\n+ [1] H. Moritz. Geodetic Reference System 1980, Journal of Geodesy, vol. 74,\n+ no. 1, pp 128\u2013133, 2000.\n+\n+ [2] https://pypi.org/project/pyproj/\n+\n+ [3] Wavelet Variability Model - Matlab Code:\n+ https://pvpmc.sandia.gov/applications/wavelet-variability-model/\n+ \"\"\"\n+\n+ # Added by Joe Ranalli (@jranalli), Penn State Hazleton, 2019\n+\n+ r_earth = 6371008.7714 # mean radius of Earth, in meters\n+ m_per_deg_lat = r_earth * np.pi / 180\n+ try:\n+ meanlat = np.mean([lat for (lat, lon) in coordinates]) # Mean latitude\n+ except TypeError: # Assume it's a single value?\n+ meanlat = coordinates[0]\n+ m_per_deg_lon = r_earth * np.cos(np.pi/180 * meanlat) * np.pi/180\n+\n+ # Conversion\n+ pos = coordinates * np.array(m_per_deg_lat, m_per_deg_lon)\n+\n+ # reshape as (x,y) pairs to return\n+ try:\n+ return np.column_stack([pos[:, 1], pos[:, 0]])\n+ except IndexError: # Assume it's a single value, which has a 1D shape\n+ return np.array((pos[1], pos[0]))\n+\n+\n+def _compute_wavelet(clearsky_index, dt=None):\n+ \"\"\"\n+ Compute the wavelet transform on the input clear_sky time series.\n+\n+ Parameters\n+ ----------\n+ clearsky_index : numeric or pandas.Series\n+ Clear Sky Index time series that will be smoothed.\n+\n+ dt : float, default None\n+ The time series time delta. By default, is inferred from the\n+ clearsky_index. Must be specified for a time series that doesn't\n+ include an index. Units of seconds [s].\n+\n+ Returns\n+ -------\n+ wavelet: numeric\n+ The individual wavelets for the time series\n+\n+ tmscales: numeric\n+ The timescales associated with the wavelets in seconds [s]\n+\n+ References\n+ ----------\n+ [1] M. Lave, J. Kleissl and J.S. Stein. A Wavelet-Based Variability\n+ Model (WVM) for Solar PV Power Plants. IEEE Transactions on Sustainable\n+ Energy, vol. 4, no. 2, pp. 501-509, 2013.\n+\n+ [3] Wavelet Variability Model - Matlab Code:\n+ https://pvpmc.sandia.gov/applications/wavelet-variability-model/\n+ \"\"\"\n+\n+ # Added by Joe Ranalli (@jranalli), Penn State Hazleton, 2019\n+\n+ try: # Assume it's a pandas type\n+ vals = clearsky_index.values.flatten()\n+ except AttributeError: # Assume it's a numpy type\n+ vals = clearsky_index.flatten()\n+ if dt is None:\n+ raise ValueError(\"dt must be specified for numpy type inputs.\")\n+ else: # flatten() succeeded, thus it's a pandas type, so get its dt\n+ try: # Assume it's a time series type index\n+ dt = (clearsky_index.index[1] - clearsky_index.index[0]).seconds\n+ except AttributeError: # It must just be a numeric index\n+ dt = (clearsky_index.index[1] - clearsky_index.index[0])\n+\n+ # Pad the series on both ends in time and place in a dataframe\n+ cs_long = np.pad(vals, (len(vals), len(vals)), 'symmetric')\n+ cs_long = pd.DataFrame(cs_long)\n+\n+ # Compute wavelet time scales\n+ min_tmscale = np.ceil(np.log(dt)/np.log(2)) # Minimum wavelet timescale\n+ max_tmscale = int(12 - min_tmscale) # maximum wavelet timescale\n+\n+ tmscales = np.zeros(max_tmscale)\n+ csi_mean = np.zeros([max_tmscale, len(cs_long)])\n+ # Loop for all time scales we will consider\n+ for i in np.arange(0, max_tmscale):\n+ j = i+1\n+ tmscales[i] = 2**j * dt # Wavelet integration time scale\n+ intvlen = 2**j # Wavelet integration time series interval\n+ # Rolling average, retains only lower frequencies than interval\n+ df = cs_long.rolling(window=intvlen, center=True, min_periods=1).mean()\n+ # Fill nan's in both directions\n+ df = df.fillna(method='bfill').fillna(method='ffill')\n+ # Pop values back out of the dataframe and store\n+ csi_mean[i, :] = df.values.flatten()\n+\n+ # Calculate the wavelets by isolating the rolling mean frequency ranges\n+ wavelet_long = np.zeros(csi_mean.shape)\n+ for i in np.arange(0, max_tmscale-1):\n+ wavelet_long[i, :] = csi_mean[i, :] - csi_mean[i+1, :]\n+ wavelet_long[max_tmscale-1, :] = csi_mean[max_tmscale-1, :] # Lowest freq\n+\n+ # Clip off the padding and just return the original time window\n+ wavelet = np.zeros([max_tmscale, len(vals)])\n+ for i in np.arange(0, max_tmscale):\n+ wavelet[i, :] = wavelet_long[i, len(vals)+1: 2*len(vals)+1]\n+\n+ return wavelet, tmscales\n", "test_patch": "diff --git a/pvlib/test/test_scaling.py b/pvlib/test/test_scaling.py\nnew file mode 100644\n--- /dev/null\n+++ b/pvlib/test/test_scaling.py\n@@ -0,0 +1,146 @@\n+import numpy as np\n+import pandas as pd\n+\n+import pytest\n+from numpy.testing import assert_almost_equal\n+\n+from pvlib import scaling\n+from conftest import requires_scipy\n+\n+\n+# Sample cloud speed\n+cloud_speed = 5\n+\n+# Sample dt\n+dt = 1\n+\n+\[email protected]\n+def coordinates():\n+ # Sample positions in lat/lon\n+ lat = np.array((9.99, 10, 10.01))\n+ lon = np.array((4.99, 5, 5.01))\n+ coordinates = np.array([(lati, loni) for (lati, loni) in zip(lat, lon)])\n+ return coordinates\n+\n+\[email protected]\n+def clear_sky_index():\n+ # Generate a sample clear_sky_index\n+ clear_sky_index = np.ones(10000)\n+ clear_sky_index[5000:5005] = np.array([1, 1, 1.1, 0.9, 1])\n+ return clear_sky_index\n+\n+\[email protected]\n+def time(clear_sky_index):\n+ # Sample time vector\n+ return np.arange(0, len(clear_sky_index))\n+\n+\[email protected]\n+def positions():\n+ # Sample positions based on the previous lat/lon (calculated manually)\n+ expect_xpos = np.array([554863.4, 555975.4, 557087.3])\n+ expect_ypos = np.array([1110838.8, 1111950.8, 1113062.7])\n+ return np.array([pt for pt in zip(expect_xpos, expect_ypos)])\n+\n+\[email protected]\n+def expect_tmscale():\n+ # Expected timescales for dt = 1\n+ return [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]\n+\n+\[email protected]\n+def expect_wavelet():\n+ # Expected wavelet for indices 5000:5004 for clear_sky_index above (Matlab)\n+ return np.array([[-0.025, 0.05, 0., -0.05, 0.025],\n+ [0.025, 0., 0., 0., -0.025],\n+ [0., 0., 0., 0., 0.]])\n+\n+\[email protected]\n+def expect_cs_smooth():\n+ # Expected smoothed clear sky index for indices 5000:5004 (Matlab)\n+ return np.array([1., 1.0289, 1., 0.9711, 1.])\n+\n+\n+def test_latlon_to_xy_zero():\n+ coord = [0, 0]\n+ pos_e = [0, 0]\n+ pos = scaling.latlon_to_xy(coord)\n+ assert_almost_equal(pos, pos_e, decimal=1)\n+\n+\n+def test_latlon_to_xy_single(coordinates, positions):\n+ # Must test against central value, because latlon_to_xy uses the mean\n+ coord = coordinates[1]\n+ pos = scaling.latlon_to_xy(coord)\n+ assert_almost_equal(pos, positions[1], decimal=1)\n+\n+\n+def test_latlon_to_xy_array(coordinates, positions):\n+ pos = scaling.latlon_to_xy(coordinates)\n+ assert_almost_equal(pos, positions, decimal=1)\n+\n+\n+def test_latlon_to_xy_list(coordinates, positions):\n+ pos = scaling.latlon_to_xy(coordinates.tolist())\n+ assert_almost_equal(pos, positions, decimal=1)\n+\n+\n+def test_compute_wavelet_series(clear_sky_index, time,\n+ expect_tmscale, expect_wavelet):\n+ csi_series = pd.Series(clear_sky_index, index=time)\n+ wavelet, tmscale = scaling._compute_wavelet(csi_series)\n+ assert_almost_equal(tmscale, expect_tmscale)\n+ assert_almost_equal(wavelet[0:3, 5000:5005], expect_wavelet)\n+\n+\n+def test_compute_wavelet_series_numindex(clear_sky_index, time,\n+ expect_tmscale, expect_wavelet):\n+ dtindex = pd.to_datetime(time, unit='s')\n+ csi_series = pd.Series(clear_sky_index, index=dtindex)\n+ wavelet, tmscale = scaling._compute_wavelet(csi_series)\n+ assert_almost_equal(tmscale, expect_tmscale)\n+ assert_almost_equal(wavelet[0:3, 5000:5005], expect_wavelet)\n+\n+\n+def test_compute_wavelet_array(clear_sky_index,\n+ expect_tmscale, expect_wavelet):\n+ wavelet, tmscale = scaling._compute_wavelet(clear_sky_index, dt)\n+ assert_almost_equal(tmscale, expect_tmscale)\n+ assert_almost_equal(wavelet[0:3, 5000:5005], expect_wavelet)\n+\n+\n+def test_compute_wavelet_array_invalid(clear_sky_index):\n+ with pytest.raises(ValueError):\n+ scaling._compute_wavelet(clear_sky_index)\n+\n+\n+@requires_scipy\n+def test_wvm_series(clear_sky_index, time, positions, expect_cs_smooth):\n+ csi_series = pd.Series(clear_sky_index, index=time)\n+ cs_sm, _, _ = scaling.wvm(csi_series, positions, cloud_speed)\n+ assert_almost_equal(cs_sm[5000:5005], expect_cs_smooth, decimal=4)\n+\n+\n+@requires_scipy\n+def test_wvm_array(clear_sky_index, positions, expect_cs_smooth):\n+ cs_sm, _, _ = scaling.wvm(clear_sky_index, positions, cloud_speed, dt=dt)\n+ assert_almost_equal(cs_sm[5000:5005], expect_cs_smooth, decimal=4)\n+\n+\n+@requires_scipy\n+def test_wvm_series_xyaslist(clear_sky_index, time, positions,\n+ expect_cs_smooth):\n+ csi_series = pd.Series(clear_sky_index, index=time)\n+ cs_sm, _, _ = scaling.wvm(csi_series, positions.tolist(), cloud_speed)\n+ assert_almost_equal(cs_sm[5000:5005], expect_cs_smooth, decimal=4)\n+\n+\n+@requires_scipy\n+def test_wvm_invalid(clear_sky_index, positions):\n+ with pytest.raises(ValueError):\n+ scaling.wvm(clear_sky_index, positions, cloud_speed)\n", "problem_statement": "Add Wavelet Variability Model (WVM) for calculating spatial smoothing of irradiance\n> > Should I spin this off to a separate issue, since it might be different (and more compartmented) than the broader downscaling discussion?\r\n> \r\n> Yes. Let's start a new module with this submission, `scaling.py` comes to mind, but I'm not enamored of it. Scope will be functions that operate on irradiance, perhaps other variables, to transform temporal or spatial characteristics.\r\n\r\nSpinoff from [issue #788 ](https://github.com/pvlib/pvlib-python/issues/788). Implementation is a python port of WVM, released as an auxiliary to the Matlab pvlib [here](https://pvpmc.sandia.gov/applications/wavelet-variability-model/). My implementation ports the original model logic, but deviates from the overall package, in that I begin at the point where the user already has a clear sky index to operate on (original starts from GHI and calculates POA clear sky index). I thought this would allow for more flexibility in choice of transposition model, etc, but it does ask a bit more work up front for a user to run the WVM.\r\n\r\nI am close to completion of a draft and will create a pull request when ready. This is my first contribution to the project (or any open source project really), so please accept my apologies in advance if it takes some guidance.\n", "hints_text": "> This is my first contribution to the project (or any open source project really), so please accept my apologies in advance if it takes some guidance.\r\n\r\nWelcome! Asking for a clear-sky index as input seems appropriate; there's no need to rigidly follow the MATLAB implementation. I'll ask for your patience with the review process, which can involve multiple iterations and reviewers.", "created_at": "2019-11-01T14:54:52Z", "version": "0.6", "FAIL_TO_PASS": ["pvlib/test/test_scaling.py::test_latlon_to_xy_zero", "pvlib/test/test_scaling.py::test_latlon_to_xy_single", "pvlib/test/test_scaling.py::test_latlon_to_xy_array", "pvlib/test/test_scaling.py::test_latlon_to_xy_list", "pvlib/test/test_scaling.py::test_compute_wavelet_series", "pvlib/test/test_scaling.py::test_compute_wavelet_series_numindex", "pvlib/test/test_scaling.py::test_compute_wavelet_array", "pvlib/test/test_scaling.py::test_compute_wavelet_array_invalid", "pvlib/test/test_scaling.py::test_wvm_series", "pvlib/test/test_scaling.py::test_wvm_array", "pvlib/test/test_scaling.py::test_wvm_series_xyaslist", "pvlib/test/test_scaling.py::test_wvm_invalid"], "PASS_TO_PASS": [], "environment_setup_commit": "b91d178868d193afd56f8e3b013661a473d699c3"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1138", "base_commit": "56971c614e7faea3c24013445f1bf6ffe9943305", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -730,8 +730,33 @@ def pvsyst(self):\n return self._singlediode(self.system.calcparams_pvsyst)\n \n def pvwatts_dc(self):\n+ \"\"\"Calculate DC power using the PVWatts model.\n+\n+ Results are stored in ModelChain.results.dc. DC power is computed\n+ from PVSystem.module_parameters['pdc0'] and then scaled by\n+ PVSystem.modules_per_string and PVSystem.strings_per_inverter.\n+\n+ Returns\n+ -------\n+ self\n+\n+ See also\n+ --------\n+ pvlib.pvsystem.PVSystem.pvwatts_dc\n+ pvlib.pvsystem.PVSystem.scale_voltage_current_power\n+ \"\"\"\n self.results.dc = self.system.pvwatts_dc(\n self.results.effective_irradiance, self.results.cell_temperature)\n+ if isinstance(self.results.dc, tuple):\n+ temp = tuple(\n+ pd.DataFrame(s, columns=['p_mp']) for s in self.results.dc)\n+ else:\n+ temp = pd.DataFrame(self.results.dc, columns=['p_mp'])\n+ scaled = self.system.scale_voltage_current_power(temp)\n+ if isinstance(scaled, tuple):\n+ self.results.dc = tuple(s['p_mp'] for s in scaled)\n+ else:\n+ self.results.dc = scaled['p_mp']\n return self\n \n @property\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -891,7 +891,7 @@ def scale_voltage_current_power(self, data):\n Parameters\n ----------\n data: DataFrame or tuple of DataFrame\n- Must contain columns `'v_mp', 'v_oc', 'i_mp' ,'i_x', 'i_xx',\n+ May contain columns `'v_mp', 'v_oc', 'i_mp' ,'i_x', 'i_xx',\n 'i_sc', 'p_mp'`.\n \n Returns\n@@ -2626,13 +2626,13 @@ def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n \n def scale_voltage_current_power(data, voltage=1, current=1):\n \"\"\"\n- Scales the voltage, current, and power of the DataFrames\n- returned by :py:func:`singlediode` and :py:func:`sapm`.\n+ Scales the voltage, current, and power in data by the voltage\n+ and current factors.\n \n Parameters\n ----------\n data: DataFrame\n- Must contain columns `'v_mp', 'v_oc', 'i_mp' ,'i_x', 'i_xx',\n+ May contain columns `'v_mp', 'v_oc', 'i_mp' ,'i_x', 'i_xx',\n 'i_sc', 'p_mp'`.\n voltage: numeric, default 1\n The amount by which to multiply the voltages.\n@@ -2648,14 +2648,15 @@ def scale_voltage_current_power(data, voltage=1, current=1):\n \n # as written, only works with a DataFrame\n # could make it work with a dict, but it would be more verbose\n- data = data.copy()\n- voltages = ['v_mp', 'v_oc']\n- currents = ['i_mp', 'i_x', 'i_xx', 'i_sc']\n- data[voltages] *= voltage\n- data[currents] *= current\n- data['p_mp'] *= voltage * current\n-\n- return data\n+ voltage_keys = ['v_mp', 'v_oc']\n+ current_keys = ['i_mp', 'i_x', 'i_xx', 'i_sc']\n+ power_keys = ['p_mp']\n+ voltage_df = data.filter(voltage_keys, axis=1) * voltage\n+ current_df = data.filter(current_keys, axis=1) * current\n+ power_df = data.filter(power_keys, axis=1) * voltage * current\n+ df = pd.concat([voltage_df, current_df, power_df], axis=1)\n+ df_sorted = df[data.columns] # retain original column order\n+ return df_sorted\n \n \n def pvwatts_dc(g_poa_effective, temp_cell, pdc0, gamma_pdc, temp_ref=25.):\n@@ -2675,20 +2676,20 @@ def pvwatts_dc(g_poa_effective, temp_cell, pdc0, gamma_pdc, temp_ref=25.):\n Parameters\n ----------\n g_poa_effective: numeric\n- Irradiance transmitted to the PV cells in units of W/m**2. To be\n+ Irradiance transmitted to the PV cells. To be\n fully consistent with PVWatts, the user must have already\n applied angle of incidence losses, but not soiling, spectral,\n- etc.\n+ etc. [W/m^2]\n temp_cell: numeric\n- Cell temperature in degrees C.\n+ Cell temperature [C].\n pdc0: numeric\n- Power of the modules at 1000 W/m2 and cell reference temperature.\n+ Power of the modules at 1000 W/m^2 and cell reference temperature. [W]\n gamma_pdc: numeric\n- The temperature coefficient in units of 1/C. Typically -0.002 to\n- -0.005 per degree C.\n+ The temperature coefficient of power. Typically -0.002 to\n+ -0.005 per degree C. [1/C]\n temp_ref: numeric, default 25.0\n Cell reference temperature. PVWatts defines it to be 25 C and\n- is included here for flexibility.\n+ is included here for flexibility. [C]\n \n Returns\n -------\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -1180,6 +1180,25 @@ def test_dc_model_user_func(pvwatts_dc_pvwatts_ac_system, location, weather,\n assert not mc.results.ac.empty\n \n \n+def test_pvwatts_dc_multiple_strings(pvwatts_dc_pvwatts_ac_system, location,\n+ weather, mocker):\n+ system = pvwatts_dc_pvwatts_ac_system\n+ m = mocker.spy(system, 'scale_voltage_current_power')\n+ mc1 = ModelChain(system, location,\n+ aoi_model='no_loss', spectral_model='no_loss')\n+ mc1.run_model(weather)\n+ assert m.call_count == 1\n+ system.arrays[0].modules_per_string = 2\n+ mc2 = ModelChain(system, location,\n+ aoi_model='no_loss', spectral_model='no_loss')\n+ mc2.run_model(weather)\n+ assert isinstance(mc2.results.ac, (pd.Series, pd.DataFrame))\n+ assert not mc2.results.ac.empty\n+ expected = pd.Series(data=[2., np.nan], index=mc2.results.dc.index,\n+ name='p_mp')\n+ assert_series_equal(mc2.results.dc / mc1.results.dc, expected)\n+\n+\n def acdc(mc):\n mc.results.ac = mc.results.dc\n \n", "problem_statement": "document or support modules_per_string strings_per_inverter with pvwatts in modelchain\nHi, \r\n\r\nI am trying to run Modelchain with pvwatt model but it seems that the `modules_per_string` and `strings_per inverter ` doesn't have any affect on the total output. \r\n\r\nI am not sure why is it so. \r\nMay be ModelChain isn't supporting so. If that's the case how can I achieve the desired result?\r\n\r\nHere is my code: \r\n\r\nThanks in advance\r\n```\r\n# built-in python modules\r\nimport os\r\nimport inspect\r\n\r\n# scientific python add-ons\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# plotting stuff\r\n# first line makes the plots appear in the notebook\r\n%matplotlib inline \r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\n# seaborn makes your plots look better\r\ntry:\r\n import seaborn as sns\r\n sns.set(rc={\"figure.figsize\": (12, 6)})\r\n sns.set_color_codes()\r\nexcept ImportError:\r\n print('We suggest you install seaborn using conda or pip and rerun this cell')\r\n\r\n# finally, we import the pvlib library\r\nimport pvlib\r\n\r\ntmy = pd.read_csv(\"http://re.jrc.ec.europa.eu/pvgis5/tmy.php?lat=29.74&lon=40.10\")\r\n\r\ntmy.Date = pd.to_datetime(tmy.Date, format='%Y-%d-%m %H:%M:%S')\r\n\r\ntmy.rename(columns={' Ghor':'ghi','Dhor':'dhi','DNI':'dni','Tair':'temp_air',\r\n 'Ws':'wind_speed'},inplace=True)\t\t\t\t\t\r\n\t\t\t\t\t\t\r\ntmy.set_index(tmy['Date'],inplace=True)\r\n #Drop unnecessary column\r\n\r\ntmy = tmy.drop('Date', 1)\r\ntmy = tmy.drop('RH', 1)\r\ntmy = tmy.drop('IR', 1)\r\ntmy = tmy.drop(' Wd', 1)\r\ntmy = tmy.drop('Pres', 1)\r\n\r\n#module =Jinko_Solar_JKM320P_72_V\r\n#inverter = ABB__PVS980_58_2000kVA_K__N_A_V__CEC_2018_\r\n\r\nlat = 29.74\r\nlon = 40.10\r\naltitude = 676\r\ntz = 'Etc/GMT+3' \r\n\r\nloc = pvlib.location.Location(latitude=lat,longitude= lon,tz=tz)\r\n\r\n#model = pvwatts \r\npvwatts_system = pvlib.pvsystem.PVSystem(module_parameters={'pdc0': 320, 'gamma_pdc': -0.0041},inverter_parameters={'pdc' : 3200000, 'pdc0' : 2024292, 'eta_inv_nom':0.988, 'eta_inv_ref':0.986},surface_tilt = 20, surface_azimuth=0,\r\n modules_per_string=30,strings_per_inverter=267, albedo = 0.2)\r\n\t\t\t\t\t\r\nmc = pvlib.modelchain.ModelChain(pvwatts_system, loc, transposition_model =\"perez\",aoi_model = 'ashrae',spectral_model='no_loss')\r\nprint(mc)\r\nmc.run_model(times=tmy.index,weather=tmy)\r\na = mc.ac\r\na = pd.Series.to_frame(a)\r\na = a * 530 # 530 = number of inverters in the system \r\n\r\na['month'] = a.index\r\na.month = a.month.dt.month\r\nmonthly = a.groupby('month').sum()\r\n```\r\n\r\n\n", "hints_text": "https://stackoverflow.com/questions/49550656/run-pvlib-modelchain-with-pvwatts-model/50165303#50165303\r\n\r\nThe work around is to scale your ``module_parameters ['pdc0']``. Pull requests welcome for improving the functionality and/or documentation.\nIt seems that the system scaling provided by `PVSystem.scale_voltage_current_power()` is a system-level entity that should be included in `PVSystem.sapm()` and `PVSystem.singlediode()` computations, in addition to adding this to `PVSystem.pvwatts_dc()`. Currently, a higher level `ModelChain` function does this (except for pvwatts, as discussed above). If folks agree to this, then a question arises as to if the corresponding wrapped functions in `pvsystem.py` should still only calculate `singlediode()` for a single module/device instead of the whole system. (ATM, I think that they should.)\n@cwhanse we need this for SPI. Do you have any concern with adding this\r\n\r\n```python\r\n self.results.dc = self.system.scale_voltage_current_power(\r\n self.results.dc,\r\n unwrap=False\r\n )\r\n```\r\n\r\nto \r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/56971c614e7faea3c24013445f1bf6ffe9943305/pvlib/modelchain.py#L732-L735\r\n\r\n?\r\n\r\nOr do you think we should go ahead with @markcampanelli's suggestion above? I think @markcampanelli's suggestion is better on the merits but it's a much bigger change and I don't know how to do it in a way that wouldn't cause user code to return unexpected answers.\nI don't have a problem patching that into `pvlib.modelchain.ModelChain.pvwatts_dc`. I think it's an oversight that the scaling was left out, since it is included in the `sapm` and `singlediode` methods.\nI think we left it out because it's arguably a departure from the pvwatts model in which you're typically specifying the pdc0 of the entire system. But I don't see a problem with the extension within our data model.\nwant me to open a PR? Or have you got it?\nWould be great if you can do it.", "created_at": "2021-01-20T21:18:35Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_missing_poa", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1213", "base_commit": "40ba4bd5c8b91754aa73e638ed984ab9657847cd", "patch": "diff --git a/pvlib/scaling.py b/pvlib/scaling.py\n--- a/pvlib/scaling.py\n+++ b/pvlib/scaling.py\n@@ -13,8 +13,8 @@\n def wvm(clearsky_index, positions, cloud_speed, dt=None):\n \"\"\"\n Compute spatial aggregation time series smoothing on clear sky index based\n- on the Wavelet Variability model of Lave et al [1-2]. Implementation is\n- basically a port of the Matlab version of the code [3].\n+ on the Wavelet Variability model of Lave et al. [1]_, [2]_. Implementation\n+ is basically a port of the Matlab version of the code [3]_.\n \n Parameters\n ----------\n@@ -48,16 +48,16 @@ def wvm(clearsky_index, positions, cloud_speed, dt=None):\n \n References\n ----------\n- [1] M. Lave, J. Kleissl and J.S. Stein. A Wavelet-Based Variability\n- Model (WVM) for Solar PV Power Plants. IEEE Transactions on Sustainable\n- Energy, vol. 4, no. 2, pp. 501-509, 2013.\n+ .. [1] M. Lave, J. Kleissl and J.S. Stein. A Wavelet-Based Variability\n+ Model (WVM) for Solar PV Power Plants. IEEE Transactions on Sustainable\n+ Energy, vol. 4, no. 2, pp. 501-509, 2013.\n \n- [2] M. Lave and J. Kleissl. Cloud speed impact on solar variability\n- scaling - Application to the wavelet variability model. Solar Energy,\n- vol. 91, pp. 11-21, 2013.\n+ .. [2] M. Lave and J. Kleissl. Cloud speed impact on solar variability\n+ scaling - Application to the wavelet variability model. Solar Energy,\n+ vol. 91, pp. 11-21, 2013.\n \n- [3] Wavelet Variability Model - Matlab Code:\n- https://pvpmc.sandia.gov/applications/wavelet-variability-model/\n+ .. [3] Wavelet Variability Model - Matlab Code:\n+ https://github.com/sandialabs/wvm\n \"\"\"\n \n # Added by Joe Ranalli (@jranalli), Penn State Hazleton, 2019\n@@ -128,13 +128,13 @@ def latlon_to_xy(coordinates):\n \n References\n ----------\n- [1] H. Moritz. Geodetic Reference System 1980, Journal of Geodesy, vol. 74,\n- no. 1, pp 128\u2013133, 2000.\n+ .. [1] H. Moritz. Geodetic Reference System 1980, Journal of Geodesy, vol.\n+ 74, no. 1, pp 128\u2013133, 2000.\n \n- [2] https://pypi.org/project/pyproj/\n+ .. [2] https://pypi.org/project/pyproj/\n \n- [3] Wavelet Variability Model - Matlab Code:\n- https://pvpmc.sandia.gov/applications/wavelet-variability-model/\n+ .. [3] Wavelet Variability Model - Matlab Code:\n+ https://github.com/sandialabs/wvm\n \"\"\"\n \n # Added by Joe Ranalli (@jranalli), Penn State Hazleton, 2019\n@@ -159,7 +159,12 @@ def latlon_to_xy(coordinates):\n \n def _compute_wavelet(clearsky_index, dt=None):\n \"\"\"\n- Compute the wavelet transform on the input clear_sky time series.\n+ Compute the wavelet transform on the input clear_sky time series. Uses a\n+ top hat wavelet [-1,1,1,-1] shape, based on the difference of successive\n+ centered moving averages. Smallest scale (filter size of 2) is a degenerate\n+ case that resembles a Haar wavelet. Returns one level of approximation\n+ coefficient (CAn) and n levels of detail coefficients (CD1, CD2, ...,\n+ CDn-1, CDn).\n \n Parameters\n ----------\n@@ -174,19 +179,20 @@ def _compute_wavelet(clearsky_index, dt=None):\n Returns\n -------\n wavelet: numeric\n- The individual wavelets for the time series\n+ The individual wavelets for the time series. Format follows increasing\n+ scale (decreasing frequency): [CD1, CD2, ..., CDn, CAn]\n \n tmscales: numeric\n The timescales associated with the wavelets in seconds [s]\n \n References\n ----------\n- [1] M. Lave, J. Kleissl and J.S. Stein. A Wavelet-Based Variability\n- Model (WVM) for Solar PV Power Plants. IEEE Transactions on Sustainable\n- Energy, vol. 4, no. 2, pp. 501-509, 2013.\n+ .. [1] M. Lave, J. Kleissl and J.S. Stein. A Wavelet-Based Variability\n+ Model (WVM) for Solar PV Power Plants. IEEE Transactions on\n+ Sustainable Energy, vol. 4, no. 2, pp. 501-509, 2013.\n \n- [3] Wavelet Variability Model - Matlab Code:\n- https://pvpmc.sandia.gov/applications/wavelet-variability-model/\n+ .. [2] Wavelet Variability Model - Matlab Code:\n+ https://github.com/sandialabs/wvm\n \"\"\"\n \n # Added by Joe Ranalli (@jranalli), Penn State Hazleton, 2019\n@@ -209,31 +215,37 @@ def _compute_wavelet(clearsky_index, dt=None):\n \n # Compute wavelet time scales\n min_tmscale = np.ceil(np.log(dt)/np.log(2)) # Minimum wavelet timescale\n- max_tmscale = int(12 - min_tmscale) # maximum wavelet timescale\n+ max_tmscale = int(13 - min_tmscale) # maximum wavelet timescale\n \n tmscales = np.zeros(max_tmscale)\n csi_mean = np.zeros([max_tmscale, len(cs_long)])\n+ # Skip averaging for the 0th scale\n+ csi_mean[0, :] = cs_long.values.flatten()\n+ tmscales[0] = 1\n # Loop for all time scales we will consider\n- for i in np.arange(0, max_tmscale):\n- j = i+1\n- tmscales[i] = 2**j * dt # Wavelet integration time scale\n- intvlen = 2**j # Wavelet integration time series interval\n+ for i in np.arange(1, max_tmscale):\n+ tmscales[i] = 2**i * dt # Wavelet integration time scale\n+ intvlen = 2**i # Wavelet integration time series interval\n # Rolling average, retains only lower frequencies than interval\n+ # Produces slightly different end effects than the MATLAB version\n df = cs_long.rolling(window=intvlen, center=True, min_periods=1).mean()\n # Fill nan's in both directions\n df = df.fillna(method='bfill').fillna(method='ffill')\n # Pop values back out of the dataframe and store\n csi_mean[i, :] = df.values.flatten()\n+ # Shift to account for different indexing in MATLAB moving average\n+ csi_mean[i, :] = np.roll(csi_mean[i, :], -1)\n+ csi_mean[i, -1] = csi_mean[i, -2]\n \n- # Calculate the wavelets by isolating the rolling mean frequency ranges\n+ # Calculate detail coefficients by difference between successive averages\n wavelet_long = np.zeros(csi_mean.shape)\n for i in np.arange(0, max_tmscale-1):\n wavelet_long[i, :] = csi_mean[i, :] - csi_mean[i+1, :]\n- wavelet_long[max_tmscale-1, :] = csi_mean[max_tmscale-1, :] # Lowest freq\n+ wavelet_long[-1, :] = csi_mean[-1, :] # Lowest freq (CAn)\n \n # Clip off the padding and just return the original time window\n wavelet = np.zeros([max_tmscale, len(vals)])\n for i in np.arange(0, max_tmscale):\n- wavelet[i, :] = wavelet_long[i, len(vals)+1: 2*len(vals)+1]\n+ wavelet[i, :] = wavelet_long[i, len(vals): 2*len(vals)]\n \n return wavelet, tmscales\n", "test_patch": "diff --git a/pvlib/tests/test_scaling.py b/pvlib/tests/test_scaling.py\n--- a/pvlib/tests/test_scaling.py\n+++ b/pvlib/tests/test_scaling.py\n@@ -48,21 +48,24 @@ def positions():\n @pytest.fixture\n def expect_tmscale():\n # Expected timescales for dt = 1\n- return [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]\n+ return [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]\n \n \n @pytest.fixture\n def expect_wavelet():\n # Expected wavelet for indices 5000:5004 for clear_sky_index above (Matlab)\n- return np.array([[-0.025, 0.05, 0., -0.05, 0.025],\n- [0.025, 0., 0., 0., -0.025],\n- [0., 0., 0., 0., 0.]])\n+ e = np.zeros([13, 5])\n+ e[0, :] = np.array([0, -0.05, 0.1, -0.05, 0])\n+ e[1, :] = np.array([-0.025, 0.05, 0., -0.05, 0.025])\n+ e[2, :] = np.array([0.025, 0., 0., 0., -0.025])\n+ e[-1, :] = np.array([1, 1, 1, 1, 1])\n+ return e\n \n \n @pytest.fixture\n def expect_cs_smooth():\n # Expected smoothed clear sky index for indices 5000:5004 (Matlab)\n- return np.array([1., 1.0289, 1., 0.9711, 1.])\n+ return np.array([1., 1., 1.05774, 0.94226, 1.])\n \n \n def test_latlon_to_xy_zero():\n@@ -94,7 +97,7 @@ def test_compute_wavelet_series(clear_sky_index, time,\n csi_series = pd.Series(clear_sky_index, index=time)\n wavelet, tmscale = scaling._compute_wavelet(csi_series)\n assert_almost_equal(tmscale, expect_tmscale)\n- assert_almost_equal(wavelet[0:3, 5000:5005], expect_wavelet)\n+ assert_almost_equal(wavelet[:, 5000:5005], expect_wavelet)\n \n \n def test_compute_wavelet_series_numindex(clear_sky_index, time,\n@@ -103,14 +106,14 @@ def test_compute_wavelet_series_numindex(clear_sky_index, time,\n csi_series = pd.Series(clear_sky_index, index=dtindex)\n wavelet, tmscale = scaling._compute_wavelet(csi_series)\n assert_almost_equal(tmscale, expect_tmscale)\n- assert_almost_equal(wavelet[0:3, 5000:5005], expect_wavelet)\n+ assert_almost_equal(wavelet[:, 5000:5005], expect_wavelet)\n \n \n def test_compute_wavelet_array(clear_sky_index,\n expect_tmscale, expect_wavelet):\n wavelet, tmscale = scaling._compute_wavelet(clear_sky_index, dt)\n assert_almost_equal(tmscale, expect_tmscale)\n- assert_almost_equal(wavelet[0:3, 5000:5005], expect_wavelet)\n+ assert_almost_equal(wavelet[:, 5000:5005], expect_wavelet)\n \n \n def test_compute_wavelet_array_invalid(clear_sky_index):\n@@ -118,6 +121,14 @@ def test_compute_wavelet_array_invalid(clear_sky_index):\n scaling._compute_wavelet(clear_sky_index)\n \n \n+def test_compute_wavelet_dwttheory(clear_sky_index, time,\n+ expect_tmscale, expect_wavelet):\n+ # Confirm detail coeffs sum to original signal\n+ csi_series = pd.Series(clear_sky_index, index=time)\n+ wavelet, tmscale = scaling._compute_wavelet(csi_series)\n+ assert_almost_equal(np.sum(wavelet, 0), csi_series)\n+\n+\n def test_wvm_series(clear_sky_index, time, positions, expect_cs_smooth):\n csi_series = pd.Series(clear_sky_index, index=time)\n cs_sm, _, _ = scaling.wvm(csi_series, positions, cloud_speed)\n", "problem_statement": "Bug within scaling.py wavelet calculation methodology\n**Describe the bug**\r\nMathematical error within the wavelet computation for the scaling.py WVM implementation. Error arises from the methodology, as opposed to just a software bug. \r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n```\r\nimport numpy as np\r\nfrom pvlib import scaling\r\ncs = np.random.rand(2**14)\r\nw, ts = scaling._compute_wavelet(cs,1)\r\nprint(np.all( (sum(w)-cs) < 1e-8 )) # Returns False, expect True\r\n```\r\n\r\n**Expected behavior**\r\nFor a discrete wavelet transform (DWT) the sum of all wavelet modes should equate to the original data. \r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.7.2\r\n - ``pandas.__version__``: 1.2.3\r\n - python: 3.8.8\r\n\r\n**Additional context**\r\nThis bug is also present in the [PV_LIB](https://pvpmc.sandia.gov/applications/wavelet-variability-model/) Matlab version that was used as the basis for this code (I did reach out to them using the PVLIB MATLAB email form, but don't know who actually wrote that code). Essentially, the existing code throws away the highest level of Detail Coefficient in the transform and keeps an extra level of Approximation coefficient. The impact on the calculation is small, but leads to an incorrect DWT and reconstruction. I have a fix that makes the code pass the theoretical test about the DWT proposed under 'To Reproduce' but there may be some question as to whether this should be corrected or left alone to match the MATLAB code it was based on. \r\n\n", "hints_text": "@jranalli thanks for finding and reporting this. Can I ask how you contacted PVLIB MATLAB? Because I maintain that repository and I didn't see the email, so we need to fix something on our end with communications.\n@cwhanse Now that I look again, I think I used the wrong form. It was just a general Questions and Comments link for the PV Performance Modeling Collaborative at the bottom of the page. I didn't see any contact point for the PV_LIB MATLAB library and I also didn't know about the github repo for it, but now I do! \r\n\r\nI do have a fix for the MATLAB code as well, but I don't see that part of the library on github. If you'd like me to open an issue on that repository as well, I'd be happy to do so, but if there's some other pathway or contact point since that's kind of listed as a separate package of the code, please let me know.\r\n\r\nEither way, do you think it's appropriate to fix this, or does there need to be a conversation with the original author of that MATLAB code? If everything is fine to go ahead with it here, I can just put together my fix as a pull request for review.\r\n\r\n\nAnd did my own looking: pvl_WVM is in it's own Matlab archive, separate from PVLIB for Matlab. The WVM code is only available as a download from pvpmc.sandia.gov, whereas PVLIB for Matlab is on [github](https://github.com/sandialabs/MATLAB_PV_LIB).\r\n\r\nI've sent the bug report to Matt Lave, the originator of the WVM algorithm and code. We'll likely welcome the bug fix but I'd like to hear Matt's view first.\nOK sounds good. If he or you want to connect for more detail on the issue, you can get contact info for me at my [Faculty Page](http://personal.psu.edu/jar339/about.html).\nfor the record: bug is confirmed via separate communication with the WVM algorithm author.", "created_at": "2021-04-23T01:38:03Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_scaling.py::test_compute_wavelet_series", "pvlib/tests/test_scaling.py::test_compute_wavelet_series_numindex", "pvlib/tests/test_scaling.py::test_compute_wavelet_array", "pvlib/tests/test_scaling.py::test_compute_wavelet_dwttheory", "pvlib/tests/test_scaling.py::test_wvm_series", "pvlib/tests/test_scaling.py::test_wvm_array", "pvlib/tests/test_scaling.py::test_wvm_series_xyaslist"], "PASS_TO_PASS": ["pvlib/tests/test_scaling.py::test_latlon_to_xy_zero", "pvlib/tests/test_scaling.py::test_latlon_to_xy_single", "pvlib/tests/test_scaling.py::test_latlon_to_xy_array", "pvlib/tests/test_scaling.py::test_latlon_to_xy_list", "pvlib/tests/test_scaling.py::test_compute_wavelet_array_invalid", "pvlib/tests/test_scaling.py::test_wvm_invalid"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1707", "base_commit": "40e9e978c170bdde4eeee1547729417665dbc34c", "patch": "diff --git a/pvlib/iam.py b/pvlib/iam.py\n--- a/pvlib/iam.py\n+++ b/pvlib/iam.py\n@@ -175,8 +175,12 @@ def physical(aoi, n=1.526, K=4.0, L=0.002, *, n_ar=None):\n n2costheta2 = n2 * costheta\n \n # reflectance of s-, p-polarized, and normal light by the first interface\n- rho12_s = ((n1costheta1 - n2costheta2) / (n1costheta1 + n2costheta2)) ** 2\n- rho12_p = ((n1costheta2 - n2costheta1) / (n1costheta2 + n2costheta1)) ** 2\n+ with np.errstate(divide='ignore', invalid='ignore'):\n+ rho12_s = \\\n+ ((n1costheta1 - n2costheta2) / (n1costheta1 + n2costheta2)) ** 2\n+ rho12_p = \\\n+ ((n1costheta2 - n2costheta1) / (n1costheta2 + n2costheta1)) ** 2\n+\n rho12_0 = ((n1 - n2) / (n1 + n2)) ** 2\n \n # transmittance through the first interface\n@@ -208,13 +212,22 @@ def physical(aoi, n=1.526, K=4.0, L=0.002, *, n_ar=None):\n tau_0 *= (1 - rho23_0) / (1 - rho23_0 * rho12_0)\n \n # transmittance after absorption in the glass\n- tau_s *= np.exp(-K * L / costheta)\n- tau_p *= np.exp(-K * L / costheta)\n+ with np.errstate(divide='ignore', invalid='ignore'):\n+ tau_s *= np.exp(-K * L / costheta)\n+ tau_p *= np.exp(-K * L / costheta)\n+\n tau_0 *= np.exp(-K * L)\n \n # incidence angle modifier\n iam = (tau_s + tau_p) / 2 / tau_0\n \n+ # for light coming from behind the plane, none can enter the module\n+ # when n2 > 1, this is already the case\n+ if np.isclose(n2, 1).any():\n+ iam = np.where(aoi >= 90, 0, iam)\n+ if isinstance(aoi, pd.Series):\n+ iam = pd.Series(iam, index=aoi.index)\n+\n return iam\n \n \n", "test_patch": "diff --git a/pvlib/tests/test_iam.py b/pvlib/tests/test_iam.py\n--- a/pvlib/tests/test_iam.py\n+++ b/pvlib/tests/test_iam.py\n@@ -51,6 +51,18 @@ def test_physical():\n assert_series_equal(iam, expected)\n \n \n+def test_physical_n1_L0():\n+ aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan])\n+ expected = np.array([1, 1, 1, 1, 0, 0, np.nan])\n+ iam = _iam.physical(aoi, n=1, L=0)\n+ assert_allclose(iam, expected, equal_nan=True)\n+\n+ aoi = pd.Series(aoi)\n+ expected = pd.Series(expected)\n+ iam = _iam.physical(aoi, n=1, L=0)\n+ assert_series_equal(iam, expected)\n+\n+\n def test_physical_ar():\n aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan])\n expected = np.array([1, 0.99944171, 0.9917463, 0.91506158, 0, 0, np.nan])\n", "problem_statement": "regression: iam.physical returns nan for aoi > 90\u00b0 when n = 1\n**Describe the bug**\r\nFor pvlib==0.9.5, when n = 1 (no reflection) and aoi > 90\u00b0, we get nan as result.\r\n\r\n**To Reproduce**\r\n```python\r\nimport pvlib\r\npvlib.iam.physical(aoi=100, n=1)\r\n```\r\nreturns `nan`.\r\n\r\n**Expected behavior**\r\nThe result should be `0`, as it was for pvlib <= 0.9.4.\r\n\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: '0.9.5'\r\n - ``pandas.__version__``: '1.5.3'\r\n - python: 3.10.4\r\n\n", "hints_text": "", "created_at": "2023-03-24T10:46:42Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_iam.py::test_physical_n1_L0"], "PASS_TO_PASS": ["pvlib/tests/test_iam.py::test_ashrae", "pvlib/tests/test_iam.py::test_ashrae_scalar", "pvlib/tests/test_iam.py::test_physical", "pvlib/tests/test_iam.py::test_physical_ar", "pvlib/tests/test_iam.py::test_physical_noar", "pvlib/tests/test_iam.py::test_physical_scalar", "pvlib/tests/test_iam.py::test_martin_ruiz", "pvlib/tests/test_iam.py::test_martin_ruiz_exception", "pvlib/tests/test_iam.py::test_martin_ruiz_diffuse", "pvlib/tests/test_iam.py::test_iam_interp", "pvlib/tests/test_iam.py::test_sapm[45-0.9975036250000002]", "pvlib/tests/test_iam.py::test_sapm[aoi1-expected1]", "pvlib/tests/test_iam.py::test_sapm[aoi2-expected2]", "pvlib/tests/test_iam.py::test_sapm_limits", "pvlib/tests/test_iam.py::test_marion_diffuse_model", "pvlib/tests/test_iam.py::test_marion_diffuse_kwargs", "pvlib/tests/test_iam.py::test_marion_diffuse_invalid", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[sky-180-0.9596085829811408]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[horizon-1800-0.8329070417832541]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[ground-180-0.719823559106309]", "pvlib/tests/test_iam.py::test_marion_integrate_list[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_list[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_list[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_series[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_series[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_series[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_ground_flat", "pvlib/tests/test_iam.py::test_marion_integrate_invalid", "pvlib/tests/test_iam.py::test_schlick", "pvlib/tests/test_iam.py::test_schlick_diffuse"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1395", "base_commit": "26579bec7e65296223503b9e05da4af914af6777", "patch": "diff --git a/pvlib/iotools/__init__.py b/pvlib/iotools/__init__.py\n--- a/pvlib/iotools/__init__.py\n+++ b/pvlib/iotools/__init__.py\n@@ -15,6 +15,7 @@\n from pvlib.iotools.pvgis import get_pvgis_tmy, read_pvgis_tmy # noqa: F401\n from pvlib.iotools.pvgis import read_pvgis_hourly # noqa: F401\n from pvlib.iotools.pvgis import get_pvgis_hourly # noqa: F401\n+from pvlib.iotools.pvgis import get_pvgis_horizon # noqa: F401\n from pvlib.iotools.bsrn import get_bsrn # noqa: F401\n from pvlib.iotools.bsrn import read_bsrn # noqa: F401\n from pvlib.iotools.bsrn import parse_bsrn # noqa: F401\ndiff --git a/pvlib/iotools/pvgis.py b/pvlib/iotools/pvgis.py\n--- a/pvlib/iotools/pvgis.py\n+++ b/pvlib/iotools/pvgis.py\n@@ -665,3 +665,57 @@ def read_pvgis_tmy(filename, pvgis_format=None, map_variables=None):\n data = data.rename(columns=VARIABLE_MAP)\n \n return data, months_selected, inputs, meta\n+\n+\n+def get_pvgis_horizon(latitude, longitude, url=URL, **kwargs):\n+ \"\"\"Get horizon data from PVGIS.\n+\n+ Parameters\n+ ----------\n+ latitude : float\n+ Latitude in degrees north\n+ longitude : float\n+ Longitude in degrees east\n+ url: str, default: :const:`pvlib.iotools.pvgis.URL`\n+ Base URL for PVGIS\n+ kwargs:\n+ Passed to requests.get\n+\n+ Returns\n+ -------\n+ data : pd.Series\n+ Pandas Series of the retrived horizon elevation angles. Index is the\n+ corresponding horizon azimuth angles.\n+ metadata : dict\n+ Metadata returned by PVGIS.\n+\n+ Notes\n+ -----\n+ The horizon azimuths are specified clockwise from north, e.g., south=180.\n+ This is the standard pvlib convention, although the PVGIS website specifies\n+ south=0.\n+\n+ References\n+ ----------\n+ .. [1] `PVGIS horizon profile tool\n+ <https://ec.europa.eu/jrc/en/PVGIS/tools/horizon>`_\n+ \"\"\"\n+ params = {'lat': latitude, 'lon': longitude, 'outputformat': 'json'}\n+ res = requests.get(url + 'printhorizon', params=params, **kwargs)\n+ if not res.ok:\n+ try:\n+ err_msg = res.json()\n+ except Exception:\n+ res.raise_for_status()\n+ else:\n+ raise requests.HTTPError(err_msg['message'])\n+ json_output = res.json()\n+ metadata = json_output['meta']\n+ data = pd.DataFrame(json_output['outputs']['horizon_profile'])\n+ data.columns = ['horizon_azimuth', 'horizon_elevation']\n+ # Convert azimuth to pvlib convention (north=0, south=180)\n+ data['horizon_azimuth'] += 180\n+ data.set_index('horizon_azimuth', inplace=True)\n+ data = data['horizon_elevation'] # convert to pd.Series\n+ data = data[data.index < 360] # remove duplicate north point (0 and 360)\n+ return data, metadata\n", "test_patch": "diff --git a/pvlib/data/test_read_pvgis_horizon.csv b/pvlib/data/test_read_pvgis_horizon.csv\nnew file mode 100644\n--- /dev/null\n+++ b/pvlib/data/test_read_pvgis_horizon.csv\n@@ -0,0 +1,49 @@\n+horizon_azimuth,horizon_elevation\n+0,9.9\n+7.5,13\n+15,14.5\n+22.5,15.7\n+30,14.9\n+37.5,15.3\n+45,15.7\n+52.5,15.7\n+60,13\n+67.5,11.5\n+75,11.1\n+82.5,11.5\n+90,10.3\n+97.5,11.5\n+105,10.3\n+112.5,9.5\n+120,10.7\n+127.5,11.8\n+135,11.8\n+142.5,8.8\n+150,8.4\n+157.5,7.3\n+165,5.7\n+172.5,5.7\n+180,4.6\n+187.5,3.4\n+195,0.8\n+202.5,0\n+210,0\n+217.5,0\n+225,0\n+232.5,0\n+240,0\n+247.5,0\n+255,0\n+262.5,0\n+270,0\n+277.5,0\n+285,0\n+292.5,0\n+300,0\n+307.5,0\n+315,1.1\n+322.5,1.9\n+330,3.8\n+337.5,5\n+345,6.5\n+352.5,9.2\ndiff --git a/pvlib/tests/iotools/test_pvgis.py b/pvlib/tests/iotools/test_pvgis.py\n--- a/pvlib/tests/iotools/test_pvgis.py\n+++ b/pvlib/tests/iotools/test_pvgis.py\n@@ -9,8 +9,9 @@\n import requests\n from pvlib.iotools import get_pvgis_tmy, read_pvgis_tmy\n from pvlib.iotools import get_pvgis_hourly, read_pvgis_hourly\n+from pvlib.iotools import get_pvgis_horizon\n from ..conftest import (DATA_DIR, RERUNS, RERUNS_DELAY, assert_frame_equal,\n- fail_on_pvlib_version)\n+ fail_on_pvlib_version, assert_series_equal)\n from pvlib._deprecation import pvlibDeprecationWarning\n \n \n@@ -509,6 +510,23 @@ def test_get_pvgis_map_variables(pvgis_tmy_mapped_columns):\n assert all([c in pvgis_tmy_mapped_columns for c in actual.columns])\n \n \[email protected]_data\[email protected](reruns=RERUNS, reruns_delay=RERUNS_DELAY)\n+def test_read_pvgis_horizon():\n+ pvgis_data, _ = get_pvgis_horizon(35.171051, -106.465158)\n+ horizon_data = pd.read_csv(DATA_DIR / 'test_read_pvgis_horizon.csv',\n+ index_col=0)\n+ horizon_data = horizon_data['horizon_elevation']\n+ assert_series_equal(pvgis_data, horizon_data)\n+\n+\[email protected]_data\[email protected](reruns=RERUNS, reruns_delay=RERUNS_DELAY)\n+def test_read_pvgis_horizon_invalid_coords():\n+ with pytest.raises(requests.HTTPError, match='lat: Incorrect value'):\n+ _, _ = get_pvgis_horizon(100, 50) # unfeasible latitude\n+\n+\n def test_read_pvgis_tmy_map_variables(pvgis_tmy_mapped_columns):\n fn = DATA_DIR / 'tmy_45.000_8.000_2005_2016.json'\n actual, _, _, _ = read_pvgis_tmy(fn, map_variables=True)\n", "problem_statement": "Add retrieval function for horizon profile from MINES Paris Tech\n<!-- 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. -->\r\n\r\n - [x] I am familiar with the [contributing guidelines](https://pvlib-python.readthedocs.io/en/latest/contributing.html)\r\n - [x] Tests added\r\n - [x] Updates entries to [`docs/sphinx/source/api.rst`](https://github.com/pvlib/pvlib-python/blob/master/docs/sphinx/source/api.rst) for API changes.\r\n - [x] Adds description and name entries in the appropriate \"what's new\" file in [`docs/sphinx/source/whatsnew`](https://github.com/pvlib/pvlib-python/tree/master/docs/sphinx/source/whatsnew) for all changes. Includes link to the GitHub Issue with `` :issue:`num` `` or this Pull Request with `` :pull:`num` ``. Includes contributor name and/or GitHub username (link with `` :ghuser:`user` ``).\r\n - [x] New code is fully documented. Includes [numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html) compliant docstrings, examples, and comments where necessary.\r\n - [x] Pull request is nearly complete and ready for detailed review.\r\n - [x] Maintainer: Appropriate GitHub Labels and Milestone are assigned to the Pull Request and linked Issue.\r\n\r\n<!-- Brief description of the problem and proposed solution (if not already fully described in the issue linked to above): -->\r\n\r\nThe proposed function retrieves the local horizon profile for a specific location (latitude, longitude, and elevation). The returned horizon profile has a resolution of 1 degree in the azimuth direction. The service is provided by MINES ParisTech though I cannot find any official documentation for it.\r\n\r\nThe function added in this PR (``pvlib.iotools.get_mines_horizon``) is very similar to the function added in #1395 (``pvlib.iotools.get_pvgis_horizon``).\n", "hints_text": "@mikofski @cwhanse I saw your discussions in #758 and #1290 and figured I'd share the code I had laying around for downloading the local horizon profile from SRTM. Does this have any interest to you?\nI'm lovin' this! Could we also look into retrieving pvgis horizon data, how do they compare to the SRTM from MINES?", "created_at": "2022-01-26T20:24:16Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile0-expected_radiation_csv-metadata_exp0-inputs_exp0-False-None]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile1-expected_radiation_csv_mapped-metadata_exp1-inputs_exp1-True-csv]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile2-expected_pv_json-metadata_exp2-inputs_exp2-False-None]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile3-expected_pv_json_mapped-metadata_exp3-inputs_exp3-True-json]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly_bad_extension", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile0-expected_radiation_csv-args0-False-https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=csv&angle=30&aspect=0&usehorizon=0&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&raddatabase=PVGIS-SARAH&startyear=2016&endyear=2016]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile1-expected_radiation_csv_mapped-args1-True-https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=csv&angle=30&aspect=0&usehorizon=0&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&raddatabase=PVGIS-SARAH&startyear=2016&endyear=2016]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile2-expected_pv_json-args2-False-https://re.jrc.ec.europa.eu/api/v5_2/seriescalc?lat=45&lon=8&outputformat=json&angle=30&aspect=0&pvtechchoice=CIS&mountingplace=free&trackingtype=2&components=0&usehorizon=1&raddatabase=PVGIS-SARAH2&startyear=2013&endyear=2014&pvcalculation=1&peakpower=10&loss=5&optimalangles=1]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile3-expected_pv_json_mapped-args3-True-https://re.jrc.ec.europa.eu/api/v5_2/seriescalc?lat=45&lon=8&outputformat=json&angle=30&aspect=0&pvtechchoice=CIS&mountingplace=free&trackingtype=2&components=0&usehorizon=1&raddatabase=PVGIS-SARAH2&startyear=2013&endyear=2014&pvcalculation=1&peakpower=10&loss=5&optimalangles=1]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_bad_status_code", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_bad_outputformat", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_additional_inputs", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly_empty_file", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_map_variables", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_json", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_epw", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_csv", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_basic", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_exception"], "PASS_TO_PASS": [], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1216", "base_commit": "01a23e31bcb9e4f844c5877a48cd7681406c6696", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -1994,8 +1994,8 @@ def calcparams_cec(effective_irradiance, temp_cell,\n alpha_sc*(1.0 - Adjust/100),\n a_ref, I_L_ref, I_o_ref,\n R_sh_ref, R_s,\n- EgRef=1.121, dEgdT=-0.0002677,\n- irrad_ref=1000, temp_ref=25)\n+ EgRef=EgRef, dEgdT=dEgdT,\n+ irrad_ref=irrad_ref, temp_ref=temp_ref)\n \n \n def calcparams_pvsyst(effective_irradiance, temp_cell,\n", "test_patch": "diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -792,6 +792,43 @@ def test_calcparams_cec(cec_module_params):\n check_less_precise=3)\n \n \n+def test_calcparams_cec_extra_params_propagation(cec_module_params, mocker):\n+ \"\"\"\n+ See bug #1215.\n+\n+ When calling `calcparams_cec`, the parameters `EgRef`, `dEgdT`, `irrad_ref`\n+ and `temp_ref` must not be ignored.\n+\n+ Since, internally, this function is calling `calcparams_desoto`, this test\n+ checks that the latter is called with the expected parameters instead of\n+ some default values.\n+ \"\"\"\n+ times = pd.date_range(start='2015-01-01', periods=3, freq='12H')\n+ effective_irradiance = pd.Series([0.0, 800.0, 800.0], index=times)\n+ temp_cell = pd.Series([25, 25, 50], index=times)\n+ extra_parameters = dict(\n+ EgRef=1.123,\n+ dEgdT=-0.0002688,\n+ irrad_ref=1100,\n+ temp_ref=23,\n+ )\n+ m = mocker.spy(pvsystem, 'calcparams_desoto')\n+ pvsystem.calcparams_cec(\n+ effective_irradiance=effective_irradiance,\n+ temp_cell=temp_cell,\n+ alpha_sc=cec_module_params['alpha_sc'],\n+ a_ref=cec_module_params['a_ref'],\n+ I_L_ref=cec_module_params['I_L_ref'],\n+ I_o_ref=cec_module_params['I_o_ref'],\n+ R_sh_ref=cec_module_params['R_sh_ref'],\n+ R_s=cec_module_params['R_s'],\n+ Adjust=cec_module_params['Adjust'],\n+ **extra_parameters,\n+ )\n+ assert m.call_count == 1\n+ assert m.call_args[1] == extra_parameters\n+\n+\n def test_calcparams_pvsyst(pvsyst_module_params):\n times = pd.date_range(start='2015-01-01', periods=2, freq='12H')\n effective_irradiance = pd.Series([0.0, 800.0], index=times)\n", "problem_statement": "`pvsystem.calcparams_cec()` does not propagate parameters\n**Describe the bug**\r\n\r\nThe function calls `calcparams_desoto` with hardcoded reference values.\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/40ba4bd5c8b91754aa73e638ed984ab9657847cd/pvlib/pvsystem.py#L1850-L1855\r\n\r\nThis means the function is silently ignoring its inputs, yielding incorrect results that may go unnoticed.\r\n\r\n\r\n**Expected behavior**\r\n\r\nThe function parameters are propagated into the `calcparams_desoto` call. In particular: `EgRef`, `dEgdT`, `irrad_ref`, `temp_ref`\n", "hints_text": "", "created_at": "2021-05-05T17:44:02Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation"], "PASS_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp_override", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_change_surface_azimuth", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_modules_per_string", "pvlib/tests/test_pvsystem.py::test_PVSystem_strings_per_inverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_type]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[temperature_model_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[albedo]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_tilt]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_azimuth]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[racking_model]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[modules_per_string]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[strings_per_inverter]", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1191", "base_commit": "0415365031ca8d0b2867f2a2877e0ad9d7098ffc", "patch": "diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py\n--- a/pvlib/irradiance.py\n+++ b/pvlib/irradiance.py\n@@ -182,6 +182,9 @@ def aoi_projection(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth):\n tools.sind(surface_tilt) * tools.sind(solar_zenith) *\n tools.cosd(solar_azimuth - surface_azimuth))\n \n+ # GH 1185\n+ projection = np.clip(projection, -1, 1)\n+\n try:\n projection.name = 'aoi_projection'\n except AttributeError:\n", "test_patch": "diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py\n--- a/pvlib/tests/test_irradiance.py\n+++ b/pvlib/tests/test_irradiance.py\n@@ -792,6 +792,27 @@ def test_aoi_and_aoi_projection(surface_tilt, surface_azimuth, solar_zenith,\n assert_allclose(aoi_projection, aoi_proj_expected, atol=1e-6)\n \n \n+def test_aoi_projection_precision():\n+ # GH 1185 -- test that aoi_projection does not exceed 1.0, and when\n+ # given identical inputs, the returned projection is very close to 1.0\n+\n+ # scalars\n+ zenith = 89.26778228223463\n+ azimuth = 60.932028605997004\n+ projection = irradiance.aoi_projection(zenith, azimuth, zenith, azimuth)\n+ assert projection <= 1\n+ assert np.isclose(projection, 1)\n+\n+ # arrays\n+ zeniths = np.array([zenith])\n+ azimuths = np.array([azimuth])\n+ projections = irradiance.aoi_projection(zeniths, azimuths,\n+ zeniths, azimuths)\n+ assert all(projections <= 1)\n+ assert all(np.isclose(projections, 1))\n+ assert projections.dtype == np.dtype('float64')\n+\n+\n @pytest.fixture\n def airmass_kt():\n # disc algorithm stopped at am=12. test am > 12 for out of range behavior\n", "problem_statement": "irradiance.aoi can return NaN when module orientation is perfectly aligned with solar position\n**Describe the bug**\r\nI was playing with a dual-axis tracking mount with #1176 and found that when the modules are perfectly aligned with the sun (i.e. AOI should be exactly zero), floating point round-off can result in aoi projection values slightly greater than one, resulting in NaN aoi. This only happens for some perfectly-aligned inputs (for example tilt=zenith=20, azimuth=180 returns aoi=0 as expected).\r\n\r\n**To Reproduce**\r\n```python\r\nimport pvlib\r\nzenith = 89.26778228223463\r\nazimuth = 60.932028605997004\r\nprint(pvlib.irradiance.aoi_projection(zenith, azimuth, zenith, azimuth))\r\nprint(pvlib.irradiance.aoi(zenith, azimuth, zenith, azimuth))\r\n\r\n# output:\r\n1.0000000000000002\r\nRuntimeWarning: invalid value encountered in arccos: aoi_value = np.rad2deg(np.arccos(projection))\r\nnan\r\n```\r\n\r\n**Expected behavior**\r\nI expect aoi=0 whenever module orientation and solar position angles are identical.\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: `0.9.0-alpha.4+14.g61650e9`\r\n - ``pandas.__version__``: `0.25.1`\r\n - ``numpy.__version__``: `1.17.0`\r\n - python: `3.7.7 (default, May 6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)]`\r\n\r\n**Additional context**\r\nSome ideas for fixes:\r\n1) In `irradiance.aoi_projection`, return a hard-coded `1.0` for inputs within some small tolerance\r\n2) In `irradiance.aoi_projection`, clamp return value to `[-1, +1]`\r\n3) In `irradiance.aoi`, clamp aoi_projection values to `[-1, +1`] before calling `arccos`\r\n4) Rework the `irradiance.aoi_projection` trig equations to not generate impossible values?\n", "hints_text": "", "created_at": "2021-03-10T01:05:50Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_irradiance.py::test_aoi_projection_precision"], "PASS_TO_PASS": ["pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_float", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_reindl", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_invalid", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-823", "base_commit": "a5c24f01e9b420968f5fda0d5c46ce2a4cf2c867", "patch": "diff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -1,7 +1,7 @@\n import numpy as np\n import pandas as pd\n \n-from pvlib.tools import cosd, sind\n+from pvlib.tools import cosd, sind, tand\n from pvlib.pvsystem import _combine_localized_attributes\n from pvlib.pvsystem import PVSystem\n from pvlib.location import Location\n@@ -10,8 +10,9 @@\n \n class SingleAxisTracker(PVSystem):\n \"\"\"\n- Inherits the PV modeling methods from :py:class:`~pvlib.pvsystem.PVSystem`.\n-\n+ A class for single-axis trackers that inherits the PV modeling methods from\n+ :py:class:`~pvlib.pvsystem.PVSystem`. For details on calculating tracker\n+ rotation see :py:func:`pvlib.tracking.singleaxis`.\n \n Parameters\n ----------\n@@ -21,7 +22,7 @@ class SingleAxisTracker(PVSystem):\n \n axis_azimuth : float, default 0\n A value denoting the compass direction along which the axis of\n- rotation lies. Measured in decimal degrees East of North.\n+ rotation lies. Measured in decimal degrees east of north.\n \n max_angle : float, default 90\n A value denoting the maximum rotation angle, in decimal degrees,\n@@ -43,16 +44,33 @@ class SingleAxisTracker(PVSystem):\n between the tracking axes has a gcr of 2/6=0.333. If gcr is not\n provided, a gcr of 2/7 is default. gcr must be <=1.\n \n+ cross_axis_tilt : float, default 0.0\n+ The angle, relative to horizontal, of the line formed by the\n+ intersection between the slope containing the tracker axes and a plane\n+ perpendicular to the tracker axes. Cross-axis tilt should be specified\n+ using a right-handed convention. For example, trackers with axis\n+ azimuth of 180 degrees (heading south) will have a negative cross-axis\n+ tilt if the tracker axes plane slopes down to the east and positive\n+ cross-axis tilt if the tracker axes plane slopes up to the east. Use\n+ :func:`~pvlib.tracking.calc_cross_axis_tilt` to calculate\n+ `cross_axis_tilt`. [degrees]\n+\n+ See also\n+ --------\n+ pvlib.tracking.singleaxis\n+ pvlib.tracking.calc_axis_tilt\n+ pvlib.tracking.calc_cross_axis_tilt\n \"\"\"\n \n- def __init__(self, axis_tilt=0, axis_azimuth=0,\n- max_angle=90, backtrack=True, gcr=2.0/7.0, **kwargs):\n+ def __init__(self, axis_tilt=0, axis_azimuth=0, max_angle=90,\n+ backtrack=True, gcr=2.0/7.0, cross_axis_tilt=0.0, **kwargs):\n \n self.axis_tilt = axis_tilt\n self.axis_azimuth = axis_azimuth\n self.max_angle = max_angle\n self.backtrack = backtrack\n self.gcr = gcr\n+ self.cross_axis_tilt = cross_axis_tilt\n \n kwargs['surface_tilt'] = None\n kwargs['surface_azimuth'] = None\n@@ -60,7 +78,8 @@ def __init__(self, axis_tilt=0, axis_azimuth=0,\n super(SingleAxisTracker, self).__init__(**kwargs)\n \n def __repr__(self):\n- attrs = ['axis_tilt', 'axis_azimuth', 'max_angle', 'backtrack', 'gcr']\n+ attrs = ['axis_tilt', 'axis_azimuth', 'max_angle', 'backtrack', 'gcr',\n+ 'cross_axis_tilt']\n sat_repr = ('SingleAxisTracker:\\n ' + '\\n '.join(\n ('{}: {}'.format(attr, getattr(self, attr)) for attr in attrs)))\n # get the parent PVSystem info\n@@ -88,8 +107,8 @@ def singleaxis(self, apparent_zenith, apparent_azimuth):\n \"\"\"\n tracking_data = singleaxis(apparent_zenith, apparent_azimuth,\n self.axis_tilt, self.axis_azimuth,\n- self.max_angle,\n- self.backtrack, self.gcr)\n+ self.max_angle, self.backtrack,\n+ self.gcr, self.cross_axis_tilt)\n \n return tracking_data\n \n@@ -215,13 +234,15 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n \n class LocalizedSingleAxisTracker(SingleAxisTracker, Location):\n \"\"\"\n- The LocalizedSingleAxisTracker class defines a standard set of\n- installed PV system attributes and modeling functions. This class\n- combines the attributes and methods of the SingleAxisTracker (a\n- subclass of PVSystem) and Location classes.\n-\n- The LocalizedSingleAxisTracker may have bugs due to the difficulty\n- of robustly implementing multiple inheritance. See\n+ The :py:class:`~pvlib.tracking.LocalizedSingleAxisTracker` class defines a\n+ standard set of installed PV system attributes and modeling functions. This\n+ class combines the attributes and methods of the\n+ :py:class:`~pvlib.tracking.SingleAxisTracker` (a subclass of\n+ :py:class:`~pvlib.pvsystem.PVSystem`) and\n+ :py:class:`~pvlib.location.Location` classes.\n+\n+ The :py:class:`~pvlib.tracking.LocalizedSingleAxisTracker` may have bugs\n+ due to the difficulty of robustly implementing multiple inheritance. See\n :py:class:`~pvlib.modelchain.ModelChain` for an alternative paradigm\n for modeling PV systems at specific locations.\n \"\"\"\n@@ -247,25 +268,25 @@ def __repr__(self):\n \n def singleaxis(apparent_zenith, apparent_azimuth,\n axis_tilt=0, axis_azimuth=0, max_angle=90,\n- backtrack=True, gcr=2.0/7.0):\n+ backtrack=True, gcr=2.0/7.0, cross_axis_tilt=0):\n \"\"\"\n- Determine the rotation angle of a single axis tracker when given a\n- particular sun zenith and azimuth angle. See [1]_ for details about\n- the equations.\n- Backtracking may be specified, and if so, a ground coverage\n- ratio is required.\n-\n- Rotation angle is determined in a panel-oriented coordinate system.\n- The tracker azimuth axis_azimuth defines the positive y-axis; the\n- positive x-axis is 90 degress clockwise from the y-axis and parallel\n- to the earth surface, and the positive z-axis is normal and oriented\n- towards the sun. Rotation angle tracker_theta indicates tracker\n- position relative to horizontal: tracker_theta = 0 is horizontal,\n- and positive tracker_theta is a clockwise rotation around the y axis\n- in the x, y, z coordinate system. For example, if tracker azimuth\n- axis_azimuth is 180 (oriented south), tracker_theta = 30 is a\n- rotation of 30 degrees towards the west, and tracker_theta = -90 is\n- a rotation to the vertical plane facing east.\n+ Determine the rotation angle of a single-axis tracker when given particular\n+ solar zenith and azimuth angles.\n+\n+ See [1]_ for details about the equations. Backtracking may be specified,\n+ and if so, a ground coverage ratio is required.\n+\n+ Rotation angle is determined in a right-handed coordinate system. The\n+ tracker `axis_azimuth` defines the positive y-axis, the positive x-axis is\n+ 90 degrees clockwise from the y-axis and parallel to the Earth's surface,\n+ and the positive z-axis is normal to both x & y-axes and oriented skyward.\n+ Rotation angle `tracker_theta` is a right-handed rotation around the y-axis\n+ in the x, y, z coordinate system and indicates tracker position relative to\n+ horizontal. For example, if tracker `axis_azimuth` is 180 (oriented south)\n+ and `axis_tilt` is zero, then a `tracker_theta` of zero is horizontal, a\n+ `tracker_theta` of 30 degrees is a rotation of 30 degrees towards the west,\n+ and a `tracker_theta` of -90 degrees is a rotation to the vertical plane\n+ facing east.\n \n Parameters\n ----------\n@@ -281,7 +302,7 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n \n axis_azimuth : float, default 0\n A value denoting the compass direction along which the axis of\n- rotation lies. Measured in decimal degrees East of North.\n+ rotation lies. Measured in decimal degrees east of north.\n \n max_angle : float, default 90\n A value denoting the maximum rotation angle, in decimal degrees,\n@@ -303,24 +324,41 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n between the tracking axes has a gcr of 2/6=0.333. If gcr is not\n provided, a gcr of 2/7 is default. gcr must be <=1.\n \n+ cross_axis_tilt : float, default 0.0\n+ The angle, relative to horizontal, of the line formed by the\n+ intersection between the slope containing the tracker axes and a plane\n+ perpendicular to the tracker axes. Cross-axis tilt should be specified\n+ using a right-handed convention. For example, trackers with axis\n+ azimuth of 180 degrees (heading south) will have a negative cross-axis\n+ tilt if the tracker axes plane slopes down to the east and positive\n+ cross-axis tilt if the tracker axes plane slopes up to the east. Use\n+ :func:`~pvlib.tracking.calc_cross_axis_tilt` to calculate\n+ `cross_axis_tilt`. [degrees]\n+\n Returns\n -------\n dict or DataFrame with the following columns:\n * `tracker_theta`: The rotation angle of the tracker.\n tracker_theta = 0 is horizontal, and positive rotation angles are\n- clockwise.\n+ clockwise. [degrees]\n * `aoi`: The angle-of-incidence of direct irradiance onto the\n- rotated panel surface.\n+ rotated panel surface. [degrees]\n * `surface_tilt`: The angle between the panel surface and the earth\n- surface, accounting for panel rotation.\n+ surface, accounting for panel rotation. [degrees]\n * `surface_azimuth`: The azimuth of the rotated panel, determined by\n projecting the vector normal to the panel's surface to the earth's\n- surface.\n+ surface. [degrees]\n+\n+ See also\n+ --------\n+ pvlib.tracking.calc_axis_tilt\n+ pvlib.tracking.calc_cross_axis_tilt\n \n References\n ----------\n- .. [1] Lorenzo, E et al., 2011, \"Tracking and back-tracking\", Prog. in\n- Photovoltaics: Research and Applications, v. 19, pp. 747-753.\n+ .. [1] Kevin Anderson and Mark Mikofski, \"Slope-Aware Backtracking for\n+ Single-Axis Trackers\", Technical Report NREL/TP-5K00-76626, July 2020.\n+ https://www.nrel.gov/docs/fy20osti/76626.pdf\n \"\"\"\n \n # MATLAB to Python conversion by\n@@ -338,118 +376,84 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n if apparent_azimuth.ndim > 1 or apparent_zenith.ndim > 1:\n raise ValueError('Input dimensions must not exceed 1')\n \n- # Calculate sun position x, y, z using coordinate system as in [1], Eq 2.\n-\n- # Positive y axis is oriented parallel to earth surface along tracking axis\n- # (for the purpose of illustration, assume y is oriented to the south);\n- # positive x axis is orthogonal, 90 deg clockwise from y-axis, and parallel\n- # to the earth's surface (if y axis is south, x axis is west);\n- # positive z axis is normal to x, y axes, pointed upward.\n-\n- # Equations in [1] assume solar azimuth is relative to reference vector\n- # pointed south, with clockwise positive.\n- # Here, the input solar azimuth is degrees East of North,\n- # i.e., relative to a reference vector pointed\n- # north with clockwise positive.\n- # Rotate sun azimuth to coordinate system as in [1]\n- # to calculate sun position.\n-\n- az = apparent_azimuth - 180\n- apparent_elevation = 90 - apparent_zenith\n- x = cosd(apparent_elevation) * sind(az)\n- y = cosd(apparent_elevation) * cosd(az)\n- z = sind(apparent_elevation)\n-\n- # translate array azimuth from compass bearing to [1] coord system\n- # wholmgren: strange to see axis_azimuth calculated differently from az,\n- # (not that it matters, or at least it shouldn't...).\n- axis_azimuth_south = axis_azimuth - 180\n-\n- # translate input array tilt angle axis_tilt to [1] coordinate system.\n-\n- # In [1] coordinates, axis_tilt is a rotation about the x-axis.\n- # For a system with array azimuth (y-axis) oriented south,\n- # the x-axis is oriented west, and a positive axis_tilt is a\n- # counterclockwise rotation, i.e, lifting the north edge of the panel.\n- # Thus, in [1] coordinate system, in the northern hemisphere a positive\n- # axis_tilt indicates a rotation toward the equator,\n- # whereas in the southern hemisphere rotation toward the equator is\n- # indicated by axis_tilt<0. Here, the input axis_tilt is\n- # always positive and is a rotation toward the equator.\n-\n- # Calculate sun position (xp, yp, zp) in panel-oriented coordinate system:\n- # positive y-axis is oriented along tracking axis at panel tilt;\n- # positive x-axis is orthogonal, clockwise, parallel to earth surface;\n- # positive z-axis is normal to x-y axes, pointed upward.\n- # Calculate sun position (xp,yp,zp) in panel coordinates using [1] Eq 11\n- # note that equation for yp (y' in Eq. 11 of Lorenzo et al 2011) is\n- # corrected, after conversation with paper's authors.\n-\n- xp = x*cosd(axis_azimuth_south) - y*sind(axis_azimuth_south)\n- yp = (x*cosd(axis_tilt)*sind(axis_azimuth_south) +\n- y*cosd(axis_tilt)*cosd(axis_azimuth_south) -\n- z*sind(axis_tilt))\n- zp = (x*sind(axis_tilt)*sind(axis_azimuth_south) +\n- y*sind(axis_tilt)*cosd(axis_azimuth_south) +\n- z*cosd(axis_tilt))\n+ # Calculate sun position x, y, z using coordinate system as in [1], Eq 1.\n+\n+ # NOTE: solar elevation = 90 - solar zenith, then use trig identities:\n+ # sin(90-x) = cos(x) & cos(90-x) = sin(x)\n+ sin_zenith = sind(apparent_zenith)\n+ x = sin_zenith * sind(apparent_azimuth)\n+ y = sin_zenith * cosd(apparent_azimuth)\n+ z = cosd(apparent_zenith)\n+\n+ # Assume the tracker reference frame is right-handed. Positive y-axis is\n+ # oriented along tracking axis; from north, the y-axis is rotated clockwise\n+ # by the axis azimuth and tilted from horizontal by the axis tilt. The\n+ # positive x-axis is 90 deg clockwise from the y-axis and parallel to\n+ # horizontal (e.g., if the y-axis is south, the x-axis is west); the\n+ # positive z-axis is normal to the x and y axes, pointed upward.\n+\n+ # Calculate sun position (xp, yp, zp) in tracker coordinate system using\n+ # [1] Eq 4.\n+\n+ cos_axis_azimuth = cosd(axis_azimuth)\n+ sin_axis_azimuth = sind(axis_azimuth)\n+ cos_axis_tilt = cosd(axis_tilt)\n+ sin_axis_tilt = sind(axis_tilt)\n+ xp = x*cos_axis_azimuth - y*sin_axis_azimuth\n+ yp = (x*cos_axis_tilt*sin_axis_azimuth\n+ + y*cos_axis_tilt*cos_axis_azimuth\n+ - z*sin_axis_tilt)\n+ zp = (x*sin_axis_tilt*sin_axis_azimuth\n+ + y*sin_axis_tilt*cos_axis_azimuth\n+ + z*cos_axis_tilt)\n \n # The ideal tracking angle wid is the rotation to place the sun position\n- # vector (xp, yp, zp) in the (y, z) plane; i.e., normal to the panel and\n- # containing the axis of rotation. wid = 0 indicates that the panel is\n- # horizontal. Here, our convention is that a clockwise rotation is\n+ # vector (xp, yp, zp) in the (y, z) plane, which is normal to the panel and\n+ # contains the axis of rotation. wid = 0 indicates that the panel is\n+ # horizontal. Here, our convention is that a clockwise rotation is\n # positive, to view rotation angles in the same frame of reference as\n- # azimuth. For example, for a system with tracking axis oriented south,\n- # a rotation toward the east is negative, and a rotation to the west is\n- # positive.\n-\n- # Use arctan2 and avoid the tmp corrections.\n-\n- # angle from x-y plane to projection of sun vector onto x-z plane\n-# tmp = np.degrees(np.arctan(zp/xp))\n-\n- # Obtain wid by translating tmp to convention for rotation angles.\n- # Have to account for which quadrant of the x-z plane in which the sun\n- # vector lies. Complete solution here but probably not necessary to\n- # consider QIII and QIV.\n-# wid = pd.Series(index=times)\n-# wid[(xp>=0) & (zp>=0)] = 90 - tmp[(xp>=0) & (zp>=0)] # QI\n-# wid[(xp<0) & (zp>=0)] = -90 - tmp[(xp<0) & (zp>=0)] # QII\n-# wid[(xp<0) & (zp<0)] = -90 - tmp[(xp<0) & (zp<0)] # QIII\n-# wid[(xp>=0) & (zp<0)] = 90 - tmp[(xp>=0) & (zp<0)] # QIV\n+ # azimuth. For example, for a system with tracking axis oriented south, a\n+ # rotation toward the east is negative, and a rotation to the west is\n+ # positive. This is a right-handed rotation around the tracker y-axis.\n \n # Calculate angle from x-y plane to projection of sun vector onto x-z plane\n- # and then obtain wid by translating tmp to convention for rotation angles.\n- wid = 90 - np.degrees(np.arctan2(zp, xp))\n+ # using [1] Eq. 5.\n+\n+ wid = np.degrees(np.arctan2(xp, zp))\n \n # filter for sun above panel horizon\n zen_gt_90 = apparent_zenith > 90\n wid[zen_gt_90] = np.nan\n \n- # Account for backtracking; modified from [1] to account for rotation\n- # angle convention being used here.\n+ # Account for backtracking\n if backtrack:\n- axes_distance = 1/gcr\n- # clip needed for low angles. GH 656\n- temp = np.clip(axes_distance*cosd(wid), -1, 1)\n+ # distance between rows in terms of rack lengths relative to cross-axis\n+ # tilt\n+ axes_distance = 1/(gcr * cosd(cross_axis_tilt))\n \n- # backtrack angle\n- # (always positive b/c acosd returns values between 0 and 180)\n- wc = np.degrees(np.arccos(temp))\n+ # NOTE: account for rare angles below array, see GH 824\n+ temp = np.abs(axes_distance * cosd(wid - cross_axis_tilt))\n \n- # Eq 4 applied when wid in QIV (wid < 0 evalulates True), QI\n+ # backtrack angle using [1], Eq. 14\n with np.errstate(invalid='ignore'):\n- # errstate for GH 622\n- tracker_theta = np.where(wid < 0, wid + wc, wid - wc)\n+ wc = np.degrees(-np.sign(wid)*np.arccos(temp))\n+\n+ # NOTE: in the middle of the day, arccos(temp) is out of range because\n+ # there's no row-to-row shade to avoid, & backtracking is unnecessary\n+ # [1], Eqs. 15-16\n+ with np.errstate(invalid='ignore'):\n+ tracker_theta = wid + np.where(temp < 1, wc, 0)\n else:\n tracker_theta = wid\n \n- tracker_theta = np.minimum(tracker_theta, max_angle)\n- tracker_theta = np.maximum(tracker_theta, -max_angle)\n+ # NOTE: max_angle defined relative to zero-point rotation, not the\n+ # system-plane normal\n+ tracker_theta = np.clip(tracker_theta, -max_angle, max_angle)\n \n- # calculate panel normal vector in panel-oriented x, y, z coordinates.\n- # y-axis is axis of tracker rotation. tracker_theta is a compass angle\n+ # Calculate panel normal vector in panel-oriented x, y, z coordinates.\n+ # y-axis is axis of tracker rotation. tracker_theta is a compass angle\n # (clockwise is positive) rather than a trigonometric angle.\n- # the *0 is a trick to preserve NaN values.\n+ # NOTE: the *0 is a trick to preserve NaN values.\n panel_norm = np.array([sind(tracker_theta),\n tracker_theta*0,\n cosd(tracker_theta)])\n@@ -460,30 +464,28 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n # calculate angle-of-incidence on panel\n aoi = np.degrees(np.arccos(np.abs(np.sum(sun_vec*panel_norm, axis=0))))\n \n- # calculate panel tilt and azimuth\n- # in a coordinate system where the panel tilt is the\n- # angle from horizontal, and the panel azimuth is\n- # the compass angle (clockwise from north) to the projection\n- # of the panel's normal to the earth's surface.\n- # These outputs are provided for convenience and comparison\n- # with other PV software which use these angle conventions.\n+ # Calculate panel tilt and azimuth in a coordinate system where the panel\n+ # tilt is the angle from horizontal, and the panel azimuth is the compass\n+ # angle (clockwise from north) to the projection of the panel's normal to\n+ # the earth's surface. These outputs are provided for convenience and\n+ # comparison with other PV software which use these angle conventions.\n \n- # project normal vector to earth surface.\n- # First rotate about x-axis by angle -axis_tilt so that y-axis is\n- # also parallel to earth surface, then project.\n+ # Project normal vector to earth surface. First rotate about x-axis by\n+ # angle -axis_tilt so that y-axis is also parallel to earth surface, then\n+ # project.\n \n # Calculate standard rotation matrix\n rot_x = np.array([[1, 0, 0],\n [0, cosd(-axis_tilt), -sind(-axis_tilt)],\n [0, sind(-axis_tilt), cosd(-axis_tilt)]])\n \n- # panel_norm_earth contains the normal vector\n- # expressed in earth-surface coordinates\n- # (z normal to surface, y aligned with tracker axis parallel to earth)\n+ # panel_norm_earth contains the normal vector expressed in earth-surface\n+ # coordinates (z normal to surface, y aligned with tracker axis parallel to\n+ # earth)\n panel_norm_earth = np.dot(rot_x, panel_norm).T\n \n- # projection to plane tangent to earth surface,\n- # in earth surface coordinates\n+ # projection to plane tangent to earth surface, in earth surface\n+ # coordinates\n projected_normal = np.array([panel_norm_earth[:, 0],\n panel_norm_earth[:, 1],\n panel_norm_earth[:, 2]*0]).T\n@@ -491,69 +493,22 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n # calculate vector magnitudes\n projected_normal_mag = np.sqrt(np.nansum(projected_normal**2, axis=1))\n \n- # renormalize the projected vector\n- # avoid creating nan values.\n+ # renormalize the projected vector, avoid creating nan values.\n non_zeros = projected_normal_mag != 0\n projected_normal[non_zeros] = (projected_normal[non_zeros].T /\n projected_normal_mag[non_zeros]).T\n \n # calculation of surface_azimuth\n- # 1. Find the angle.\n-# surface_azimuth = pd.Series(\n-# np.degrees(np.arctan(projected_normal[:,1]/projected_normal[:,0])),\n-# index=times)\n surface_azimuth = \\\n np.degrees(np.arctan2(projected_normal[:, 1], projected_normal[:, 0]))\n \n- # 2. Clean up atan when x-coord or y-coord is zero\n-# surface_azimuth[(projected_normal[:,0]==0) & (projected_normal[:,1]>0)] = 90\n-# surface_azimuth[(projected_normal[:,0]==0) & (projected_normal[:,1]<0)] = -90\n-# surface_azimuth[(projected_normal[:,1]==0) & (projected_normal[:,0]>0)] = 0\n-# surface_azimuth[(projected_normal[:,1]==0) & (projected_normal[:,0]<0)] = 180\n-\n- # 3. Correct atan for QII and QIII\n-# surface_azimuth[(projected_normal[:,0]<0) & (projected_normal[:,1]>0)] += 180 # QII\n-# surface_azimuth[(projected_normal[:,0]<0) & (projected_normal[:,1]<0)] += 180 # QIII\n-\n- # 4. Skip to below\n-\n- # at this point surface_azimuth contains angles between -90 and +270,\n- # where 0 is along the positive x-axis,\n- # the y-axis is in the direction of the tracker azimuth,\n- # and positive angles are rotations from the positive x axis towards\n- # the positive y-axis.\n- # Adjust to compass angles\n- # (clockwise rotation from 0 along the positive y-axis)\n-# surface_azimuth[surface_azimuth<=90] = 90 - surface_azimuth[surface_azimuth<=90]\n-# surface_azimuth[surface_azimuth>90] = 450 - surface_azimuth[surface_azimuth>90]\n-\n- # finally rotate to align y-axis with true north\n- # PVLIB_MATLAB has this latitude correction,\n- # but I don't think it's latitude dependent if you always\n- # specify axis_azimuth with respect to North.\n-# if latitude > 0 or True:\n-# surface_azimuth = surface_azimuth - axis_azimuth\n-# else:\n-# surface_azimuth = surface_azimuth - axis_azimuth - 180\n-# surface_azimuth[surface_azimuth<0] = 360 + surface_azimuth[surface_azimuth<0]\n-\n- # the commented code above is mostly part of PVLIB_MATLAB.\n- # My (wholmgren) take is that it can be done more simply.\n- # Say that we're pointing along the postive x axis (likely west).\n- # We just need to rotate 90 degrees to get from the x axis\n- # to the y axis (likely south),\n- # and then add the axis_azimuth to get back to North.\n- # Anything left over is the azimuth that we want,\n- # and we can map it into the [0,360) domain.\n-\n- # 4. Rotate 0 reference from panel's x axis to it's y axis and\n- # then back to North.\n+ # Rotate 0 reference from panel's x-axis to its y-axis and then back to\n+ # north.\n surface_azimuth = 90 - surface_azimuth + axis_azimuth\n \n- # 5. Map azimuth into [0,360) domain.\n- # surface_azimuth[surface_azimuth < 0] += 360\n- # surface_azimuth[surface_azimuth >= 360] -= 360\n- surface_azimuth = surface_azimuth % 360\n+ # Map azimuth into [0,360) domain.\n+ with np.errstate(invalid='ignore'):\n+ surface_azimuth = surface_azimuth % 360\n \n # Calculate surface_tilt\n dotproduct = (panel_norm_earth * projected_normal).sum(axis=1)\n@@ -561,7 +516,7 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n \n # Bundle DataFrame for return values and filter for sun below horizon.\n out = {'tracker_theta': tracker_theta, 'aoi': aoi,\n- 'surface_azimuth': surface_azimuth, 'surface_tilt': surface_tilt}\n+ 'surface_tilt': surface_tilt, 'surface_azimuth': surface_azimuth}\n if index is not None:\n out = pd.DataFrame(out, index=index)\n out = out[['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt']]\n@@ -570,3 +525,154 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n out = {k: np.where(zen_gt_90, np.nan, v) for k, v in out.items()}\n \n return out\n+\n+\n+def calc_axis_tilt(slope_azimuth, slope_tilt, axis_azimuth):\n+ \"\"\"\n+ Calculate tracker axis tilt in the global reference frame when on a sloped\n+ plane.\n+\n+ Parameters\n+ ----------\n+ slope_azimuth : float\n+ direction of normal to slope on horizontal [degrees]\n+ slope_tilt : float\n+ tilt of normal to slope relative to vertical [degrees]\n+ axis_azimuth : float\n+ direction of tracker axes on horizontal [degrees]\n+\n+ Returns\n+ -------\n+ axis_tilt : float\n+ tilt of tracker [degrees]\n+\n+ See also\n+ --------\n+ pvlib.tracking.singleaxis\n+ pvlib.tracking.calc_cross_axis_tilt\n+\n+ Notes\n+ -----\n+ See [1]_ for derivation of equations.\n+\n+ References\n+ ----------\n+ .. [1] Kevin Anderson and Mark Mikofski, \"Slope-Aware Backtracking for\n+ Single-Axis Trackers\", Technical Report NREL/TP-5K00-76626, July 2020.\n+ https://www.nrel.gov/docs/fy20osti/76626.pdf\n+ \"\"\"\n+ delta_gamma = axis_azimuth - slope_azimuth\n+ # equations 18-19\n+ tan_axis_tilt = cosd(delta_gamma) * tand(slope_tilt)\n+ return np.degrees(np.arctan(tan_axis_tilt))\n+\n+\n+def _calc_tracker_norm(ba, bg, dg):\n+ \"\"\"\n+ Calculate tracker normal, v, cross product of tracker axis and unit normal,\n+ N, to the system slope plane.\n+\n+ Parameters\n+ ----------\n+ ba : float\n+ axis tilt [degrees]\n+ bg : float\n+ ground tilt [degrees]\n+ dg : float\n+ delta gamma, difference between axis and ground azimuths [degrees]\n+\n+ Returns\n+ -------\n+ vector : tuple\n+ vx, vy, vz\n+ \"\"\"\n+ cos_ba = cosd(ba)\n+ cos_bg = cosd(bg)\n+ sin_bg = sind(bg)\n+ sin_dg = sind(dg)\n+ vx = sin_dg * cos_ba * cos_bg\n+ vy = sind(ba)*sin_bg + cosd(dg)*cos_ba*cos_bg\n+ vz = -sin_dg*sin_bg*cos_ba\n+ return vx, vy, vz\n+\n+\n+def _calc_beta_c(v, dg, ba):\n+ \"\"\"\n+ Calculate the cross-axis tilt angle.\n+\n+ Parameters\n+ ----------\n+ v : tuple\n+ tracker normal\n+ dg : float\n+ delta gamma, difference between axis and ground azimuths [degrees]\n+ ba : float\n+ axis tilt [degrees]\n+\n+ Returns\n+ -------\n+ beta_c : float\n+ cross-axis tilt angle [radians]\n+ \"\"\"\n+ vnorm = np.sqrt(np.dot(v, v))\n+ beta_c = np.arcsin(\n+ ((v[0]*cosd(dg) - v[1]*sind(dg)) * sind(ba) + v[2]*cosd(ba)) / vnorm)\n+ return beta_c\n+\n+\n+def calc_cross_axis_tilt(\n+ slope_azimuth, slope_tilt, axis_azimuth, axis_tilt):\n+ \"\"\"\n+ Calculate the angle, relative to horizontal, of the line formed by the\n+ intersection between the slope containing the tracker axes and a plane\n+ perpendicular to the tracker axes.\n+\n+ Use the cross-axis tilt to avoid row-to-row shade when backtracking on a\n+ slope not parallel with the axis azimuth. Cross-axis tilt should be\n+ specified using a right-handed convention. For example, trackers with axis\n+ azimuth of 180 degrees (heading south) will have a negative cross-axis tilt\n+ if the tracker axes plane slopes down to the east and positive cross-axis\n+ tilt if the tracker axes plane slopes up to the east.\n+\n+ Parameters\n+ ----------\n+ slope_azimuth : float\n+ direction of the normal to the slope containing the tracker axes, when\n+ projected on the horizontal [degrees]\n+ slope_tilt : float\n+ angle of the slope containing the tracker axes, relative to horizontal\n+ [degrees]\n+ axis_azimuth : float\n+ direction of tracker axes projected on the horizontal [degrees]\n+ axis_tilt : float\n+ tilt of trackers relative to horizontal [degrees]\n+\n+ Returns\n+ -------\n+ cross_axis_tilt : float\n+ angle, relative to horizontal, of the line formed by the intersection\n+ between the slope containing the tracker axes and a plane perpendicular\n+ to the tracker axes [degrees]\n+\n+ See also\n+ --------\n+ pvlib.tracking.singleaxis\n+ pvlib.tracking.calc_axis_tilt\n+\n+ Notes\n+ -----\n+ See [1]_ for derivation of equations.\n+\n+ References\n+ ----------\n+ .. [1] Kevin Anderson and Mark Mikofski, \"Slope-Aware Backtracking for\n+ Single-Axis Trackers\", Technical Report NREL/TP-5K00-76626, July 2020.\n+ https://www.nrel.gov/docs/fy20osti/76626.pdf\n+ \"\"\"\n+ # delta-gamma, difference between axis and slope azimuths\n+ delta_gamma = axis_azimuth - slope_azimuth\n+ # equation 22\n+ v = _calc_tracker_norm(axis_tilt, slope_tilt, delta_gamma)\n+ # equation 26\n+ beta_c = _calc_beta_c(v, delta_gamma, axis_tilt)\n+ return np.degrees(beta_c)\n", "test_patch": "diff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -6,8 +6,10 @@\n from conftest import assert_frame_equal\n from numpy.testing import assert_allclose\n \n+import pvlib\n from pvlib.location import Location\n from pvlib import tracking\n+from conftest import DATA_DIR\n \n SINGLEAXIS_COL_ORDER = ['tracker_theta', 'aoi',\n 'surface_azimuth', 'surface_tilt']\n@@ -41,7 +43,7 @@ def test_scalars():\n expect = {'tracker_theta': 0, 'aoi': 10, 'surface_azimuth': 90,\n 'surface_tilt': 0}\n for k, v in expect.items():\n- assert_allclose(tracker_data[k], v)\n+ assert np.isclose(tracker_data[k], v)\n \n \n def test_arrays():\n@@ -55,7 +57,7 @@ def test_arrays():\n expect = {'tracker_theta': 0, 'aoi': 10, 'surface_azimuth': 90,\n 'surface_tilt': 0}\n for k, v in expect.items():\n- assert_allclose(tracker_data[k], v)\n+ assert_allclose(tracker_data[k], v, atol=1e-7)\n \n \n def test_nans():\n@@ -71,7 +73,7 @@ def test_nans():\n 'surface_azimuth': np.array([90, nan, nan]),\n 'surface_tilt': np.array([0, nan, nan])}\n for k, v in expect.items():\n- assert_allclose(tracker_data[k], v)\n+ assert_allclose(tracker_data[k], v, atol=1e-7)\n \n # repeat with Series because nans can differ\n apparent_zenith = pd.Series(apparent_zenith)\n@@ -268,7 +270,7 @@ def test_horizon_tilted():\n out = tracking.singleaxis(solar_zenith, solar_azimuth, axis_tilt=90,\n axis_azimuth=180, backtrack=False, max_angle=180)\n expected = pd.DataFrame(np.array(\n- [[ 180., 45., 0., 90.],\n+ [[-180., 45., 0., 90.],\n [ 0., 45., 180., 90.],\n [ 179., 45., 359., 90.]]),\n columns=['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt'])\n@@ -276,15 +278,15 @@ def test_horizon_tilted():\n \n \n def test_low_sun_angles():\n- # GH 656\n+ # GH 656, 824\n result = tracking.singleaxis(\n apparent_zenith=80, apparent_azimuth=338, axis_tilt=30,\n axis_azimuth=180, max_angle=60, backtrack=True, gcr=0.35)\n expected = {\n- 'tracker_theta': np.array([-50.31051385]),\n- 'aoi': np.array([61.35300178]),\n- 'surface_azimuth': np.array([112.53615425]),\n- 'surface_tilt': np.array([56.42233095])}\n+ 'tracker_theta': np.array([60.0]),\n+ 'aoi': np.array([80.420987]),\n+ 'surface_azimuth': np.array([253.897886]),\n+ 'surface_tilt': np.array([64.341094])}\n for k, v in result.items():\n assert_allclose(expected[k], v)\n \n@@ -447,6 +449,7 @@ def test_SingleAxisTracker___repr__():\n max_angle: 45\n backtrack: True\n gcr: 0.25\n+ cross_axis_tilt: 0.0\n name: None\n surface_tilt: None\n surface_azimuth: None\n@@ -471,6 +474,7 @@ def test_LocalizedSingleAxisTracker___repr__():\n max_angle: 90\n backtrack: True\n gcr: 0.25\n+ cross_axis_tilt: 0.0\n name: None\n surface_tilt: None\n surface_azimuth: None\n@@ -486,3 +490,87 @@ def test_LocalizedSingleAxisTracker___repr__():\n tz: UTC\"\"\"\n \n assert localized_system.__repr__() == expected\n+\n+\n+def test_calc_axis_tilt():\n+ # expected values\n+ expected_axis_tilt = 2.239 # [degrees]\n+ expected_side_slope = 9.86649274360294 # [degrees]\n+ expected = DATA_DIR / 'singleaxis_tracker_wslope.csv'\n+ expected = pd.read_csv(expected, index_col='timestamp', parse_dates=True)\n+ # solar positions\n+ starttime = '2017-01-01T00:30:00-0300'\n+ stoptime = '2017-12-31T23:59:59-0300'\n+ lat, lon = -27.597300, -48.549610\n+ times = pd.DatetimeIndex(pd.date_range(starttime, stoptime, freq='H'))\n+ solpos = pvlib.solarposition.get_solarposition(times, lat, lon)\n+ # singleaxis tracker w/slope data\n+ slope_azimuth, slope_tilt = 77.34, 10.1149\n+ axis_azimuth = 0.0\n+ max_angle = 75.0\n+ # Note: GCR is relative to horizontal distance between rows\n+ gcr = 0.33292759 # GCR = length / horizontal_pitch = 1.64 / 5 / cos(9.86)\n+ # calculate tracker axis zenith\n+ axis_tilt = tracking.calc_axis_tilt(\n+ slope_azimuth, slope_tilt, axis_azimuth=axis_azimuth)\n+ assert np.isclose(axis_tilt, expected_axis_tilt)\n+ # calculate cross-axis tilt and relative rotation\n+ cross_axis_tilt = tracking.calc_cross_axis_tilt(\n+ slope_azimuth, slope_tilt, axis_azimuth, axis_tilt)\n+ assert np.isclose(cross_axis_tilt, expected_side_slope)\n+ sat = tracking.singleaxis(\n+ solpos.apparent_zenith, solpos.azimuth, axis_tilt, axis_azimuth,\n+ max_angle, backtrack=True, gcr=gcr, cross_axis_tilt=cross_axis_tilt)\n+ np.testing.assert_allclose(\n+ sat['tracker_theta'], expected['tracker_theta'], atol=1e-7)\n+ np.testing.assert_allclose(sat['aoi'], expected['aoi'], atol=1e-7)\n+ np.testing.assert_allclose(\n+ sat['surface_azimuth'], expected['surface_azimuth'], atol=1e-7)\n+ np.testing.assert_allclose(\n+ sat['surface_tilt'], expected['surface_tilt'], atol=1e-7)\n+\n+\n+def test_slope_aware_backtracking():\n+ \"\"\"\n+ Test validation data set from https://www.nrel.gov/docs/fy20osti/76626.pdf\n+ \"\"\"\n+ expected_data = np.array(\n+ [('2019-01-01T08:00-0500', 2.404287, 122.79177, -84.440, -10.899),\n+ ('2019-01-01T09:00-0500', 11.263058, 133.288729, -72.604, -25.747),\n+ ('2019-01-01T10:00-0500', 18.733558, 145.285552, -59.861, -59.861),\n+ ('2019-01-01T11:00-0500', 24.109076, 158.939435, -45.578, -45.578),\n+ ('2019-01-01T12:00-0500', 26.810735, 173.931802, -28.764, -28.764),\n+ ('2019-01-01T13:00-0500', 26.482495, 189.371536, -8.475, -8.475),\n+ ('2019-01-01T14:00-0500', 23.170447, 204.13681, 15.120, 15.120),\n+ ('2019-01-01T15:00-0500', 17.296785, 217.446538, 39.562, 39.562),\n+ ('2019-01-01T16:00-0500', 9.461862, 229.102218, 61.587, 32.339),\n+ ('2019-01-01T17:00-0500', 0.524817, 239.330401, 79.530, 5.490)],\n+ dtype=[\n+ ('Time', '<M8[h]'), ('ApparentElevation', '<f8'),\n+ ('SolarAzimuth', '<f8'), ('TrueTracking', '<f8'),\n+ ('Backtracking', '<f8')])\n+ expected_axis_tilt = 9.666\n+ expected_slope_angle = -2.576\n+ slope_azimuth, slope_tilt = 180.0, 10.0\n+ axis_azimuth = 195.0\n+ axis_tilt = tracking.calc_axis_tilt(\n+ slope_azimuth, slope_tilt, axis_azimuth)\n+ assert np.isclose(axis_tilt, expected_axis_tilt, rtol=1e-3, atol=1e-3)\n+ cross_axis_tilt = tracking.calc_cross_axis_tilt(\n+ slope_azimuth, slope_tilt, axis_azimuth, axis_tilt)\n+ assert np.isclose(\n+ cross_axis_tilt, expected_slope_angle, rtol=1e-3, atol=1e-3)\n+ sat = tracking.singleaxis(\n+ 90.0-expected_data['ApparentElevation'], expected_data['SolarAzimuth'],\n+ axis_tilt, axis_azimuth, max_angle=90.0, backtrack=True, gcr=0.5,\n+ cross_axis_tilt=cross_axis_tilt)\n+ np.testing.assert_allclose(\n+ sat['tracker_theta'], expected_data['Backtracking'],\n+ rtol=1e-3, atol=1e-3)\n+ truetracking = tracking.singleaxis(\n+ 90.0-expected_data['ApparentElevation'], expected_data['SolarAzimuth'],\n+ axis_tilt, axis_azimuth, max_angle=90.0, backtrack=False, gcr=0.5,\n+ cross_axis_tilt=cross_axis_tilt)\n+ np.testing.assert_allclose(\n+ truetracking['tracker_theta'], expected_data['TrueTracking'],\n+ rtol=1e-3, atol=1e-3)\n", "problem_statement": "backtracking for rare case when sun below tracker improvement\n**Describe the bug**\r\n- related to #656\r\n- in the rare case when the sun rays are below the tracker, then the top of the next row is shaded\r\n- currently tracker backtracks away from sun, back is facing sun instead of front\r\n- this only happens for tilted trackers and very low sun angles, either early morning or late evening when the sun rays are furthest north or south\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. create a tilted tracker\r\n```python\r\n# in Brazil so facing north\r\naxis_azimuth = 0.0 \r\naxis_tilt = 20\r\nmax_angle = 75.0\r\ngcr = 0.35\r\n```\r\n2. pick the earliest morning (or latest evening) timestamp\r\n```python\r\nimport pvlib\r\nimport pandas as pd\r\n\r\n# Brazil, timezone is UTC-3[hrs]\r\nstarttime = '2017-01-01T00:30:00-0300'\r\nstoptime = '2017-12-31T23:59:59-0300'\r\nlat, lon = -27.597300, -48.549610\r\ntimes = pd.DatetimeIndex(pd.date_range(\r\n starttime, stoptime, freq='H'))\r\nsolpos = pvlib.solarposition.get_solarposition(\r\n times, lat, lon)\r\n# get the early times\r\nts0 = '2017-01-01 05:30:00-03:00'\r\nts1 = '2017-01-01 12:30:00-03:00'\r\napparent_zenith = solpos['apparent_zenith'][ts0:ts1]\r\nazimuth = solpos['azimuth'][ts0:ts1]\r\nsat = pvlib.tracking.singleaxis(\r\n apparent_zenith, azimuth, axis_tilt, axis_azimuth, max_angle, True, gcr)\r\n```\r\n3. notice that the tracker suddenly jumps from one side facing east to west\r\n```\r\n tracker_theta aoi surface_azimuth surface_tilt\r\n2017-01-01 05:30:00-03:00 -21.964540 62.721237 310.299287 29.368272\r\n2017-01-01 06:30:00-03:00 16.231156 69.264752 40.403367 25.546154\r\n2017-01-01 07:30:00-03:00 69.073645 20.433849 82.548858 70.389280\r\n2017-01-01 08:30:00-03:00 54.554616 18.683626 76.316479 56.978562\r\n2017-01-01 09:30:00-03:00 40.131687 17.224233 67.917292 44.072837\r\n2017-01-01 10:30:00-03:00 25.769332 16.144347 54.683567 32.194782\r\n2017-01-01 11:30:00-03:00 11.439675 15.509532 30.610665 22.923644\r\n2017-01-01 12:30:00-03:00 -2.877428 15.358209 351.639727 20.197537\r\n```\r\n\r\n4. AOI is also wrong\r\n\r\n**Expected behavior**\r\nThe tracker should avoid shade. It should not jump from one direction to the other. If the sun ray is below the tracker then it will need to track to it's max rotation or backtrack. If there is shading at it's max rotation then it should track backtrack to zero, or perhaps parallel to the sun rays. Perhaps if bifacial, then it could go backwards, 180 from the correct backtrack position to show it's backside to the sun.\r\n\r\nproposed algorithm (_updated after [this comment](#issuecomment-559154895)_):\r\n```python\r\nif backtracking:\r\n # cos(R) = L / Lx, R is rotation, L is surface length,\r\n # Lx is shadow on ground, tracker shades when Lx > x\r\n # x is row spacing related to GCR, x = L/GCR\r\n lrot = np.cos(tr_rot_no_lim) # tracker rotation not limited by max angle\r\n\r\n # Note: if tr_rot > 90[deg] then lrot < 0 \r\n # which *can* happen at low angles if axis tilt > 0\r\n # tracker should never backtrack more than 90[deg], when lrot = 0\r\n cos_rot = np.minimum(np.abs(lrot) / self.gcr, 1)\r\n\r\n # so if lrot<0 tracker should backtrack forward\r\n # backtrack_rot = np.sign(lrot) * np.arccos(cos_rot)\r\n\r\n # NOTE: updated after comment from @kevinsa5 at Nov 27, 2019, 8:16 AM PST\r\n # to remove sign()\r\n backtrack_rot = np.arccos(cos_rot)\r\n```\r\n\r\nalso remove abs from aoi calculation\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/c699575cb6857674f0a96348b77e10c805e741c7/pvlib/tracking.py#L461\r\n\r\n**Screenshots**\r\nIf applicable, add screenshots to help explain your problem.\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.6.3\r\n - ``pandas.__version__``: 0.24\r\n - python: 3.7\r\n\r\n**Additional context**\r\nAdd any other context about the problem here.\r\n\n[STY] remove old comments from single axis tracking\n**Describe the bug**\r\nAfter #823 is merged there may be stale comments in `pvlib.tracking.singleaxis` and commented code that can be removed. This might make the code more readable. It would also resolve some stickler complaints about long lines.\r\n\r\n**To Reproduce**\r\nComments to remove:\r\n1. [L375-L379](../blob/e210b8253458a60c95fc21939e9817271cf51934/pvlib/tracking.py#L375-L379) - the tracking algorithm now follows [1] that uses clockwise rotation around z-axis from north\r\n2. [L393-L395](../blob/e210b8253458a60c95fc21939e9817271cf51934/pvlib/tracking.py#L393-L395) - ditto\r\n3. [L400-L410](../blob/e210b8253458a60c95fc21939e9817271cf51934/pvlib/tracking.py#L400-L410) - ditto\r\n4. [L441-L452](../blob/e210b8253458a60c95fc21939e9817271cf51934/pvlib/tracking.py#L441-L452) - pvlib has been using arctan2(x,z) in `pvlib.tracking.singleaxis` for 6 years since 1fb82cc262e43e1d2b55e4b5510a1a5e7e340667, so I believe these comments are unnecessary now\r\n5. [L471-L472](../blob/e210b8253458a60c95fc21939e9817271cf51934/pvlib/tracking.py#L471-L472) - this commented code was updated in #823, should we leave it or delete it?\r\n3. [L553-L555](../blob/e210b8253458a60c95fc21939e9817271cf51934/pvlib/tracking.py#L553-L555)\r\n\r\netc.\r\n\r\n[1] https://www.nrel.gov/docs/fy20osti/76626.pdf\r\n\r\n**Expected behavior**\r\nA clear and concise description of what you expected to happen.\r\n\r\n**Screenshots**\r\nIf applicable, add screenshots to help explain your problem.\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: \r\n - ``pandas.__version__``: \r\n - python:\r\n\r\n**Additional context**\r\nAdd any other context about the problem here.\r\n\n", "hints_text": "\n", "created_at": "2019-11-22T09:31:54Z", "version": "0.6", "FAIL_TO_PASS": ["pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_LocalizedSingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_slope_aware_backtracking"], "PASS_TO_PASS": ["pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_creation", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_LocalizedSingleAxisTracker_creation", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_localize", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_localize_location", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_get_irradiance"], "environment_setup_commit": "b91d178868d193afd56f8e3b013661a473d699c3"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1368", "base_commit": "93e84041387c80bf8738fe96409a0cfd5852c29a", "patch": "diff --git a/pvlib/iotools/crn.py b/pvlib/iotools/crn.py\n--- a/pvlib/iotools/crn.py\n+++ b/pvlib/iotools/crn.py\n@@ -2,15 +2,14 @@\n \"\"\"\n \n import pandas as pd\n-import numpy as np\n \n \n-HEADERS = (\n- 'WBANNO UTC_DATE UTC_TIME LST_DATE LST_TIME CRX_VN LONGITUDE LATITUDE '\n- 'AIR_TEMPERATURE PRECIPITATION SOLAR_RADIATION SR_FLAG '\n- 'SURFACE_TEMPERATURE ST_TYPE ST_FLAG RELATIVE_HUMIDITY RH_FLAG '\n- 'SOIL_MOISTURE_5 SOIL_TEMPERATURE_5 WETNESS WET_FLAG WIND_1_5 WIND_FLAG'\n-)\n+HEADERS = [\n+ 'WBANNO', 'UTC_DATE', 'UTC_TIME', 'LST_DATE', 'LST_TIME', 'CRX_VN',\n+ 'LONGITUDE', 'LATITUDE', 'AIR_TEMPERATURE', 'PRECIPITATION',\n+ 'SOLAR_RADIATION', 'SR_FLAG', 'SURFACE_TEMPERATURE', 'ST_TYPE', 'ST_FLAG',\n+ 'RELATIVE_HUMIDITY', 'RH_FLAG', 'SOIL_MOISTURE_5', 'SOIL_TEMPERATURE_5',\n+ 'WETNESS', 'WET_FLAG', 'WIND_1_5', 'WIND_FLAG']\n \n VARIABLE_MAP = {\n 'LONGITUDE': 'longitude',\n@@ -24,6 +23,21 @@\n 'WIND_FLAG': 'wind_speed_flag'\n }\n \n+NAN_DICT = {\n+ 'CRX_VN': -99999,\n+ 'AIR_TEMPERATURE': -9999,\n+ 'PRECIPITATION': -9999,\n+ 'SOLAR_RADIATION': -99999,\n+ 'SURFACE_TEMPERATURE': -9999,\n+ 'RELATIVE_HUMIDITY': -9999,\n+ 'SOIL_MOISTURE_5': -99,\n+ 'SOIL_TEMPERATURE_5': -9999,\n+ 'WETNESS': -9999,\n+ 'WIND_1_5': -99}\n+\n+# Add NUL characters to possible NaN values for all columns\n+NAN_DICT = {k: [v, '\\x00\\x00\\x00\\x00\\x00\\x00'] for k, v in NAN_DICT.items()}\n+\n # as specified in CRN README.txt file. excludes 1 space between columns\n WIDTHS = [5, 8, 4, 8, 4, 6, 7, 7, 7, 7, 6, 1, 7, 1, 1, 5, 1, 7, 7, 5, 1, 6, 1]\n # add 1 to make fields contiguous (required by pandas.read_fwf)\n@@ -40,15 +54,22 @@\n ]\n \n \n-def read_crn(filename):\n- \"\"\"\n- Read a NOAA USCRN fixed-width file into pandas dataframe. The CRN is\n- described in [1]_ and [2]_.\n+def read_crn(filename, map_variables=True):\n+ \"\"\"Read a NOAA USCRN fixed-width file into a pandas dataframe.\n+\n+ The CRN network consists of over 100 meteorological stations covering the\n+ U.S. and is described in [1]_ and [2]_. The primary goal of CRN is to\n+ provide long-term measurements of temperature, precipitation, and soil\n+ moisture and temperature. Additionally, global horizontal irradiance (GHI)\n+ is measured at each site using a photodiode pyranometer.\n \n Parameters\n ----------\n filename: str, path object, or file-like\n filepath or url to read for the fixed-width file.\n+ map_variables: boolean, default: True\n+ When true, renames columns of the Dataframe to pvlib variable names\n+ where applicable. See variable :const:`VARIABLE_MAP`.\n \n Returns\n -------\n@@ -60,12 +81,12 @@ def read_crn(filename):\n -----\n CRN files contain 5 minute averages labeled by the interval ending\n time. Here, missing data is flagged as NaN, rather than the lowest\n- possible integer for a field (e.g. -999 or -99). Air temperature in\n- deg C. Wind speed in m/s at a height of 1.5 m above ground level.\n+ possible integer for a field (e.g. -999 or -99). Air temperature is in\n+ deg C and wind speed is in m/s at a height of 1.5 m above ground level.\n \n- Variables corresponding to standard pvlib variables are renamed,\n+ Variables corresponding to standard pvlib variables are by default renamed,\n e.g. `SOLAR_RADIATION` becomes `ghi`. See the\n- `pvlib.iotools.crn.VARIABLE_MAP` dict for the complete mapping.\n+ :const:`pvlib.iotools.crn.VARIABLE_MAP` dict for the complete mapping.\n \n CRN files occasionally have a set of null characters on a line\n instead of valid data. This function drops those lines. Sometimes\n@@ -85,16 +106,13 @@ def read_crn(filename):\n Amer. Meteor. Soc., 94, 489-498. :doi:`10.1175/BAMS-D-12-00170.1`\n \"\"\"\n \n- # read in data. set fields with NUL characters to NaN\n- data = pd.read_fwf(filename, header=None, names=HEADERS.split(' '),\n- widths=WIDTHS, na_values=['\\x00\\x00\\x00\\x00\\x00\\x00'])\n- # at this point we only have NaNs from NUL characters, not -999 etc.\n- # these bad rows need to be removed so that dtypes can be set.\n- # NaNs require float dtype so we run into errors if we don't do this.\n- data = data.dropna(axis=0)\n- # loop here because dtype kwarg not supported in read_fwf until 0.20\n- for (col, _dtype) in zip(data.columns, DTYPES):\n- data[col] = data[col].astype(_dtype)\n+ # read in data\n+ data = pd.read_fwf(filename, header=None, names=HEADERS, widths=WIDTHS,\n+ na_values=NAN_DICT)\n+ # Remove rows with all nans\n+ data = data.dropna(axis=0, how='all')\n+ # set dtypes here because dtype kwarg not supported in read_fwf until 0.20\n+ data = data.astype(dict(zip(HEADERS, DTYPES)))\n \n # set index\n # UTC_TIME does not have leading 0s, so must zfill(4) to comply\n@@ -103,19 +121,8 @@ def read_crn(filename):\n dtindex = pd.to_datetime(dts['UTC_DATE'] + dts['UTC_TIME'].str.zfill(4),\n format='%Y%m%d%H%M', utc=True)\n data = data.set_index(dtindex)\n- try:\n- # to_datetime(utc=True) does not work in older versions of pandas\n- data = data.tz_localize('UTC')\n- except TypeError:\n- pass\n-\n- # Now we can set nans. This could be done a per column basis to be\n- # safer, since in principle a real -99 value could occur in a -9999\n- # column. Very unlikely to see that in the real world.\n- for val in [-99, -999, -9999]:\n- # consider replacing with .replace([-99, -999, -9999])\n- data = data.where(data != val, np.nan)\n-\n- data = data.rename(columns=VARIABLE_MAP)\n+\n+ if map_variables:\n+ data = data.rename(columns=VARIABLE_MAP)\n \n return data\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_crn.py b/pvlib/tests/iotools/test_crn.py\n--- a/pvlib/tests/iotools/test_crn.py\n+++ b/pvlib/tests/iotools/test_crn.py\n@@ -3,11 +3,11 @@\n from numpy import dtype, nan\n import pytest\n from pvlib.iotools import crn\n-from ..conftest import DATA_DIR, assert_frame_equal\n+from ..conftest import DATA_DIR, assert_frame_equal, assert_index_equal\n \n \n @pytest.fixture\n-def columns():\n+def columns_mapped():\n return [\n 'WBANNO', 'UTC_DATE', 'UTC_TIME', 'LST_DATE', 'LST_TIME', 'CRX_VN',\n 'longitude', 'latitude', 'temp_air', 'PRECIPITATION', 'ghi',\n@@ -17,6 +17,16 @@ def columns():\n 'WETNESS', 'WET_FLAG', 'wind_speed', 'wind_speed_flag']\n \n \[email protected]\n+def columns_unmapped():\n+ return [\n+ 'WBANNO', 'UTC_DATE', 'UTC_TIME', 'LST_DATE', 'LST_TIME', 'CRX_VN',\n+ 'LONGITUDE', 'LATITUDE', 'AIR_TEMPERATURE', 'PRECIPITATION',\n+ 'SOLAR_RADIATION', 'SR_FLAG', 'SURFACE_TEMPERATURE', 'ST_TYPE',\n+ 'ST_FLAG', 'RELATIVE_HUMIDITY', 'RH_FLAG', 'SOIL_MOISTURE_5',\n+ 'SOIL_TEMPERATURE_5', 'WETNESS', 'WET_FLAG', 'WIND_1_5', 'WIND_FLAG']\n+\n+\n @pytest.fixture\n def dtypes():\n return [\n@@ -39,7 +49,7 @@ def testfile_problems():\n return DATA_DIR / 'CRN_with_problems.txt'\n \n \n-def test_read_crn(testfile, columns, dtypes):\n+def test_read_crn(testfile, columns_mapped, dtypes):\n index = pd.DatetimeIndex(['2019-01-01 16:10:00',\n '2019-01-01 16:15:00',\n '2019-01-01 16:20:00',\n@@ -54,25 +64,31 @@ def test_read_crn(testfile, columns, dtypes):\n 0.0, 340.0, 0, 4.3, 'C', 0, 83.0, 0, nan, nan, 1183, 0, 0.53, 0],\n [53131, 20190101, 1625, 20190101, 925, 3, -111.17, 32.24, 4.0,\n 0.0, 393.0, 0, 4.8, 'C', 0, 81.0, 0, nan, nan, 1223, 0, 0.64, 0]])\n- expected = pd.DataFrame(values, columns=columns, index=index)\n+ expected = pd.DataFrame(values, columns=columns_mapped, index=index)\n for (col, _dtype) in zip(expected.columns, dtypes):\n expected[col] = expected[col].astype(_dtype)\n out = crn.read_crn(testfile)\n assert_frame_equal(out, expected)\n \n \n-def test_read_crn_problems(testfile_problems, columns, dtypes):\n+# Test map_variables=False returns correct column names\n+def test_read_crn_map_variables(testfile, columns_unmapped, dtypes):\n+ out = crn.read_crn(testfile, map_variables=False)\n+ assert_index_equal(out.columns, pd.Index(columns_unmapped))\n+\n+\n+def test_read_crn_problems(testfile_problems, columns_mapped, dtypes):\n # GH1025\n index = pd.DatetimeIndex(['2020-07-06 12:00:00',\n '2020-07-06 13:10:00'],\n freq=None).tz_localize('UTC')\n values = np.array([\n- [92821, 20200706, 1200, 20200706, 700, '3', -80.69, 28.62, 24.9,\n- 0.0, 190.0, 0, 25.5, 'C', 0, 93.0, 0, nan, nan, 990, 0, 1.57, 0],\n+ [92821, 20200706, 1200, 20200706, 700, '3.0', -80.69, 28.62, 24.9,\n+ 0.0, np.nan, 0, 25.5, 'C', 0, 93.0, 0, nan, nan, 990, 0, 1.57, 0],\n [92821, 20200706, 1310, 20200706, 810, '2.623', -80.69, 28.62,\n 26.9, 0.0, 430.0, 0, 30.2, 'C', 0, 87.0, 0, nan, nan, 989, 0,\n 1.64, 0]])\n- expected = pd.DataFrame(values, columns=columns, index=index)\n+ expected = pd.DataFrame(values, columns=columns_mapped, index=index)\n for (col, _dtype) in zip(expected.columns, dtypes):\n expected[col] = expected[col].astype(_dtype)\n out = crn.read_crn(testfile_problems)\n", "problem_statement": "`read_crn` returns -99999 instead of `NaN`\n**Describe the bug**\r\n`read_crn` fails to map -99999 to `NaN`\r\n\r\n**To Reproduce**\r\n```python\r\nfrom pvlib.iotools import read_crn\r\ncrn = read_crn('https://www.ncei.noaa.gov/pub/data/uscrn/products/subhourly01/2021/CRNS0101-05-2021-NY_Millbrook_3_W.txt')\r\ncrn.loc['2021-12-14 0930':'2021-12-14 1130', 'ghi']\r\n2021-12-14 09:30:00+00:00 0.0\r\n2021-12-14 09:35:00+00:00 0.0\r\n2021-12-14 09:40:00+00:00 0.0\r\n2021-12-14 09:45:00+00:00 0.0\r\n2021-12-14 09:50:00+00:00 0.0\r\n2021-12-14 09:55:00+00:00 0.0\r\n2021-12-14 10:00:00+00:00 0.0\r\n2021-12-14 10:05:00+00:00 -99999.0\r\n2021-12-14 10:10:00+00:00 -99999.0\r\n2021-12-14 10:15:00+00:00 -99999.0\r\n2021-12-14 10:20:00+00:00 -99999.0\r\n2021-12-14 10:25:00+00:00 -99999.0\r\n2021-12-14 10:30:00+00:00 -99999.0\r\n2021-12-14 10:35:00+00:00 -99999.0\r\n2021-12-14 10:40:00+00:00 -99999.0\r\n2021-12-14 10:45:00+00:00 -99999.0\r\n2021-12-14 10:50:00+00:00 -99999.0\r\n2021-12-14 10:55:00+00:00 -99999.0\r\n2021-12-14 11:00:00+00:00 -99999.0\r\n2021-12-14 11:05:00+00:00 0.0\r\n2021-12-14 11:10:00+00:00 0.0\r\n2021-12-14 11:15:00+00:00 0.0\r\n2021-12-14 11:20:00+00:00 0.0\r\n2021-12-14 11:25:00+00:00 0.0\r\n2021-12-14 11:30:00+00:00 0.0\r\nName: ghi, dtype: float64\r\n```\r\n\r\n**Expected behavior**\r\nShould return `NaN` instead of -99999\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.9.0\r\n - ``pandas.__version__``: 1.0.3 (doesn't matter)\r\n - python: 3.7\r\n\r\n**Additional context**\r\n\r\nDocumentation [here](https://www.ncei.noaa.gov/pub/data/uscrn/products/subhourly01/) says\r\n\r\n> C. Missing data are indicated by the lowest possible integer for a \r\n> given column format, such as -9999.0 for 7-character fields with \r\n> one decimal place or -99.000 for 7-character fields with three\r\n> decimal places.\r\n\r\nSo we should change \r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a/pvlib/iotools/crn.py#L112-L117\r\n\r\nto include -99999 and perhaps -999999. Or do the smarter thing as discussed in the comment.\r\n\r\nalso https://github.com/SolarArbiter/solarforecastarbiter-core/issues/773\n", "hints_text": "", "created_at": "2022-01-05T22:59:26Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_crn.py::test_read_crn_map_variables"], "PASS_TO_PASS": ["pvlib/tests/iotools/test_crn.py::test_read_crn"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1448", "base_commit": "8d0f863da92739669e01ac4da4145e4547638b50", "patch": "diff --git a/pvlib/iotools/crn.py b/pvlib/iotools/crn.py\n--- a/pvlib/iotools/crn.py\n+++ b/pvlib/iotools/crn.py\n@@ -2,6 +2,7 @@\n \"\"\"\n \n import pandas as pd\n+import numpy as np\n \n \n HEADERS = [\n@@ -107,13 +108,24 @@ def read_crn(filename, map_variables=True):\n \"\"\"\n \n # read in data\n+ # TODO: instead of parsing as strings and then post-processing, switch to\n+ # pd.read_fwf(..., dtype=dict(zip(HEADERS, DTYPES)), skip_blank_lines=True)\n+ # when our minimum pandas >= 1.2.0 (skip_blank_lines bug for <1.2.0).\n+ # As a workaround, parse all values as strings, then drop NaN, then cast\n+ # to the appropriate dtypes, and mask \"sentinal\" NaN (e.g. -9999.0)\n data = pd.read_fwf(filename, header=None, names=HEADERS, widths=WIDTHS,\n- na_values=NAN_DICT)\n- # Remove rows with all nans\n+ dtype=str)\n+\n+ # drop empty (bad) lines\n data = data.dropna(axis=0, how='all')\n- # set dtypes here because dtype kwarg not supported in read_fwf until 0.20\n+\n+ # can't set dtypes in read_fwf because int cols can't contain NaN, so\n+ # do it here instead\n data = data.astype(dict(zip(HEADERS, DTYPES)))\n \n+ # finally, replace -999 values with NaN\n+ data = data.replace(NAN_DICT, value=np.nan)\n+\n # set index\n # UTC_TIME does not have leading 0s, so must zfill(4) to comply\n # with %H%M format\ndiff --git a/pvlib/solarposition.py b/pvlib/solarposition.py\n--- a/pvlib/solarposition.py\n+++ b/pvlib/solarposition.py\n@@ -22,6 +22,7 @@\n import pandas as pd\n import scipy.optimize as so\n import warnings\n+import datetime\n \n from pvlib import atmosphere\n from pvlib.tools import datetime_to_djd, djd_to_datetime\n@@ -574,9 +575,10 @@ def sun_rise_set_transit_ephem(times, latitude, longitude,\n trans = []\n for thetime in times:\n thetime = thetime.to_pydatetime()\n- # pyephem drops timezone when converting to its internal datetime\n- # format, so handle timezone explicitly here\n- obs.date = ephem.Date(thetime - thetime.utcoffset())\n+ # older versions of pyephem ignore timezone when converting to its\n+ # internal datetime format, so convert to UTC here to support\n+ # all versions. GH #1449\n+ obs.date = ephem.Date(thetime.astimezone(datetime.timezone.utc))\n sunrise.append(_ephem_to_timezone(rising(sun), tzinfo))\n sunset.append(_ephem_to_timezone(setting(sun), tzinfo))\n trans.append(_ephem_to_timezone(transit(sun), tzinfo))\ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -510,6 +510,9 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n \n # Calculate surface_tilt\n dotproduct = (panel_norm_earth * projected_normal).sum(axis=1)\n+ # for edge cases like axis_tilt=90, numpy's SIMD can produce values like\n+ # dotproduct = (1 + 2e-16). Clip off the excess so that arccos works:\n+ dotproduct = np.clip(dotproduct, -1, 1)\n surface_tilt = 90 - np.degrees(np.arccos(dotproduct))\n \n # Bundle DataFrame for return values and filter for sun below horizon.\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -39,7 +39,7 @@\n URL = 'https://github.com/pvlib/pvlib-python'\n \n INSTALL_REQUIRES = ['numpy >= 1.16.0',\n- 'pandas >= 0.22.0',\n+ 'pandas >= 0.25.0',\n 'pytz',\n 'requests',\n 'scipy >= 1.2.0',\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_crn.py b/pvlib/tests/iotools/test_crn.py\n--- a/pvlib/tests/iotools/test_crn.py\n+++ b/pvlib/tests/iotools/test_crn.py\n@@ -83,7 +83,7 @@ def test_read_crn_problems(testfile_problems, columns_mapped, dtypes):\n '2020-07-06 13:10:00'],\n freq=None).tz_localize('UTC')\n values = np.array([\n- [92821, 20200706, 1200, 20200706, 700, '3.0', -80.69, 28.62, 24.9,\n+ [92821, 20200706, 1200, 20200706, 700, '3', -80.69, 28.62, 24.9,\n 0.0, np.nan, 0, 25.5, 'C', 0, 93.0, 0, nan, nan, 990, 0, 1.57, 0],\n [92821, 20200706, 1310, 20200706, 810, '2.623', -80.69, 28.62,\n 26.9, 0.0, 430.0, 0, 30.2, 'C', 0, 87.0, 0, nan, nan, 989, 0,\ndiff --git a/pvlib/tests/iotools/test_psm3.py b/pvlib/tests/iotools/test_psm3.py\n--- a/pvlib/tests/iotools/test_psm3.py\n+++ b/pvlib/tests/iotools/test_psm3.py\n@@ -170,7 +170,7 @@ def test_read_psm3_map_variables():\n data, metadata = psm3.read_psm3(MANUAL_TEST_DATA, map_variables=True)\n columns_mapped = ['Year', 'Month', 'Day', 'Hour', 'Minute', 'dhi', 'dni',\n 'ghi', 'dhi_clear', 'dni_clear', 'ghi_clear',\n- 'Cloud Type', 'Dew Point', 'apparent_zenith',\n+ 'Cloud Type', 'Dew Point', 'solar_zenith',\n 'Fill Flag', 'albedo', 'wind_speed',\n 'precipitable_water', 'wind_direction',\n 'relative_humidity', 'temp_air', 'pressure']\ndiff --git a/pvlib/tests/test_conftest.py b/pvlib/tests/test_conftest.py\n--- a/pvlib/tests/test_conftest.py\n+++ b/pvlib/tests/test_conftest.py\n@@ -52,22 +52,21 @@ def test_use_fixture_with_decorator(some_data):\n 'assert_frame_equal'])\n @pytest.mark.parametrize('pd_version', ['1.0.0', '1.1.0'])\n @pytest.mark.parametrize('check_less_precise', [True, False])\n-def test__check_pandas_assert_kwargs(mocker, monkeypatch,\n- function_name, pd_version,\n+def test__check_pandas_assert_kwargs(mocker, function_name, pd_version,\n check_less_precise):\n # test that conftest._check_pandas_assert_kwargs returns appropriate\n # kwargs for the assert_x_equal functions\n \n- # patch the pandas assert; not interested in actually calling them:\n- def patched_assert(*args, **kwargs):\n- pass\n+ # NOTE: be careful about mixing mocker.patch and pytest.MonkeyPatch!\n+ # they do not coordinate their cleanups, so it is safest to only\n+ # use one or the other. GH #1447\n \n- monkeypatch.setattr(pandas.testing, function_name, patched_assert)\n- # then attach a spy to it so we can see what args it is called with:\n- mocked_function = mocker.spy(pandas.testing, function_name)\n+ # patch the pandas assert; not interested in actually calling them,\n+ # plus we want to spy on how they get called.\n+ spy = mocker.patch('pandas.testing.' + function_name)\n # patch pd.__version__ to exercise the two branches in\n # conftest._check_pandas_assert_kwargs\n- monkeypatch.setattr(pandas, '__version__', pd_version)\n+ mocker.patch('pandas.__version__', new=pd_version)\n \n # finally, run the function and check what args got passed to pandas:\n assert_function = getattr(conftest, function_name)\n@@ -79,4 +78,4 @@ def patched_assert(*args, **kwargs):\n else:\n expected_kwargs = {'check_less_precise': check_less_precise}\n \n- mocked_function.assert_called_with(*args, **expected_kwargs)\n+ spy.assert_called_once_with(*args, **expected_kwargs)\n", "problem_statement": "Output of solarposition.sun_rise_set_transit_ephem depends on installed ephem version\n**Describe the bug**\r\n`pvlib.solarposition.sun_rise_set_transit_ephem` returns a different answer depending on what version of `ephem` is installed. I think the problem is that our wrapper assumes that ephem doesn't pay attention to timezone localization, so it converts the timestamp components to UTC but doesn't bother to change the timestamp's tzinfo:\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/8d0f863da92739669e01ac4da4145e4547638b50/pvlib/solarposition.py#L577-L579\r\n\r\nHowever, starting in `ephem==4.1.1` the timezone is no longer ignored ([ref](https://rhodesmill.org/pyephem/CHANGELOG.html#version-4-1-1-2021-november-27)), so the UTC offset is applied twice. This can shift the timestamp into the next solar period and return the rise/set/transit for the wrong day. \r\n\r\n\r\n**To Reproduce**\r\nSee how the returned sunrise differs by ~24 hours (2019-01-01 vs 2019-01-02) here:\r\n\r\n```python\r\nimport pandas as pd\r\nimport pvlib\r\ntimes = pd.date_range('2019-01-01', freq='h', periods=1, tz='Etc/GMT+8')\r\nout = pvlib.solarposition.sun_rise_set_transit_ephem(times, 40, -120)\r\nprint(out.T)\r\n```\r\n\r\n#### `ephem==4.0.0.1`:\r\n```\r\n\r\n 2019-01-01 00:00:00-08:00\r\nsunrise 2019-01-01 07:21:28.793036-08:00\r\nsunset 2019-01-01 16:45:50.959086-08:00\r\ntransit 2019-01-01 12:03:35.730674-08:00\r\n```\r\n\r\n#### `ephem==4.1.2`:\r\n```\r\n 2019-01-01 00:00:00-08:00\r\nsunrise 2019-01-02 07:21:35.237404-08:00\r\nsunset 2019-01-01 16:45:50.947472-08:00\r\ntransit 2019-01-01 12:03:35.728413-08:00\r\n```\r\n\r\n**Expected behavior**\r\npvlib should give ephem timestamps consistent with its input requirements. Replacing the above manual utc offset subtraction (which leaves the original tzinfo in place) with `thetime.astimezone(pytz.UTC)` may be suitable for both old and new versions of ephem. I don't ever use pytz and python datetimes so maybe there's a better alternative.\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.9.1\r\n - python: 3.7\r\n\r\n**Additional context**\r\nThis difference would have popped up back in November when ephem 4.1.1 was released had it not been for #1447. Here's an example failure: https://dev.azure.com/solararbiter/pvlib%20python/_build/results?buildId=6027&view=logs&j=e1592cb8-2816-5754-b393-3839a187d454&t=377c4fd6-97bd-5996-bc02-4d072a8786ea&l=2267\r\n\n", "hints_text": "", "created_at": "2022-04-22T23:54:20Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_crn.py::test_read_crn_problems"], "PASS_TO_PASS": ["pvlib/tests/iotools/test_crn.py::test_read_crn", "pvlib/tests/iotools/test_crn.py::test_read_crn_map_variables", "pvlib/tests/iotools/test_psm3.py::test_parse_psm3", "pvlib/tests/iotools/test_psm3.py::test_read_psm3", "pvlib/tests/iotools/test_psm3.py::test_read_psm3_map_variables", "pvlib/tests/test_conftest.py::test_fail_on_pvlib_version_pass", "pvlib/tests/test_conftest.py::test_use_fixture_with_decorator", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[True-1.0.0-assert_index_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[True-1.0.0-assert_series_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[True-1.0.0-assert_frame_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[True-1.1.0-assert_index_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[True-1.1.0-assert_series_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[True-1.1.0-assert_frame_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[False-1.0.0-assert_index_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[False-1.0.0-assert_series_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[False-1.0.0-assert_frame_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[False-1.1.0-assert_index_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[False-1.1.0-assert_series_equal]", "pvlib/tests/test_conftest.py::test__check_pandas_assert_kwargs[False-1.1.0-assert_frame_equal]"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1589", "base_commit": "bd86597f62013f576670a452869ea88a47c58c01", "patch": "diff --git a/pvlib/bifacial/infinite_sheds.py b/pvlib/bifacial/infinite_sheds.py\n--- a/pvlib/bifacial/infinite_sheds.py\n+++ b/pvlib/bifacial/infinite_sheds.py\n@@ -216,8 +216,8 @@ def _ground_angle(x, surface_tilt, gcr):\n # : \\ v *-.\\\n # : \\<-----P---->\\\n \n- x1 = x * sind(surface_tilt)\n- x2 = (x * cosd(surface_tilt) + 1 / gcr)\n+ x1 = gcr * x * sind(surface_tilt)\n+ x2 = gcr * x * cosd(surface_tilt) + 1\n psi = np.arctan2(x1, x2) # do this first because it handles 0 / 0\n return np.rad2deg(psi)\n \ndiff --git a/pvlib/shading.py b/pvlib/shading.py\n--- a/pvlib/shading.py\n+++ b/pvlib/shading.py\n@@ -52,8 +52,8 @@ def masking_angle(surface_tilt, gcr, slant_height):\n # The original equation (8 in [1]) requires pitch and collector width,\n # but it's easy to non-dimensionalize it to make it a function of GCR\n # by factoring out B from the argument to arctan.\n- numerator = (1 - slant_height) * sind(surface_tilt)\n- denominator = 1/gcr - (1 - slant_height) * cosd(surface_tilt)\n+ numerator = gcr * (1 - slant_height) * sind(surface_tilt)\n+ denominator = 1 - gcr * (1 - slant_height) * cosd(surface_tilt)\n phi = np.arctan(numerator / denominator)\n return np.degrees(phi)\n \n", "test_patch": "diff --git a/pvlib/tests/bifacial/test_infinite_sheds.py b/pvlib/tests/bifacial/test_infinite_sheds.py\n--- a/pvlib/tests/bifacial/test_infinite_sheds.py\n+++ b/pvlib/tests/bifacial/test_infinite_sheds.py\n@@ -106,6 +106,14 @@ def test__ground_angle(test_system):\n assert np.allclose(angles, expected_angles)\n \n \n+def test__ground_angle_zero_gcr():\n+ surface_tilt = 30.0\n+ x = np.array([0.0, 0.5, 1.0])\n+ angles = infinite_sheds._ground_angle(x, surface_tilt, 0)\n+ expected_angles = np.array([0, 0, 0])\n+ assert np.allclose(angles, expected_angles)\n+\n+\n def test__vf_row_ground(test_system):\n ts, _, _ = test_system\n x = np.array([0., 0.5, 1.0])\ndiff --git a/pvlib/tests/test_shading.py b/pvlib/tests/test_shading.py\n--- a/pvlib/tests/test_shading.py\n+++ b/pvlib/tests/test_shading.py\n@@ -45,6 +45,13 @@ def test_masking_angle_scalar(surface_tilt, masking_angle):\n assert np.isclose(masking_angle_actual, angle)\n \n \n+def test_masking_angle_zero_gcr(surface_tilt):\n+ # scalar inputs and outputs, including zero\n+ for tilt in surface_tilt:\n+ masking_angle_actual = shading.masking_angle(tilt, 0, 0.25)\n+ assert np.isclose(masking_angle_actual, 0)\n+\n+\n def test_masking_angle_passias_series(surface_tilt, average_masking_angle):\n # pandas series inputs and outputs\n masking_angle_actual = shading.masking_angle_passias(surface_tilt, 0.5)\n", "problem_statement": "ZeroDivisionError when gcr is zero\n**Describe the bug**\r\n\r\nThough maybe not intuitive, setting ground coverage ratio to zero is useful when a plant consists of a single shed, e.g. calculating the irradiance on the backside of the panels. However, e.g., `bifacial.infinite_sheds.get_irradiance_poa` fails with `ZeroDivisionError` whenever `gcr=0`.\r\n\r\n**To Reproduce**\r\n\r\n```python\r\nfrom pvlib.bifacial.infinite_sheds import get_irradiance_poa\r\n\r\nget_irradiance_poa(surface_tilt=160, surface_azimuth=180, solar_zenith=20, solar_azimuth=180, gcr=0, height=1, pitch=1000, ghi=200, dhi=200, dni=0, albedo=0.2)\r\n```\r\nreturns:\r\n```\r\nTraceback (most recent call last):\r\n File \"C:\\Python\\Python310\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3398, in run_code\r\n exec(code_obj, self.user_global_ns, self.user_ns)\r\n File \"<ipython-input-7-0cb583b2b311>\", line 3, in <cell line: 3>\r\n get_irradiance_poa(surface_tilt=160, surface_azimuth=180, solar_zenith=20, solar_azimuth=180, gcr=0, height=1, pitch=1, ghi=200, dhi=200, dni=0, albedo=0.2)\r\n File \"C:\\Python\\Python310\\lib\\site-packages\\pvlib\\bifacial\\infinite_sheds.py\", line 522, in get_irradiance_poa\r\n vf_shade_sky, vf_noshade_sky = _vf_row_sky_integ(\r\n File \"C:\\Python\\Python310\\lib\\site-packages\\pvlib\\bifacial\\infinite_sheds.py\", line 145, in _vf_row_sky_integ\r\n psi_t_shaded = masking_angle(surface_tilt, gcr, x)\r\n File \"C:\\Python\\Python310\\lib\\site-packages\\pvlib\\shading.py\", line 56, in masking_angle\r\n denominator = 1/gcr - (1 - slant_height) * cosd(surface_tilt)\r\nZeroDivisionError: division by zero\r\n```\r\n\r\n**Expected behavior**\r\n\r\nOne can easily solve this `ZeroDivisionError` by multiplying both numerator and denominator with `gcr` inside `shading.masking_angle` and the same inside `bifacial.infinite_sheds._ground_angle`.\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: '0.9.3'\r\n - ``pandas.__version__``: '1.4.4'\r\n - python: '3.10.4'\r\n\n", "hints_text": "@kdebrab thanks for investigating this case, which wasn't consider in the implementation. @pvlib/pvlib-core I think we should fix this. \r\n\r\nFor consistency we should also extend `shading.masking_angle_passias` for the limiting case of `gcr=0`. That may be more complicated and could be done in a second PR.\r\n\nI think `infinite_sheds.get_irradiance_poa(...)` converges to `irradiance.get_total_irradiance(..., model='isotropic')` as gcr approaches zero, so that's an option for modeling this situation in the meantime. \nProbably close enough to be useful, but in theory the rear irradiance would be slightly less than GHI * 1/2 (1 - cos(tilt)), due to the row's shadow.\nWith a more realistic model (e.g. pvfactors) that considers shadows individually that's true, but `infinite_sheds` models ground-reflected irradiance using integrated averages which dilute the effect of the row's own shadow to nothing as gcr approaches zero. By decreasing `gcr` and increasing `npoints` you can get `infinite_sheds` as close to `get_total_irradiance` as you like:\r\n\r\n\r\n\r\n<details>\r\n <summary>Source</summary>\r\n\r\n```python\r\nimport pvlib\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ntimes = pd.date_range('2019-06-01', '2019-06-02', freq='T', tz='Etc/GMT+5')\r\nlocation = pvlib.location.Location(40, -80)\r\nsp = location.get_solarposition(times)\r\ncs = location.get_clearsky(times, solar_position=sp)\r\n\r\nkwargs = dict(\r\n surface_tilt=20, surface_azimuth=180,\r\n solar_zenith=sp.apparent_zenith, solar_azimuth=sp.azimuth,\r\n ghi=cs.ghi, dhi=cs.dhi, dni=cs.dni, albedo=0.2\r\n)\r\n\r\nlimit = pvlib.irradiance.get_total_irradiance(**kwargs, model='isotropic')['poa_global']\r\n\r\nall_stats = []\r\n\r\nfor gcr in [0.3, 0.1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7]:\r\n stats = dict(gcr=gcr)\r\n for npoints in [100, 1000, 10000]:\r\n out = pvlib.bifacial.infinite_sheds.get_irradiance_poa(gcr=gcr, height=1, pitch=1/gcr, npoints=npoints, **kwargs)\r\n stats[f'npoints={npoints}'] = np.max(np.abs(out['poa_global'] - limit))\r\n\r\n all_stats.append(stats)\r\n\r\npd.DataFrame(all_stats).set_index('gcr').plot(logx=True, logy=True)\r\nplt.ylabel('Max Absolute Difference [W/m2]')\r\n\r\n```\r\n</details>\n@kanderso-nrel Thanks for pointing this out!\r\n\r\nI think for a `surface_tilt` equal to 20\u00b0 (front side of the panel) this result would be fine, as there is no shadow on the front surface from the own row. However, changing `surface_tilt` to 160\u00b0 (back side of the panel) yields basically the same figure and that is indeed not ideal (and unexpected for me).\r\n\r\nIf I understand well, this is due to the calculation of the ground-reflected irradiance, where the infinite_sheds method uses (1) the **average** 'view factor from the ground to the sky' of the ground between the rows, and (2) the **average** 'fraction of ground between rows that is unshaded', both of which approach 1 as the pitch approaches infinity.\r\n\r\nI think an improved method would not take the average, but some kind of weighted average, considering that the reflection from the ground right in front of the surface is more important than the reflection from the ground further away from the surface. In that case, I would assume that the effect of the row's own shadow would no longer dilute when gcr approaches zero.\n> However, changing surface_tilt to 160\u00b0 (back side of the panel) yields basically the same figure and that is indeed not ideal (and unexpected for me).\r\n\r\nOops, I think I had originally started with rear-side, switched to front-side just to check it as well, and forgot to switch back to rear before posting here. Good catch.\r\n\r\nFYI pvfactors (`pvlib.bifacial.pvfactors.pvfactors_timeseries`) can model irradiance for single rows (`n_pvrows=1, index_observed_pvrow=0`) and does not suffer from the averaging issues you mention. ", "created_at": "2022-11-11T14:19:29Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/bifacial/test_infinite_sheds.py::test__ground_angle_zero_gcr", "pvlib/tests/test_shading.py::test_masking_angle_zero_gcr"], "PASS_TO_PASS": ["pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_ground_sky_integ", "pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_row_sky_integ", "pvlib/tests/bifacial/test_infinite_sheds.py::test__poa_sky_diffuse_pv", "pvlib/tests/bifacial/test_infinite_sheds.py::test__ground_angle", "pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_row_ground", "pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_row_ground_integ", "pvlib/tests/bifacial/test_infinite_sheds.py::test__poa_ground_shadows", "pvlib/tests/bifacial/test_infinite_sheds.py::test__shaded_fraction_floats", "pvlib/tests/bifacial/test_infinite_sheds.py::test__shaded_fraction_array", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_poa", "pvlib/tests/bifacial/test_infinite_sheds.py::test__backside_tilt", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_limiting_gcr", "pvlib/tests/test_shading.py::test_masking_angle_series", "pvlib/tests/test_shading.py::test_masking_angle_scalar", "pvlib/tests/test_shading.py::test_masking_angle_passias_series", "pvlib/tests/test_shading.py::test_masking_angle_passias_scalar", "pvlib/tests/test_shading.py::test_sky_diffuse_passias_series", "pvlib/tests/test_shading.py::test_sky_diffuse_passias_scalar"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1031", "base_commit": "27872b83b0932cc419116f79e442963cced935bb", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -238,8 +238,9 @@ def __init__(self,\n \n def __repr__(self):\n attrs = ['name', 'surface_tilt', 'surface_azimuth', 'module',\n- 'inverter', 'albedo', 'racking_model']\n- return ('PVSystem: \\n ' + '\\n '.join(\n+ 'inverter', 'albedo', 'racking_model', 'module_type',\n+ 'temperature_model_parameters']\n+ return ('PVSystem:\\n ' + '\\n '.join(\n ('{}: {}'.format(attr, getattr(self, attr)) for attr in attrs)))\n \n def get_aoi(self, solar_zenith, solar_azimuth):\n@@ -898,8 +899,9 @@ def __init__(self, pvsystem=None, location=None, **kwargs):\n def __repr__(self):\n attrs = ['name', 'latitude', 'longitude', 'altitude', 'tz',\n 'surface_tilt', 'surface_azimuth', 'module', 'inverter',\n- 'albedo', 'racking_model']\n- return ('LocalizedPVSystem: \\n ' + '\\n '.join(\n+ 'albedo', 'racking_model', 'module_type',\n+ 'temperature_model_parameters']\n+ return ('LocalizedPVSystem:\\n ' + '\\n '.join(\n ('{}: {}'.format(attr, getattr(self, attr)) for attr in attrs)))\n \n \ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -61,7 +61,7 @@ def __init__(self, axis_tilt=0, axis_azimuth=0,\n \n def __repr__(self):\n attrs = ['axis_tilt', 'axis_azimuth', 'max_angle', 'backtrack', 'gcr']\n- sat_repr = ('SingleAxisTracker: \\n ' + '\\n '.join(\n+ sat_repr = ('SingleAxisTracker:\\n ' + '\\n '.join(\n ('{}: {}'.format(attr, getattr(self, attr)) for attr in attrs)))\n # get the parent PVSystem info\n pvsystem_repr = super(SingleAxisTracker, self).__repr__()\n", "test_patch": "diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -1119,23 +1119,43 @@ def test_PVSystem_localize_with_latlon():\n \n \n def test_PVSystem___repr__():\n- system = pvsystem.PVSystem(module='blah', inverter='blarg', name='pv ftw')\n-\n- expected = ('PVSystem: \\n name: pv ftw\\n surface_tilt: 0\\n '\n- 'surface_azimuth: 180\\n module: blah\\n inverter: blarg\\n '\n- 'albedo: 0.25\\n racking_model: open_rack')\n-\n+ system = pvsystem.PVSystem(\n+ module='blah', inverter='blarg', name='pv ftw',\n+ temperature_model_parameters={'a': -3.56})\n+\n+ expected = \"\"\"PVSystem:\n+ name: pv ftw\n+ surface_tilt: 0\n+ surface_azimuth: 180\n+ module: blah\n+ inverter: blarg\n+ albedo: 0.25\n+ racking_model: open_rack\n+ module_type: glass_polymer\n+ temperature_model_parameters: {'a': -3.56}\"\"\"\n assert system.__repr__() == expected\n \n \n def test_PVSystem_localize___repr__():\n- system = pvsystem.PVSystem(module='blah', inverter='blarg', name='pv ftw')\n+ system = pvsystem.PVSystem(\n+ module='blah', inverter='blarg', name='pv ftw',\n+ temperature_model_parameters={'a': -3.56})\n localized_system = system.localize(latitude=32, longitude=-111)\n-\n- expected = ('LocalizedPVSystem: \\n name: None\\n latitude: 32\\n '\n- 'longitude: -111\\n altitude: 0\\n tz: UTC\\n '\n- 'surface_tilt: 0\\n surface_azimuth: 180\\n module: blah\\n '\n- 'inverter: blarg\\n albedo: 0.25\\n racking_model: open_rack')\n+ # apparently name is not preserved when creating a system using localize\n+ expected = \"\"\"LocalizedPVSystem:\n+ name: None\n+ latitude: 32\n+ longitude: -111\n+ altitude: 0\n+ tz: UTC\n+ surface_tilt: 0\n+ surface_azimuth: 180\n+ module: blah\n+ inverter: blarg\n+ albedo: 0.25\n+ racking_model: open_rack\n+ module_type: glass_polymer\n+ temperature_model_parameters: {'a': -3.56}\"\"\"\n \n assert localized_system.__repr__() == expected\n \n@@ -1158,16 +1178,24 @@ def test_LocalizedPVSystem_creation():\n \n \n def test_LocalizedPVSystem___repr__():\n- localized_system = pvsystem.LocalizedPVSystem(latitude=32,\n- longitude=-111,\n- module='blah',\n- inverter='blarg',\n- name='my name')\n-\n- expected = ('LocalizedPVSystem: \\n name: my name\\n latitude: 32\\n '\n- 'longitude: -111\\n altitude: 0\\n tz: UTC\\n '\n- 'surface_tilt: 0\\n surface_azimuth: 180\\n module: blah\\n '\n- 'inverter: blarg\\n albedo: 0.25\\n racking_model: open_rack')\n+ localized_system = pvsystem.LocalizedPVSystem(\n+ latitude=32, longitude=-111, module='blah', inverter='blarg',\n+ name='my name', temperature_model_parameters={'a': -3.56})\n+\n+ expected = \"\"\"LocalizedPVSystem:\n+ name: my name\n+ latitude: 32\n+ longitude: -111\n+ altitude: 0\n+ tz: UTC\n+ surface_tilt: 0\n+ surface_azimuth: 180\n+ module: blah\n+ inverter: blarg\n+ albedo: 0.25\n+ racking_model: open_rack\n+ module_type: glass_polymer\n+ temperature_model_parameters: {'a': -3.56}\"\"\"\n \n assert localized_system.__repr__() == expected\n \ndiff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -438,28 +438,51 @@ def test_get_irradiance():\n \n \n def test_SingleAxisTracker___repr__():\n- system = tracking.SingleAxisTracker(max_angle=45, gcr=.25,\n- module='blah', inverter='blarg')\n- expected = ('SingleAxisTracker: \\n axis_tilt: 0\\n axis_azimuth: 0\\n '\n- 'max_angle: 45\\n backtrack: True\\n gcr: 0.25\\n '\n- 'name: None\\n surface_tilt: None\\n surface_azimuth: None\\n '\n- 'module: blah\\n inverter: blarg\\n albedo: 0.25\\n '\n- 'racking_model: open_rack')\n+ system = tracking.SingleAxisTracker(\n+ max_angle=45, gcr=.25, module='blah', inverter='blarg',\n+ temperature_model_parameters={'a': -3.56})\n+ expected = \"\"\"SingleAxisTracker:\n+ axis_tilt: 0\n+ axis_azimuth: 0\n+ max_angle: 45\n+ backtrack: True\n+ gcr: 0.25\n+ name: None\n+ surface_tilt: None\n+ surface_azimuth: None\n+ module: blah\n+ inverter: blarg\n+ albedo: 0.25\n+ racking_model: open_rack\n+ module_type: glass_polymer\n+ temperature_model_parameters: {'a': -3.56}\"\"\"\n assert system.__repr__() == expected\n \n \n def test_LocalizedSingleAxisTracker___repr__():\n- localized_system = tracking.LocalizedSingleAxisTracker(latitude=32,\n- longitude=-111,\n- module='blah',\n- inverter='blarg',\n- gcr=0.25)\n-\n- expected = ('LocalizedSingleAxisTracker: \\n axis_tilt: 0\\n '\n- 'axis_azimuth: 0\\n max_angle: 90\\n backtrack: True\\n '\n- 'gcr: 0.25\\n name: None\\n surface_tilt: None\\n '\n- 'surface_azimuth: None\\n module: blah\\n inverter: blarg\\n '\n- 'albedo: 0.25\\n racking_model: open_rack\\n '\n- 'latitude: 32\\n longitude: -111\\n altitude: 0\\n tz: UTC')\n+ localized_system = tracking.LocalizedSingleAxisTracker(\n+ latitude=32, longitude=-111, module='blah', inverter='blarg',\n+ gcr=0.25, temperature_model_parameters={'a': -3.56})\n+ # apparently the repr order is different for LocalizedSingleAxisTracker\n+ # than for LocalizedPVSystem. maybe a MRO thing.\n+ expected = \"\"\"LocalizedSingleAxisTracker:\n+ axis_tilt: 0\n+ axis_azimuth: 0\n+ max_angle: 90\n+ backtrack: True\n+ gcr: 0.25\n+ name: None\n+ surface_tilt: None\n+ surface_azimuth: None\n+ module: blah\n+ inverter: blarg\n+ albedo: 0.25\n+ racking_model: open_rack\n+ module_type: glass_polymer\n+ temperature_model_parameters: {'a': -3.56}\n+ latitude: 32\n+ longitude: -111\n+ altitude: 0\n+ tz: UTC\"\"\"\n \n assert localized_system.__repr__() == expected\n", "problem_statement": "expand PVSystem repr\nThe PVSystem repr is\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/27872b83b0932cc419116f79e442963cced935bb/pvlib/pvsystem.py#L239-L243\r\n\r\nThe main issue that I have is that the repr doesn't give me enough information about the temperature model settings. It's relatively important because `temperature_model_params` (not printed) may be inferred from `module_type` (not printed) and `racking_model` (printed). So I'd like to add both `temperature_model_params` and `module_type`.\r\n\r\nWe also don't include `module_parameters`, `inverter_parameters`, and `losses_parameters` in the repr. If I recall correctly, we decided against including these because they can be relatively long. I still think that's reasonable. We could add something like `if len(module_parameters): 'Set. See PVSystem.module_parameters'; else: {}`, but I don't know if that's worth the effort.\n", "hints_text": "", "created_at": "2020-08-25T03:29:48Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize___repr__", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem___repr__", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_LocalizedSingleAxisTracker___repr__"], "PASS_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_pvsystem_sapm_warning", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test__infer_temperature_model_params_deprec_warning", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_location", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_latlon", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem_creation", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_deprecated_08", "pvlib/tests/test_pvsystem.py::test__pvsyst_celltemp_translator", "pvlib/tests/test_pvsystem.py::test__sapm_celltemp_translator", "pvlib/tests/test_pvsystem.py::test_deprecated_09", "pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_creation", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_LocalizedSingleAxisTracker_creation", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_localize", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_localize_location", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_get_irradiance"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1349", "base_commit": "aba071f707f9025882e57f3e55cc9e3e90e869b2", "patch": "diff --git a/pvlib/spectrum/spectrl2.py b/pvlib/spectrum/spectrl2.py\n--- a/pvlib/spectrum/spectrl2.py\n+++ b/pvlib/spectrum/spectrl2.py\n@@ -260,6 +260,11 @@ def spectrl2(apparent_zenith, aoi, surface_tilt, ground_albedo,\n 2-5 kasten1966 kasten1966 kastenyoung1989\n =================== ========== ========== ===============\n \n+ This implementation also deviates from the reference by including a\n+ check for angles of incidence greater than 90 degrees; without this,\n+ the model might return negative spectral irradiance values when the\n+ sun is behind the plane of array.\n+\n References\n ----------\n .. [1] Bird, R, and Riordan, C., 1984, \"Simple solar spectral model for\n@@ -357,10 +362,16 @@ def spectrl2(apparent_zenith, aoi, surface_tilt, ground_albedo,\n Is = (Ir + Ia + Ig) * Cs # Eq 3-1\n \n # calculate spectral irradiance on a tilted surface, Eq 3-18\n- Ibeam = Id * cosd(aoi)\n-\n- # don't need surface_azimuth if we provide projection_ratio\n- projection_ratio = cosd(aoi) / cosZ\n+ # Note: clipping cosd(aoi) to >=0 is not in the reference, but is necessary\n+ # to prevent nonsense values when the sun is behind the plane of array.\n+ # The same constraint is applied in irradiance.haydavies when not\n+ # supplying `projection_ratio`.\n+ aoi_projection_nn = np.maximum(cosd(aoi), 0) # GH 1348\n+ Ibeam = Id * aoi_projection_nn\n+\n+ # don't need surface_azimuth if we provide projection_ratio.\n+ # Also constrain cos zenith to avoid blowup, as in irradiance.haydavies\n+ projection_ratio = aoi_projection_nn / np.maximum(cosZ, 0.01745)\n Isky = pvlib.irradiance.haydavies(surface_tilt=surface_tilt,\n surface_azimuth=None,\n dhi=Is,\n", "test_patch": "diff --git a/pvlib/tests/test_spectrum.py b/pvlib/tests/test_spectrum.py\n--- a/pvlib/tests/test_spectrum.py\n+++ b/pvlib/tests/test_spectrum.py\n@@ -92,3 +92,17 @@ def test_dayofyear_missing(spectrl2_data):\n kwargs.pop('dayofyear')\n with pytest.raises(ValueError, match='dayofyear must be specified'):\n _ = spectrum.spectrl2(**kwargs)\n+\n+\n+def test_aoi_gt_90(spectrl2_data):\n+ # test that returned irradiance values are non-negative when aoi > 90\n+ # see GH #1348\n+ kwargs, _ = spectrl2_data\n+ kwargs['apparent_zenith'] = 70\n+ kwargs['aoi'] = 130\n+ kwargs['surface_tilt'] = 60\n+\n+ spectra = spectrum.spectrl2(**kwargs)\n+ for key in ['poa_direct', 'poa_global']:\n+ message = f'{key} contains negative values for aoi>90'\n+ assert np.all(spectra[key] >= 0), message\n", "problem_statement": "`spectrum.spectrl2` calculates negative irradiance for angle of incidence outside +/- 90\u00b0\nWhen using pvlib (but also the spectrl2 implementation provided by NREL), I obtain negative Irradiance for a north-facing panel.\r\nFrom @kevinsa5 's [reply on StackOverflow](https://stackoverflow.com/questions/70172766/pvlib-bird1984-north-facing-element-shows-negative-irradiance/70174010#70174010) I take that this is in fact not intended.\r\n\r\nIn the example code below, the angle of incidence is calculated as values around 115\u00b0, so exceeding a possible (implicitly assumed) +/- 90\u00b0 bound (sun behind panel).\r\n\r\nThis seems to be left open in the original report ([Bird & Riordan, 1984](https://www.nrel.gov/docs/legosti/old/2436.pdf)).\r\n\r\nThe direct irradiance `I_d` (*of a horizontal panel*, Eq 2-1) is obtained by multiplying by cosine of the sun zenith angle. I'd guess that setting that value strictly to zero for angles when cosZ is negative would not be too much of a stretch.\r\n\r\nThen, the direct irradiance `I_d` goes into (Eq 3-18):\r\n\r\n```\r\nI_T(t) = I_d*cos(aoi) + I_s * ( (I_d*cos(aoi) / (H_0*D*cos(Z)) ) + 0.5*(1+cos(t)) * (1 - I_d/(H_0*D)) + 0.5 * I_T0 * r_g * (1-cos(t))\r\n```\r\n\r\nAs such, when you view the angle of incidence `aoi` as the analogue of the sun zenith angle in the prior example, the two first terms of the diffuse irradiation (Eq 3-18) would become zero, which - again - for the direct irradiance would kind of make sense. What remains of (Eq 3-18) would be\r\n\r\n```\r\nI_T(t) = 0 + 0 + 0.5*(1+cos(t))*(1 - 0) + 0.5*I_T0*r_g*(1-cos(t))\r\n```\r\n\r\nI'm not from the field, so I'm very, very wary about the implications of such a work-around suggestion. Can anyone with a proper background comment on this? (Maybe it's the future of air conditioning :-D)\r\n\r\n\r\n**MWE based on the tutorial below**\r\n\r\n```python\r\n## Using PV Lib\r\n\r\nfrom pvlib import spectrum, solarposition, irradiance, atmosphere\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n# assumptions from the technical report:\r\nlat = 49.88\r\nlon = 8.63\r\ntilt = 45\r\nazimuth = 0 # North = 0\r\npressure = 101300 # sea level, roughly\r\nwater_vapor_content = 0.5 # cm\r\ntau500 = 0.1\r\nozone = 0.31 # atm-cm\r\nalbedo = 0.2\r\n\r\ntimes = pd.date_range('2021-11-30 8:00', freq='h', periods=6, tz=\"Europe/Berlin\") # , tz='Etc/GMT+9'\r\nsolpos = solarposition.get_solarposition(times, lat, lon)\r\naoi = irradiance.aoi(tilt, azimuth, solpos.apparent_zenith, solpos.azimuth)\r\n\r\n# The technical report uses the 'kasten1966' airmass model, but later\r\n# versions of SPECTRL2 use 'kastenyoung1989'. Here we use 'kasten1966'\r\n# for consistency with the technical report.\r\nrelative_airmass = atmosphere.get_relative_airmass(solpos.apparent_zenith,\r\n model='kasten1966')\r\n\r\nspectra = spectrum.spectrl2(\r\n apparent_zenith=solpos.apparent_zenith,\r\n aoi=aoi,\r\n surface_tilt=tilt,\r\n ground_albedo=albedo,\r\n surface_pressure=pressure,\r\n relative_airmass=relative_airmass,\r\n precipitable_water=water_vapor_content,\r\n ozone=ozone,\r\n aerosol_turbidity_500nm=tau500,\r\n)\r\n\r\nplt.figure()\r\nplt.plot(spectra['wavelength'], spectra['poa_global'])\r\nplt.xlim(200, 2700)\r\n# plt.ylim(0, 1.8)\r\nplt.title(r\"2021-11-30, Darmstadt, $\\tau=0.1$, Wv=0.5 cm\")\r\nplt.ylabel(r\"Irradiance ($W m^{-2} nm^{-1}$)\")\r\nplt.xlabel(r\"Wavelength ($nm$)\")\r\ntime_labels = times.strftime(\"%H:%M %p\")\r\nlabels = [\r\n \"AM {:0.02f}, Z{:0.02f}, {}\".format(*vals)\r\n for vals in zip(relative_airmass, solpos.apparent_zenith, time_labels)\r\n]\r\nplt.legend(labels)\r\nplt.show()\r\n```\r\n\r\n\r\n\r\n\n", "hints_text": "Thanks @cweickhmann! I want to take a closer look at the technical report to be sure, but on a first glance I think the problem here is the same one solved by the line marked with `# GH 526` in `irradiance.haydavies`:\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/aba071f707f9025882e57f3e55cc9e3e90e869b2/pvlib/irradiance.py#L811-L816\r\n\r\nNote that, even though `spectrum.spectrl2` uses `irradiance.haydavies` under the hood, the above branch is not hit because `spectrl2` passes in a pre-calculated `projection_ratio`. So I think clipping the projection to be non-negative before passing it to `haydavies` would solve the problem. The `# GH 432` line might be desirable as well, though I don't think it's relevant for this issue. \r\n\r\nDoes anyone have qualms about us deviating from the reference by implementing that fix and making a note about it in the docstring? `aoi > 90` is hardly an uncommon occurrence, even for arrays that aren't high-latitude and facing north. \n> deviating from the reference by implementing that fix and making a note about it \r\n\r\nI support that.", "created_at": "2021-12-04T20:54:05Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_spectrum.py::test_aoi_gt_90"], "PASS_TO_PASS": ["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"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-980", "base_commit": "75369dcabacb6c6c38790cc23825f33f155ad1a9", "patch": "diff --git a/pvlib/soiling.py b/pvlib/soiling.py\n--- a/pvlib/soiling.py\n+++ b/pvlib/soiling.py\n@@ -12,8 +12,8 @@\n def hsu(rainfall, cleaning_threshold, tilt, pm2_5, pm10,\n depo_veloc=None, rain_accum_period=pd.Timedelta('1h')):\n \"\"\"\n- Calculates soiling ratio given particulate and rain data using the model\n- from Humboldt State University (HSU).\n+ Calculates soiling ratio given particulate and rain data using the\n+ Fixed Velocity model from Humboldt State University (HSU).\n \n The HSU soiling model [1]_ returns the soiling ratio, a value between zero\n and one which is equivalent to (1 - transmission loss). Therefore a soiling\n@@ -76,8 +76,17 @@ def hsu(rainfall, cleaning_threshold, tilt, pm2_5, pm10,\n # cleaning is True for intervals with rainfall greater than threshold\n cleaning_times = accum_rain.index[accum_rain >= cleaning_threshold]\n \n- horiz_mass_rate = pm2_5 * depo_veloc['2_5']\\\n- + np.maximum(pm10 - pm2_5, 0.) * depo_veloc['10'] * 3600\n+ # determine the time intervals in seconds (dt_sec)\n+ dt = rainfall.index\n+ # subtract shifted values from original and convert to seconds\n+ dt_diff = (dt[1:] - dt[:-1]).total_seconds()\n+ # ensure same number of elements in the array, assuming that the interval\n+ # prior to the first value is equal in length to the first interval\n+ dt_sec = np.append(dt_diff[0], dt_diff).astype('float64')\n+\n+ horiz_mass_rate = (\n+ pm2_5 * depo_veloc['2_5'] + np.maximum(pm10 - pm2_5, 0.)\n+ * depo_veloc['10']) * dt_sec\n tilted_mass_rate = horiz_mass_rate * cosd(tilt) # assuming no rain\n \n # tms -> tilt_mass_rate\n", "test_patch": "diff --git a/pvlib/tests/test_soiling.py b/pvlib/tests/test_soiling.py\n--- a/pvlib/tests/test_soiling.py\n+++ b/pvlib/tests/test_soiling.py\n@@ -18,24 +18,24 @@ def expected_output():\n end=pd.Timestamp(2019, 1, 1, 23, 59, 0), freq='1h')\n \n expected_no_cleaning = pd.Series(\n- data=[0.97230454, 0.95036146, 0.93039061, 0.91177978, 0.89427556,\n- 0.8777455 , 0.86211038, 0.84731759, 0.83332881, 0.82011354,\n- 0.80764549, 0.79590056, 0.78485556, 0.77448749, 0.76477312,\n- 0.75568883, 0.74721046, 0.73931338, 0.73197253, 0.72516253,\n- 0.7188578 , 0.71303268, 0.7076616 , 0.70271919],\n+ data=[0.96998483, 0.94623958, 0.92468139, 0.90465654, 0.88589707,\n+ 0.86826366, 0.85167258, 0.83606715, 0.82140458, 0.80764919,\n+ 0.79476875, 0.78273241, 0.77150951, 0.76106905, 0.75137932,\n+ 0.74240789, 0.73412165, 0.72648695, 0.71946981, 0.7130361,\n+ 0.70715176, 0.70178307, 0.69689677, 0.69246034],\n index=dt)\n return expected_no_cleaning\n \n @pytest.fixture\n def expected_output_1():\n dt = pd.date_range(start=pd.Timestamp(2019, 1, 1, 0, 0, 0),\n- end=pd.Timestamp(2019, 1, 1, 23, 59, 0), freq='1h')\n+ end=pd.Timestamp(2019, 1, 1, 23, 59, 0), freq='1h')\n expected_output_1 = pd.Series(\n- data=[0.9872406 , 0.97706269, 0.96769693, 0.95884032, 1.,\n- 0.9872406 , 0.97706269, 0.96769693, 1. , 1. ,\n- 0.9872406 , 0.97706269, 0.96769693, 0.95884032, 0.95036001,\n- 0.94218263, 0.93426236, 0.92656836, 0.91907873, 0.91177728,\n- 0.9046517 , 0.89769238, 0.89089165, 0.88424329],\n+ data=[0.98484972, 0.97277367, 0.96167471, 0.95119603, 1.,\n+ 0.98484972, 0.97277367, 0.96167471, 1., 1.,\n+ 0.98484972, 0.97277367, 0.96167471, 0.95119603, 0.94118234,\n+ 0.93154854, 0.922242, 0.91322759, 0.90448058, 0.89598283,\n+ 0.88772062, 0.87968325, 0.8718622, 0.86425049],\n index=dt)\n return expected_output_1\n \n@@ -44,15 +44,31 @@ def expected_output_2():\n dt = pd.date_range(start=pd.Timestamp(2019, 1, 1, 0, 0, 0),\n end=pd.Timestamp(2019, 1, 1, 23, 59, 0), freq='1h')\n expected_output_2 = pd.Series(\n- data=[0.97229869, 0.95035106, 0.93037619, 0.91176175, 1.,\n- 1. , 1. , 0.97229869, 1. , 1. ,\n- 1. , 1. , 0.97229869, 0.95035106, 0.93037619,\n- 0.91176175, 0.89425431, 1. , 1. , 1. ,\n- 1. , 0.97229869, 0.95035106, 0.93037619],\n+ data=[0.95036261, 0.91178179, 0.87774818, 0.84732079, 1.,\n+ 1., 1., 0.95036261, 1., 1.,\n+ 1., 1., 0.95036261, 0.91178179, 0.87774818,\n+ 0.84732079, 0.8201171, 1., 1., 1.,\n+ 1., 0.95036261, 0.91178179, 0.87774818],\n index=dt)\n-\n return expected_output_2\n \n+\[email protected]\n+def expected_output_3():\n+ dt = pd.date_range(start=pd.Timestamp(2019, 1, 1, 0, 0, 0),\n+ end=pd.Timestamp(2019, 1, 1, 23, 59, 0), freq='1h')\n+ timedelta = [0, 0, 0, 0, 0, 30, 0, 30, 0, 30, 0, -30,\n+ -30, -30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n+ dt_new = dt + pd.to_timedelta(timedelta, 'm')\n+ expected_output_3 = pd.Series(\n+ data=[0.96576705, 0.9387675, 0.91437615, 0.89186852, 1.,\n+ 1., 0.98093819, 0.9387675, 1., 1.,\n+ 1., 1., 0.96576705, 0.9387675, 0.90291005,\n+ 0.88122293, 0.86104089, 1., 1., 1.,\n+ 0.96576705, 0.9387675, 0.91437615, 0.89186852],\n+ index=dt_new)\n+ return expected_output_3\n+\n @pytest.fixture\n def rainfall_input():\n \n@@ -105,12 +121,30 @@ def test_hsu_defaults(rainfall_input, expected_output_1):\n Test Soiling HSU function with default deposition velocity and default rain\n accumulation period.\n \"\"\"\n- result = hsu(\n- rainfall=rainfall_input, cleaning_threshold=0.5, tilt=0.0,\n- pm2_5=1.0e-2,pm10=2.0e-2)\n+ result = hsu(rainfall=rainfall_input, cleaning_threshold=0.5, tilt=0.0,\n+ pm2_5=1.0e-2, pm10=2.0e-2)\n assert np.allclose(result.values, expected_output_1)\n \n \n+@requires_scipy\n+def test_hsu_variable_time_intervals(rainfall_input, expected_output_3):\n+ \"\"\"\n+ Test Soiling HSU function with variable time intervals.\n+ \"\"\"\n+ depo_veloc = {'2_5': 1.0e-4, '10': 1.0e-4}\n+ rain = pd.DataFrame(data=rainfall_input)\n+ # define time deltas in minutes\n+ timedelta = [0, 0, 0, 0, 0, 30, 0, 30, 0, 30, 0, -30,\n+ -30, -30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n+ rain['mins_added'] = pd.to_timedelta(timedelta, 'm')\n+ rain['new_time'] = rain.index + rain['mins_added']\n+ rain_var_times = rain.set_index('new_time').iloc[:, 0]\n+ result = hsu(\n+ rainfall=rain_var_times, cleaning_threshold=0.5, tilt=50.0,\n+ pm2_5=1, pm10=2, depo_veloc=depo_veloc,\n+ rain_accum_period=pd.Timedelta('2h'))\n+ assert np.allclose(result, expected_output_3)\n+\n @pytest.fixture\n def greensboro_rain():\n # get TMY3 data with rain\n", "problem_statement": "pvlib.soiling.hsu model implementation errors\n**Describe the bug**\r\nI ran an example run using the Matlab version of the HSU soiling function and found that the python version did not give anywhere near the same results. The Matlab results matched the results in the original JPV paper. As a result of this test, I found two errors in the python implementation, which are listed below:\r\n\r\n1. depo_veloc = {'2_5': 0.004, '10': 0.0009} has the wrong default values. They are reversed.\r\nThe proper dictionary should be: {'2_5': 0.0009, '10': 0.004}. This is confirmed in the JPV paper and the Matlab version of the function.\r\n\r\n2. The horiz_mass_rate is in g/(m^2*hr) but should be in g/(m^2*s). The line needs to be multiplied by 60x60 or 3600.\r\nThe proper line of code should be: \r\nhoriz_mass_rate = (pm2_5 * depo_veloc['2_5']+ np.maximum(pm10 - pm2_5, 0.) * depo_veloc['10'])*3600\r\n\r\nWhen I made these changes I was able to match the validation dataset from the JPV paper, as shown below.\r\n\r\n\r\n\n", "hints_text": "nice sleuthing Josh! Is a PR forthcoming? \ud83c\udf89 \nHi Mark,\r\n Yes, a PR is in the works. I need to improve the testing first.\r\n\r\n-Josh\r\n\r\nFrom: Mark Mikofski <[email protected]>\r\nReply-To: pvlib/pvlib-python <[email protected]>\r\nDate: Tuesday, May 19, 2020 at 3:51 PM\r\nTo: pvlib/pvlib-python <[email protected]>\r\nCc: Joshua Stein <[email protected]>, Author <[email protected]>\r\nSubject: [EXTERNAL] Re: [pvlib/pvlib-python] pvlib.soiling.hsu model implementation errors (#970)\r\n\r\n\r\nnice sleuthing Josh! Is a PR forthcoming? \ud83c\udf89\r\n\r\n\u2014\r\nYou are receiving this because you authored the thread.\r\nReply to this email directly, view it on GitHub<https://github.com/pvlib/pvlib-python/issues/970#issuecomment-631102921>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/ABJES5C2CRTZFF7ROT2EPOTRSL5ORANCNFSM4NFL4K3Q>.\r\n\nNow I need to go back and figure out where I missed these errors in the review.", "created_at": "2020-06-12T17:45:46Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_soiling.py::test_hsu_no_cleaning", "pvlib/tests/test_soiling.py::test_hsu", "pvlib/tests/test_soiling.py::test_hsu_defaults", "pvlib/tests/test_soiling.py::test_hsu_variable_time_intervals"], "PASS_TO_PASS": ["pvlib/tests/test_soiling.py::test_kimber_nowash", "pvlib/tests/test_soiling.py::test_kimber_manwash", "pvlib/tests/test_soiling.py::test_kimber_norain", "pvlib/tests/test_soiling.py::test_kimber_initial_soil"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1048", "base_commit": "7fc595a13bcd42e3269c0806f5505ac907af9730", "patch": "diff --git a/pvlib/ivtools/__init__.py b/pvlib/ivtools/__init__.py\n--- a/pvlib/ivtools/__init__.py\n+++ b/pvlib/ivtools/__init__.py\n@@ -4,4 +4,4 @@\n \n \"\"\"\n \n-from pvlib.ivtools import sde, sdm, utility # noqa: F401\n+from pvlib.ivtools import sde, sdm, utils # noqa: F401\ndiff --git a/pvlib/ivtools/sde.py b/pvlib/ivtools/sde.py\n--- a/pvlib/ivtools/sde.py\n+++ b/pvlib/ivtools/sde.py\n@@ -7,7 +7,7 @@\n \n import numpy as np\n \n-from pvlib.ivtools.utility import _schumaker_qspline\n+from pvlib.ivtools.utils import _schumaker_qspline\n \n \n # set constant for numpy.linalg.lstsq parameter rcond\ndiff --git a/pvlib/ivtools/sdm.py b/pvlib/ivtools/sdm.py\n--- a/pvlib/ivtools/sdm.py\n+++ b/pvlib/ivtools/sdm.py\n@@ -10,7 +10,7 @@\n \n from pvlib.pvsystem import singlediode, v_from_i\n \n-from pvlib.ivtools.utility import constants, rectify_iv_curve, _numdiff\n+from pvlib.ivtools.utils import rectify_iv_curve, _numdiff\n from pvlib.ivtools.sde import _fit_sandia_cocontent\n \n \n@@ -301,7 +301,7 @@ def _system_of_equations_desoto(params, specs):\n return y\n \n \n-def fit_pvsyst_sandia(ivcurves, specs, const=constants, maxiter=5, eps1=1.e-3):\n+def fit_pvsyst_sandia(ivcurves, specs, const=None, maxiter=5, eps1=1.e-3):\n \"\"\"\n Estimate parameters for the PVsyst module performance model.\n \n@@ -416,6 +416,9 @@ def fit_pvsyst_sandia(ivcurves, specs, const=constants, maxiter=5, eps1=1.e-3):\n .. [7] PVLib MATLAB https://github.com/sandialabs/MATLAB_PV_LIB\n \"\"\"\n \n+ if const is None:\n+ const = {'E0': 1000.0, 'T0': 25.0, 'k': 1.38066e-23, 'q': 1.60218e-19}\n+\n ee = ivcurves['ee']\n tc = ivcurves['tc']\n tck = tc + 273.15\n@@ -476,7 +479,7 @@ def fit_pvsyst_sandia(ivcurves, specs, const=constants, maxiter=5, eps1=1.e-3):\n return pvsyst\n \n \n-def fit_desoto_sandia(ivcurves, specs, const=constants, maxiter=5, eps1=1.e-3):\n+def fit_desoto_sandia(ivcurves, specs, const=None, maxiter=5, eps1=1.e-3):\n \"\"\"\n Estimate parameters for the De Soto module performance model.\n \n@@ -575,6 +578,9 @@ def fit_desoto_sandia(ivcurves, specs, const=constants, maxiter=5, eps1=1.e-3):\n .. [4] PVLib MATLAB https://github.com/sandialabs/MATLAB_PV_LIB\n \"\"\"\n \n+ if const is None:\n+ const = {'E0': 1000.0, 'T0': 25.0, 'k': 1.38066e-23, 'q': 1.60218e-19}\n+\n ee = ivcurves['ee']\n tc = ivcurves['tc']\n tck = tc + 273.15\n@@ -939,10 +945,11 @@ def _update_io(voc, iph, io, rs, rsh, nnsvth):\n dvoc = pvoc - voc\n \n # Update Io\n- new_io = tio * (1. + (2. * dvoc) / (2. * nnsvth - dvoc))\n+ with np.errstate(invalid=\"ignore\", divide=\"ignore\"):\n+ new_io = tio * (1. + (2. * dvoc) / (2. * nnsvth - dvoc))\n+ # Calculate Maximum Percent Difference\n+ maxerr = np.max(np.abs(new_io - tio) / tio) * 100.\n \n- # Calculate Maximum Percent Difference\n- maxerr = np.max(np.abs(new_io - tio) / tio) * 100.\n tio = new_io\n k += 1.\n \n@@ -1131,8 +1138,9 @@ def _update_rsh_fixed_pt(vmp, imp, iph, io, rs, rsh, nnsvth):\n \n for i in range(niter):\n _, z = _calc_theta_phi_exact(vmp, imp, iph, io, rs, x1, nnsvth)\n- next_x1 = (1 + z) / z * ((iph + io) * x1 / imp - nnsvth * z / imp - 2 *\n- vmp / imp)\n+ with np.errstate(divide=\"ignore\"):\n+ next_x1 = (1 + z) / z * ((iph + io) * x1 / imp - nnsvth * z / imp\n+ - 2 * vmp / imp)\n x1 = next_x1\n \n return x1\n@@ -1200,12 +1208,12 @@ def _calc_theta_phi_exact(vmp, imp, iph, io, rs, rsh, nnsvth):\n \n # Argument for Lambert W function involved in V = V(I) [2] Eq. 12; [3]\n # Eq. 3\n- with np.errstate(over=\"ignore\"):\n+ with np.errstate(over=\"ignore\", divide=\"ignore\", invalid=\"ignore\"):\n argw = np.where(\n nnsvth == 0,\n np.nan,\n rsh * io / nnsvth * np.exp(rsh * (iph + io - imp) / nnsvth))\n- phi = np.where(argw > 0, lambertw(argw).real, np.nan)\n+ phi = np.where(argw > 0, lambertw(argw).real, np.nan)\n \n # NaN where argw overflows. Switch to log space to evaluate\n u = np.isinf(argw)\n@@ -1225,21 +1233,23 @@ def _calc_theta_phi_exact(vmp, imp, iph, io, rs, rsh, nnsvth):\n \n # Argument for Lambert W function involved in I = I(V) [2] Eq. 11; [3]\n # E1. 2\n- with np.errstate(over=\"ignore\"):\n+ with np.errstate(over=\"ignore\", divide=\"ignore\", invalid=\"ignore\"):\n argw = np.where(\n nnsvth == 0,\n np.nan,\n rsh / (rsh + rs) * rs * io / nnsvth * np.exp(\n rsh / (rsh + rs) * (rs * (iph + io) + vmp) / nnsvth))\n- theta = np.where(argw > 0, lambertw(argw).real, np.nan)\n+ theta = np.where(argw > 0, lambertw(argw).real, np.nan)\n \n # NaN where argw overflows. Switch to log space to evaluate\n u = np.isinf(argw)\n if np.any(u):\n- logargw = (\n- np.log(rsh[u]) / (rsh[u] + rs[u]) + np.log(rs[u]) + np.log(io[u])\n- - np.log(nnsvth[u]) + (rsh[u] / (rsh[u] + rs[u]))\n- * (rs[u] * (iph[u] + io[u]) + vmp[u]) / nnsvth[u])\n+ with np.errstate(divide=\"ignore\"):\n+ logargw = (\n+ np.log(rsh[u]) - np.log(rsh[u] + rs[u]) + np.log(rs[u])\n+ + np.log(io[u]) - np.log(nnsvth[u])\n+ + (rsh[u] / (rsh[u] + rs[u]))\n+ * (rs[u] * (iph[u] + io[u]) + vmp[u]) / nnsvth[u])\n # Three iterations of Newton-Raphson method to solve w+log(w)=logargW.\n # The initial guess is w=logargW. Where direct evaluation (above)\n # results in NaN from overflow, 3 iterations of Newton's method gives\ndiff --git a/pvlib/ivtools/utility.py b/pvlib/ivtools/utils.py\nsimilarity index 98%\nrename from pvlib/ivtools/utility.py\nrename to pvlib/ivtools/utils.py\n--- a/pvlib/ivtools/utility.py\n+++ b/pvlib/ivtools/utils.py\n@@ -1,5 +1,5 @@\n \"\"\"\n-The ``pvlib.ivtools.utility.py`` module contains utility functions related to\n+The ``pvlib.ivtools.utils.py`` module contains utility functions related to\n working with IV curves, or fitting equations to IV curve data.\n \n \"\"\"\n@@ -12,9 +12,6 @@\n EPS = np.finfo('float').eps**(1/3)\n \n \n-constants = {'E0': 1000.0, 'T0': 25.0, 'k': 1.38066e-23, 'q': 1.60218e-19}\n-\n-\n def _numdiff(x, f):\n \"\"\"\n Compute first and second order derivative using possibly unequally\n", "test_patch": "diff --git a/pvlib/tests/ivtools/test_utility.py b/pvlib/tests/ivtools/test_utils.py\nsimilarity index 96%\nrename from pvlib/tests/ivtools/test_utility.py\nrename to pvlib/tests/ivtools/test_utils.py\n--- a/pvlib/tests/ivtools/test_utility.py\n+++ b/pvlib/tests/ivtools/test_utils.py\n@@ -1,8 +1,8 @@\n import numpy as np\n import pandas as pd\n import pytest\n-from pvlib.ivtools.utility import _numdiff, rectify_iv_curve\n-from pvlib.ivtools.utility import _schumaker_qspline\n+from pvlib.ivtools.utils import _numdiff, rectify_iv_curve\n+from pvlib.ivtools.utils import _schumaker_qspline\n \n from conftest import DATA_DIR\n \n", "problem_statement": "warnings in test_sdm\nhttps://dev.azure.com/solararbiter/pvlib%20python/_build/results?buildId=4054&view=logs&j=fc432b8b-e2e3-594e-d8b1-15597b6c1d62&t=309866e1-2cf4-5f00-3d0a-999fc3a0f279&l=209\r\n\r\nthrough\r\n\r\nhttps://dev.azure.com/solararbiter/pvlib%20python/_build/results?buildId=4054&view=logs&j=fc432b8b-e2e3-594e-d8b1-15597b6c1d62&t=309866e1-2cf4-5f00-3d0a-999fc3a0f279&l=295\r\n\r\nSo almost 100 lines of warnings.\n", "hints_text": "Not bugs per se, the algorithm handles non-convergence when looping through the IV curves by continuing, although the rattling and squeaks are audible. I'd prefer to keep that behavior and silencing divide by 0 and invalid (nan) value warnings in place, if that's OK.\nNo problem with the algorithm, just its rattles and squeaks. Does it need to emit its own more useful warnings?\nIt could, but the causes for non-convergence may not be easy to identify and state. The returned dict includes a Boolean array that is False for IV curves for which it didn't get parameters. It could warn that the array is non-empty, but that seems unnecessary to me.", "created_at": "2020-09-05T22:40:49Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/ivtools/test_utils.py::test__numdiff", "pvlib/tests/ivtools/test_utils.py::test_rectify_iv_curve", "pvlib/tests/ivtools/test_utils.py::test__schmumaker_qspline[x0-y0-expected0]", "pvlib/tests/ivtools/test_utils.py::test__schmumaker_qspline[x1-y1-expected1]", "pvlib/tests/ivtools/test_utils.py::test__schmumaker_qspline[x2-y2-expected2]"], "PASS_TO_PASS": [], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1623", "base_commit": "30c62e368529df01faa609d6b38456a7b0db9b53", "patch": "diff --git a/docs/examples/adr-pvarray/plot_simulate_system.py b/docs/examples/adr-pvarray/plot_simulate_system.py\n--- a/docs/examples/adr-pvarray/plot_simulate_system.py\n+++ b/docs/examples/adr-pvarray/plot_simulate_system.py\n@@ -29,10 +29,12 @@\n PVLIB_DIR = pvlib.__path__[0]\n DATA_FILE = os.path.join(PVLIB_DIR, 'data', '723170TYA.CSV')\n \n-tmy, metadata = iotools.read_tmy3(DATA_FILE, coerce_year=1990)\n+tmy, metadata = iotools.read_tmy3(DATA_FILE, coerce_year=1990,\n+ map_variables=True)\n \n-df = pd.DataFrame({'ghi': tmy['GHI'], 'dhi': tmy['DHI'], 'dni': tmy['DNI'],\n- 'temp_air': tmy['DryBulb'], 'wind_speed': tmy['Wspd'],\n+df = pd.DataFrame({'ghi': tmy['ghi'], 'dhi': tmy['dhi'], 'dni': tmy['dni'],\n+ 'temp_air': tmy['temp_air'],\n+ 'wind_speed': tmy['wind_speed'],\n })\n \n # %%\ndiff --git a/docs/examples/irradiance-decomposition/plot_diffuse_fraction.py b/docs/examples/irradiance-decomposition/plot_diffuse_fraction.py\n--- a/docs/examples/irradiance-decomposition/plot_diffuse_fraction.py\n+++ b/docs/examples/irradiance-decomposition/plot_diffuse_fraction.py\n@@ -27,7 +27,8 @@\n # of data measured from 1990 to 2010. Therefore we change the timestamps to a\n # common year, 1990.\n DATA_DIR = pathlib.Path(pvlib.__file__).parent / 'data'\n-greensboro, metadata = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990)\n+greensboro, metadata = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990,\n+ map_variables=True)\n \n # Many of the diffuse fraction estimation methods require the \"true\" zenith, so\n # we calculate the solar positions for the 1990 at Greensboro, NC.\n@@ -36,8 +37,8 @@\n solpos = get_solarposition(\n greensboro.index.shift(freq=\"-30T\"), latitude=metadata['latitude'],\n longitude=metadata['longitude'], altitude=metadata['altitude'],\n- pressure=greensboro.Pressure*100, # convert from millibar to Pa\n- temperature=greensboro.DryBulb)\n+ pressure=greensboro.pressure*100, # convert from millibar to Pa\n+ temperature=greensboro.temp_air)\n solpos.index = greensboro.index # reset index to end of the hour\n \n # %%\n@@ -56,10 +57,10 @@\n # an exponential relation with airmass.\n \n out_disc = irradiance.disc(\n- greensboro.GHI, solpos.zenith, greensboro.index, greensboro.Pressure*100)\n+ greensboro.ghi, solpos.zenith, greensboro.index, greensboro.pressure*100)\n # use \"complete sum\" AKA \"closure\" equations: DHI = GHI - DNI * cos(zenith)\n df_disc = irradiance.complete_irradiance(\n- solar_zenith=solpos.apparent_zenith, ghi=greensboro.GHI, dni=out_disc.dni,\n+ solar_zenith=solpos.apparent_zenith, ghi=greensboro.ghi, dni=out_disc.dni,\n dhi=None)\n out_disc = out_disc.rename(columns={'dni': 'dni_disc'})\n out_disc['dhi_disc'] = df_disc.dhi\n@@ -72,11 +73,11 @@\n # developed by Richard Perez and Pierre Ineichen in 1992.\n \n dni_dirint = irradiance.dirint(\n- greensboro.GHI, solpos.zenith, greensboro.index, greensboro.Pressure*100,\n- temp_dew=greensboro.DewPoint)\n+ greensboro.ghi, solpos.zenith, greensboro.index, greensboro.pressure*100,\n+ temp_dew=greensboro.temp_dew)\n # use \"complete sum\" AKA \"closure\" equation: DHI = GHI - DNI * cos(zenith)\n df_dirint = irradiance.complete_irradiance(\n- solar_zenith=solpos.apparent_zenith, ghi=greensboro.GHI, dni=dni_dirint,\n+ solar_zenith=solpos.apparent_zenith, ghi=greensboro.ghi, dni=dni_dirint,\n dhi=None)\n out_dirint = pd.DataFrame(\n {'dni_dirint': dni_dirint, 'dhi_dirint': df_dirint.dhi},\n@@ -91,7 +92,7 @@\n # splits kt into 3 regions: linear for kt <= 0.22, a 4th order polynomial\n # between 0.22 < kt <= 0.8, and a horizontal line for kt > 0.8.\n \n-out_erbs = irradiance.erbs(greensboro.GHI, solpos.zenith, greensboro.index)\n+out_erbs = irradiance.erbs(greensboro.ghi, solpos.zenith, greensboro.index)\n out_erbs = out_erbs.rename(columns={'dni': 'dni_erbs', 'dhi': 'dhi_erbs'})\n \n # %%\n@@ -102,7 +103,7 @@\n # exponential correlation that is continuously differentiable and bounded\n # between zero and one.\n \n-out_boland = irradiance.boland(greensboro.GHI, solpos.zenith, greensboro.index)\n+out_boland = irradiance.boland(greensboro.ghi, solpos.zenith, greensboro.index)\n out_boland = out_boland.rename(\n columns={'dni': 'dni_boland', 'dhi': 'dhi_boland'})\n \n@@ -118,20 +119,20 @@\n # file together to make plotting easier.\n \n dni_renames = {\n- 'DNI': 'TMY3', 'dni_disc': 'DISC', 'dni_dirint': 'DIRINT',\n+ 'dni': 'TMY3', 'dni_disc': 'DISC', 'dni_dirint': 'DIRINT',\n 'dni_erbs': 'Erbs', 'dni_boland': 'Boland'}\n dni = [\n- greensboro.DNI, out_disc.dni_disc, out_dirint.dni_dirint,\n+ greensboro.dni, out_disc.dni_disc, out_dirint.dni_dirint,\n out_erbs.dni_erbs, out_boland.dni_boland]\n dni = pd.concat(dni, axis=1).rename(columns=dni_renames)\n dhi_renames = {\n- 'DHI': 'TMY3', 'dhi_disc': 'DISC', 'dhi_dirint': 'DIRINT',\n+ 'dhi': 'TMY3', 'dhi_disc': 'DISC', 'dhi_dirint': 'DIRINT',\n 'dhi_erbs': 'Erbs', 'dhi_boland': 'Boland'}\n dhi = [\n- greensboro.DHI, out_disc.dhi_disc, out_dirint.dhi_dirint,\n+ greensboro.dhi, out_disc.dhi_disc, out_dirint.dhi_dirint,\n out_erbs.dhi_erbs, out_boland.dhi_boland]\n dhi = pd.concat(dhi, axis=1).rename(columns=dhi_renames)\n-ghi_kt = pd.concat([greensboro.GHI/1000.0, out_erbs.kt], axis=1)\n+ghi_kt = pd.concat([greensboro.ghi/1000.0, out_erbs.kt], axis=1)\n \n # %%\n # Winter\ndiff --git a/docs/examples/irradiance-transposition/plot_seasonal_tilt.py b/docs/examples/irradiance-transposition/plot_seasonal_tilt.py\n--- a/docs/examples/irradiance-transposition/plot_seasonal_tilt.py\n+++ b/docs/examples/irradiance-transposition/plot_seasonal_tilt.py\n@@ -44,12 +44,13 @@ def get_orientation(self, solar_zenith, solar_azimuth):\n # like we expect:\n \n DATA_DIR = pathlib.Path(pvlib.__file__).parent / 'data'\n-tmy, metadata = iotools.read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990)\n+tmy, metadata = iotools.read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990,\n+ map_variables=True)\n # shift from TMY3 right-labeled index to left-labeled index:\n tmy.index = tmy.index - pd.Timedelta(hours=1)\n weather = pd.DataFrame({\n- 'ghi': tmy['GHI'], 'dhi': tmy['DHI'], 'dni': tmy['DNI'],\n- 'temp_air': tmy['DryBulb'], 'wind_speed': tmy['Wspd'],\n+ 'ghi': tmy['ghi'], 'dhi': tmy['dhi'], 'dni': tmy['dni'],\n+ 'temp_air': tmy['temp_air'], 'wind_speed': tmy['wind_speed'],\n })\n loc = location.Location.from_tmy(metadata)\n solpos = loc.get_solarposition(weather.index)\ndiff --git a/docs/examples/irradiance-transposition/plot_transposition_gain.py b/docs/examples/irradiance-transposition/plot_transposition_gain.py\n--- a/docs/examples/irradiance-transposition/plot_transposition_gain.py\n+++ b/docs/examples/irradiance-transposition/plot_transposition_gain.py\n@@ -32,7 +32,8 @@\n DATA_DIR = pathlib.Path(pvlib.__file__).parent / 'data'\n \n # get TMY3 dataset\n-tmy, metadata = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990)\n+tmy, metadata = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990,\n+ map_variables=True)\n # TMY3 datasets are right-labeled (AKA \"end of interval\") which means the last\n # interval of Dec 31, 23:00 to Jan 1 00:00 is labeled Jan 1 00:00. When rolling\n # up hourly irradiance to monthly insolation, a spurious January value is\n@@ -60,9 +61,9 @@ def calculate_poa(tmy, solar_position, surface_tilt, surface_azimuth):\n poa = irradiance.get_total_irradiance(\n surface_tilt=surface_tilt,\n surface_azimuth=surface_azimuth,\n- dni=tmy['DNI'],\n- ghi=tmy['GHI'],\n- dhi=tmy['DHI'],\n+ dni=tmy['dni'],\n+ ghi=tmy['ghi'],\n+ dhi=tmy['dhi'],\n solar_zenith=solar_position['apparent_zenith'],\n solar_azimuth=solar_position['azimuth'],\n model='isotropic')\n@@ -97,7 +98,7 @@ def calculate_poa(tmy, solar_position, surface_tilt, surface_azimuth):\n df_monthly['SAT-0.4'] = poa_irradiance.resample('m').sum()\n \n # calculate the percent difference from GHI\n-ghi_monthly = tmy['GHI'].resample('m').sum()\n+ghi_monthly = tmy['ghi'].resample('m').sum()\n df_monthly = 100 * (df_monthly.divide(ghi_monthly, axis=0) - 1)\n \n df_monthly.plot()\ndiff --git a/docs/examples/soiling/plot_greensboro_kimber_soiling.py b/docs/examples/soiling/plot_greensboro_kimber_soiling.py\n--- a/docs/examples/soiling/plot_greensboro_kimber_soiling.py\n+++ b/docs/examples/soiling/plot_greensboro_kimber_soiling.py\n@@ -40,9 +40,10 @@\n DATA_DIR = pathlib.Path(pvlib.__file__).parent / 'data'\n \n # get TMY3 data with rain\n-greensboro, _ = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990)\n+greensboro, _ = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990,\n+ map_variables=True)\n # get the rain data\n-greensboro_rain = greensboro.Lprecipdepth\n+greensboro_rain = greensboro['Lprecip depth (mm)']\n # calculate soiling with no wash dates and cleaning threshold of 25-mm of rain\n THRESHOLD = 25.0\n soiling_no_wash = kimber(greensboro_rain, cleaning_threshold=THRESHOLD)\ndiff --git a/pvlib/iotools/tmy.py b/pvlib/iotools/tmy.py\n--- a/pvlib/iotools/tmy.py\n+++ b/pvlib/iotools/tmy.py\n@@ -3,9 +3,28 @@\n import datetime\n import re\n import pandas as pd\n-\n-\n-def read_tmy3(filename, coerce_year=None, recolumn=True):\n+import warnings\n+from pvlib._deprecation import pvlibDeprecationWarning\n+\n+# Dictionary mapping TMY3 names to pvlib names\n+VARIABLE_MAP = {\n+ 'GHI (W/m^2)': 'ghi',\n+ 'ETR (W/m^2)': 'ghi_extra',\n+ 'DNI (W/m^2)': 'dni',\n+ 'ETRN (W/m^2)': 'dni_extra',\n+ 'DHI (W/m^2)': 'dhi',\n+ 'Pressure (mbar)': 'pressure',\n+ 'Wdir (degrees)': 'wind_direction',\n+ 'Wspd (m/s)': 'wind_speed',\n+ 'Dry-bulb (C)': 'temp_air',\n+ 'Dew-point (C)': 'temp_dew',\n+ 'RHum (%)': 'relative_humidity',\n+ 'Alb (unitless)': 'albedo',\n+ 'Pwat (cm)': 'precipitable_water'\n+}\n+\n+\n+def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n \"\"\"Read a TMY3 file into a pandas dataframe.\n \n Note that values contained in the metadata dictionary are unchanged\n@@ -24,9 +43,13 @@ def read_tmy3(filename, coerce_year=None, recolumn=True):\n If supplied, the year of the index will be set to `coerce_year`, except\n for the last index value which will be set to the *next* year so that\n the index increases monotonically.\n- recolumn : bool, default True\n+ map_variables : bool, default None\n+ When True, renames columns of the DataFrame to pvlib variable names\n+ where applicable. See variable :const:`VARIABLE_MAP`.\n+ recolumn : bool (deprecated, use map_variables instead)\n If ``True``, apply standard names to TMY3 columns. Typically this\n results in stripping the units from the column name.\n+ Cannot be used in combination with ``map_variables``.\n \n Returns\n -------\n@@ -57,80 +80,83 @@ def read_tmy3(filename, coerce_year=None, recolumn=True):\n USAF Int USAF identifier\n =============== ====== ===================\n \n- ===================== ======================================================================================================================================================\n- field description\n- ===================== ======================================================================================================================================================\n- Index A pandas datetime index. NOTE, the index is timezone aware, and times are set to local standard time (daylight savings is not included)\n- ETR Extraterrestrial horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n- ETRN Extraterrestrial normal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n- GHI Direct and diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n- GHISource See [1]_, Table 1-4\n- GHIUncertainty Uncertainty based on random and bias error estimates see [2]_\n- DNI Amount of direct normal radiation (modeled) recv'd during 60 mintues prior to timestamp, Wh/m^2\n- DNISource See [1]_, Table 1-4\n- DNIUncertainty Uncertainty based on random and bias error estimates see [2]_\n- DHI Amount of diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n- DHISource See [1]_, Table 1-4\n- DHIUncertainty Uncertainty based on random and bias error estimates see [2]_\n- GHillum Avg. total horizontal illuminance recv'd during the 60 minutes prior to timestamp, lx\n- GHillumSource See [1]_, Table 1-4\n- GHillumUncertainty Uncertainty based on random and bias error estimates see [2]_\n- DNillum Avg. direct normal illuminance recv'd during the 60 minutes prior to timestamp, lx\n- DNillumSource See [1]_, Table 1-4\n- DNillumUncertainty Uncertainty based on random and bias error estimates see [2]_\n- DHillum Avg. horizontal diffuse illuminance recv'd during the 60 minutes prior to timestamp, lx\n- DHillumSource See [1]_, Table 1-4\n- DHillumUncertainty Uncertainty based on random and bias error estimates see [2]_\n- Zenithlum Avg. luminance at the sky's zenith during the 60 minutes prior to timestamp, cd/m^2\n- ZenithlumSource See [1]_, Table 1-4\n- ZenithlumUncertainty Uncertainty based on random and bias error estimates see [1]_ section 2.10\n- TotCld Amount of sky dome covered by clouds or obscuring phenonema at time stamp, tenths of sky\n- TotCldSource See [1]_, Table 1-5\n- TotCldUncertainty See [1]_, Table 1-6\n- OpqCld Amount of sky dome covered by clouds or obscuring phenonema that prevent observing the sky at time stamp, tenths of sky\n- OpqCldSource See [1]_, Table 1-5\n- OpqCldUncertainty See [1]_, Table 1-6\n- DryBulb Dry bulb temperature at the time indicated, deg C\n- DryBulbSource See [1]_, Table 1-5\n- DryBulbUncertainty See [1]_, Table 1-6\n- DewPoint Dew-point temperature at the time indicated, deg C\n- DewPointSource See [1]_, Table 1-5\n- DewPointUncertainty See [1]_, Table 1-6\n- RHum Relatitudeive humidity at the time indicated, percent\n- RHumSource See [1]_, Table 1-5\n- RHumUncertainty See [1]_, Table 1-6\n- Pressure Station pressure at the time indicated, 1 mbar\n- PressureSource See [1]_, Table 1-5\n- PressureUncertainty See [1]_, Table 1-6\n- Wdir Wind direction at time indicated, degrees from north (360 = north; 0 = undefined,calm)\n- WdirSource See [1]_, Table 1-5\n- WdirUncertainty See [1]_, Table 1-6\n- Wspd Wind speed at the time indicated, meter/second\n- WspdSource See [1]_, Table 1-5\n- WspdUncertainty See [1]_, Table 1-6\n- Hvis Distance to discernable remote objects at time indicated (7777=unlimited), meter\n- HvisSource See [1]_, Table 1-5\n- HvisUncertainty See [1]_, Table 1-6\n- CeilHgt Height of cloud base above local terrain (7777=unlimited), meter\n- CeilHgtSource See [1]_, Table 1-5\n- CeilHgtUncertainty See [1]_, Table 1-6\n- Pwat Total precipitable water contained in a column of unit cross section from earth to top of atmosphere, cm\n- PwatSource See [1]_, Table 1-5\n- PwatUncertainty See [1]_, Table 1-6\n- AOD The broadband aerosol optical depth per unit of air mass due to extinction by aerosol component of atmosphere, unitless\n- AODSource See [1]_, Table 1-5\n- AODUncertainty See [1]_, Table 1-6\n- Alb The ratio of reflected solar irradiance to global horizontal irradiance, unitless\n- AlbSource See [1]_, Table 1-5\n- AlbUncertainty See [1]_, Table 1-6\n- Lprecipdepth The amount of liquid precipitation observed at indicated time for the period indicated in the liquid precipitation quantity field, millimeter\n- Lprecipquantity The period of accumulatitudeion for the liquid precipitation depth field, hour\n- LprecipSource See [1]_, Table 1-5\n- LprecipUncertainty See [1]_, Table 1-6\n- PresWth Present weather code, see [2]_.\n- PresWthSource Present weather code source, see [2]_.\n- PresWthUncertainty Present weather code uncertainty, see [2]_.\n- ===================== ======================================================================================================================================================\n+\n+ ======================== ======================================================================================================================================================\n+ field description\n+ ======================== ======================================================================================================================================================\n+ **\u2020 denotes variables that are mapped when `map_variables` is True**\n+ -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n+ Index A pandas datetime index. NOTE, the index is timezone aware, and times are set to local standard time (daylight savings is not included)\n+ ghi_extra\u2020 Extraterrestrial horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n+ dni_extra\u2020 Extraterrestrial normal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n+ ghi\u2020 Direct and diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n+ GHI source See [1]_, Table 1-4\n+ GHI uncert (%) Uncertainty based on random and bias error estimates see [2]_\n+ dni\u2020 Amount of direct normal radiation (modeled) recv'd during 60 mintues prior to timestamp, Wh/m^2\n+ DNI source See [1]_, Table 1-4\n+ DNI uncert (%) Uncertainty based on random and bias error estimates see [2]_\n+ dhi\u2020 Amount of diffuse horizontal radiation recv'd during 60 minutes prior to timestamp, Wh/m^2\n+ DHI source See [1]_, Table 1-4\n+ DHI uncert (%) Uncertainty based on random and bias error estimates see [2]_\n+ GH illum (lx) Avg. total horizontal illuminance recv'd during the 60 minutes prior to timestamp, lx\n+ GH illum source See [1]_, Table 1-4\n+ GH illum uncert (%) Uncertainty based on random and bias error estimates see [2]_\n+ DN illum (lx) Avg. direct normal illuminance recv'd during the 60 minutes prior to timestamp, lx\n+ DN illum source See [1]_, Table 1-4\n+ DN illum uncert (%) Uncertainty based on random and bias error estimates see [2]_\n+ DH illum (lx) Avg. horizontal diffuse illuminance recv'd during the 60 minutes prior to timestamp, lx\n+ DH illum source See [1]_, Table 1-4\n+ DH illum uncert (%) Uncertainty based on random and bias error estimates see [2]_\n+ Zenith lum (cd/m^2) Avg. luminance at the sky's zenith during the 60 minutes prior to timestamp, cd/m^2\n+ Zenith lum source See [1]_, Table 1-4\n+ Zenith lum uncert (%) Uncertainty based on random and bias error estimates see [1]_ section 2.10\n+ TotCld (tenths) Amount of sky dome covered by clouds or obscuring phenonema at time stamp, tenths of sky\n+ TotCld source See [1]_, Table 1-5\n+ TotCld uncert (code) See [1]_, Table 1-6\n+ OpqCld (tenths) Amount of sky dome covered by clouds or obscuring phenonema that prevent observing the sky at time stamp, tenths of sky\n+ OpqCld source See [1]_, Table 1-5\n+ OpqCld uncert (code) See [1]_, Table 1-6\n+ temp_air\u2020 Dry bulb temperature at the time indicated, deg C\n+ Dry-bulb source See [1]_, Table 1-5\n+ Dry-bulb uncert (code) See [1]_, Table 1-6\n+ temp_dew\u2020 Dew-point temperature at the time indicated, deg C\n+ Dew-point source See [1]_, Table 1-5\n+ Dew-point uncert (code) See [1]_, Table 1-6\n+ relative_humidity\u2020 Relatitudeive humidity at the time indicated, percent\n+ RHum source See [1]_, Table 1-5\n+ RHum uncert (code) See [1]_, Table 1-6\n+ pressure\u2020 Station pressure at the time indicated, 1 mbar\n+ Pressure source See [1]_, Table 1-5\n+ Pressure uncert (code) See [1]_, Table 1-6\n+ wind_direction\u2020 Wind direction at time indicated, degrees from north (360 = north; 0 = undefined,calm)\n+ Wdir source See [1]_, Table 1-5\n+ Wdir uncert (code) See [1]_, Table 1-6\n+ wind_speed\u2020 Wind speed at the time indicated, meter/second\n+ Wspd source See [1]_, Table 1-5\n+ Wspd uncert (code) See [1]_, Table 1-6\n+ Hvis (m) Distance to discernable remote objects at time indicated (7777=unlimited), meter\n+ Hvis source See [1]_, Table 1-5\n+ Hvis uncert (coe) See [1]_, Table 1-6\n+ CeilHgt (m) Height of cloud base above local terrain (7777=unlimited), meter\n+ CeilHgt source See [1]_, Table 1-5\n+ CeilHgt uncert (code) See [1]_, Table 1-6\n+ precipitable_water\u2020 Total precipitable water contained in a column of unit cross section from earth to top of atmosphere, cm\n+ Pwat source See [1]_, Table 1-5\n+ Pwat uncert (code) See [1]_, Table 1-6\n+ AOD The broadband aerosol optical depth per unit of air mass due to extinction by aerosol component of atmosphere, unitless\n+ AOD source See [1]_, Table 1-5\n+ AOD uncert (code) See [1]_, Table 1-6\n+ albedo\u2020 The ratio of reflected solar irradiance to global horizontal irradiance, unitless\n+ Alb source See [1]_, Table 1-5\n+ Alb uncert (code) See [1]_, Table 1-6\n+ Lprecip depth (mm) The amount of liquid precipitation observed at indicated time for the period indicated in the liquid precipitation quantity field, millimeter\n+ Lprecip quantity (hr) The period of accumulatitudeion for the liquid precipitation depth field, hour\n+ Lprecip source See [1]_, Table 1-5\n+ Lprecip uncert (code) See [1]_, Table 1-6\n+ PresWth (METAR code) Present weather code, see [2]_.\n+ PresWth source Present weather code source, see [2]_.\n+ PresWth uncert (code) Present weather code uncertainty, see [2]_.\n+ ======================== ======================================================================================================================================================\n \n .. admonition:: Midnight representation\n \n@@ -152,8 +178,10 @@ def read_tmy3(filename, coerce_year=None, recolumn=True):\n ----------\n .. [1] Wilcox, S and Marion, W. \"Users Manual for TMY3 Data Sets\".\n NREL/TP-581-43156, Revised May 2008.\n+ :doi:`10.2172/928611`\n .. [2] Wilcox, S. (2007). National Solar Radiation Database 1991 2005\n Update: Users Manual. 472 pp.; NREL Report No. TP-581-41364.\n+ :doi:`10.2172/901864`\n .. [3] `SolarAnywhere file formats\n <https://www.solaranywhere.com/support/historical-data/file-formats/>`_\n \"\"\" # noqa: E501\n@@ -198,9 +226,26 @@ def read_tmy3(filename, coerce_year=None, recolumn=True):\n # NOTE: as of pvlib-0.6.3, min req is pandas-0.18.1, so pd.to_timedelta\n # unit must be in (D,h,m,s,ms,us,ns), but pandas>=0.24 allows unit='hour'\n data.index = data_ymd + pd.to_timedelta(shifted_hour, unit='h')\n-\n- if recolumn:\n- data = _recolumn(data) # rename to standard column names\n+ # shouldnt' specify both recolumn and map_variables\n+ if recolumn is not None and map_variables is not None:\n+ msg = \"`map_variables` and `recolumn` cannot both be specified\"\n+ raise ValueError(msg)\n+ elif map_variables is None and recolumn is not None:\n+ warnings.warn(\n+ 'The recolumn parameter is deprecated and will be removed in '\n+ 'pvlib 0.11.0. Use `map_variables` instead, although note that '\n+ 'its behavior is different from `recolumn`.',\n+ pvlibDeprecationWarning)\n+ elif map_variables is None and recolumn is None:\n+ warnings.warn(\n+ 'TMY3 variable names will be renamed to pvlib conventions by '\n+ 'default starting in pvlib 0.11.0. Specify map_variables=True '\n+ 'to enable that behavior now, or specify map_variables=False '\n+ 'to hide this warning.', pvlibDeprecationWarning)\n+ if map_variables:\n+ data = data.rename(columns=VARIABLE_MAP)\n+ elif recolumn or (recolumn is None and map_variables is None):\n+ data = _recolumn(data)\n \n data = data.tz_localize(int(meta['TZ'] * 3600))\n \n", "test_patch": "diff --git a/pvlib/tests/iotools/test_tmy.py b/pvlib/tests/iotools/test_tmy.py\n--- a/pvlib/tests/iotools/test_tmy.py\n+++ b/pvlib/tests/iotools/test_tmy.py\n@@ -1,8 +1,10 @@\n import numpy as np\n import pandas as pd\n from pvlib.iotools import tmy\n+from pvlib._deprecation import pvlibDeprecationWarning\n from ..conftest import DATA_DIR\n import pytest\n+import warnings\n \n # test the API works\n from pvlib.iotools import read_tmy3\n@@ -16,29 +18,60 @@\n \n \n def test_read_tmy3():\n- tmy.read_tmy3(TMY3_TESTFILE)\n+ tmy.read_tmy3(TMY3_TESTFILE, map_variables=False)\n \n \n def test_read_tmy3_recolumn():\n- data, meta = tmy.read_tmy3(TMY3_TESTFILE)\n+ with warnings.catch_warnings():\n+ warnings.simplefilter(\"ignore\")\n+ data, meta = tmy.read_tmy3(TMY3_TESTFILE, recolumn=True)\n assert 'GHISource' in data.columns\n \n \n def test_read_tmy3_norecolumn():\n- data, _ = tmy.read_tmy3(TMY3_TESTFILE, recolumn=False)\n+ data, _ = tmy.read_tmy3(TMY3_TESTFILE, map_variables=False)\n assert 'GHI source' in data.columns\n \n \n+def test_read_tmy3_raise_valueerror():\n+ with pytest.raises(ValueError, match='`map_variables` and `recolumn`'):\n+ _ = tmy.read_tmy3(TMY3_TESTFILE, recolumn=True, map_variables=True)\n+\n+\n+def test_read_tmy3_map_variables():\n+ data, meta = tmy.read_tmy3(TMY3_TESTFILE, map_variables=True)\n+ assert 'ghi' in data.columns\n+ assert 'dni' in data.columns\n+ assert 'dhi' in data.columns\n+ assert 'pressure' in data.columns\n+ assert 'wind_direction' in data.columns\n+ assert 'wind_speed' in data.columns\n+ assert 'temp_air' in data.columns\n+ assert 'temp_dew' in data.columns\n+ assert 'relative_humidity' in data.columns\n+ assert 'albedo' in data.columns\n+ assert 'ghi_extra' in data.columns\n+ assert 'dni_extra' in data.columns\n+ assert 'precipitable_water' in data.columns\n+\n+\n+def test_read_tmy3_map_variables_deprecating_warning():\n+ with pytest.warns(pvlibDeprecationWarning, match='names will be renamed'):\n+ data, meta = tmy.read_tmy3(TMY3_TESTFILE)\n+\n+\n def test_read_tmy3_coerce_year():\n coerce_year = 1987\n- data, _ = tmy.read_tmy3(TMY3_TESTFILE, coerce_year=coerce_year)\n+ data, _ = tmy.read_tmy3(TMY3_TESTFILE, coerce_year=coerce_year,\n+ map_variables=False)\n assert (data.index[:-1].year == 1987).all()\n assert data.index[-1].year == 1988\n \n \n def test_read_tmy3_no_coerce_year():\n coerce_year = None\n- data, _ = tmy.read_tmy3(TMY3_TESTFILE, coerce_year=coerce_year)\n+ data, _ = tmy.read_tmy3(TMY3_TESTFILE, coerce_year=coerce_year,\n+ map_variables=False)\n assert 1997 and 1999 in data.index.year\n assert data.index[-2] == pd.Timestamp('1998-12-31 23:00:00-09:00')\n assert data.index[-1] == pd.Timestamp('1999-01-01 00:00:00-09:00')\n@@ -50,7 +83,7 @@ def test_read_tmy2():\n \n def test_gh865_read_tmy3_feb_leapyear_hr24():\n \"\"\"correctly parse the 24th hour if the tmy3 file has a leap year in feb\"\"\"\n- data, meta = read_tmy3(TMY3_FEB_LEAPYEAR)\n+ data, meta = read_tmy3(TMY3_FEB_LEAPYEAR, map_variables=False)\n # just to be safe, make sure this _IS_ the Greensboro file\n greensboro = {\n 'USAF': 723170,\n@@ -66,7 +99,8 @@ def test_gh865_read_tmy3_feb_leapyear_hr24():\n assert data.index[1414] == pd.Timestamp('1996-02-28 23:00:00-0500')\n assert data.index[1415] == pd.Timestamp('1996-03-01 00:00:00-0500')\n # now check if it parses correctly when we try to coerce the year\n- data, _ = read_tmy3(TMY3_FEB_LEAPYEAR, coerce_year=1990)\n+ data, _ = read_tmy3(TMY3_FEB_LEAPYEAR, coerce_year=1990,\n+ map_variables=False)\n # if get's here w/o an error, then gh865 is fixed, but let's check anyway\n assert all(data.index[:-1].year == 1990)\n assert data.index[-1].year == 1991\n@@ -87,7 +121,7 @@ def test_solaranywhere_tmy3(solaranywhere_index):\n # The SolarAnywhere TMY3 format specifies midnight as 00:00 whereas the\n # NREL TMY3 format utilizes 24:00. The SolarAnywhere file is therefore\n # included to test files with 00:00 timestamps are parsed correctly\n- data, meta = tmy.read_tmy3(TMY3_SOLARANYWHERE)\n+ data, meta = tmy.read_tmy3(TMY3_SOLARANYWHERE, map_variables=False)\n pd.testing.assert_index_equal(data.index, solaranywhere_index)\n assert meta['USAF'] == 0\n assert meta['Name'] == 'Burlington United States'\ndiff --git a/pvlib/tests/test_location.py b/pvlib/tests/test_location.py\n--- a/pvlib/tests/test_location.py\n+++ b/pvlib/tests/test_location.py\n@@ -212,7 +212,7 @@ def test_get_clearsky_valueerror(times):\n def test_from_tmy_3():\n from pvlib.tests.iotools.test_tmy import TMY3_TESTFILE\n from pvlib.iotools import read_tmy3\n- data, meta = read_tmy3(TMY3_TESTFILE)\n+ data, meta = read_tmy3(TMY3_TESTFILE, map_variables=True)\n loc = Location.from_tmy(meta, data)\n assert loc.name is not None\n assert loc.altitude != 0\ndiff --git a/pvlib/tests/test_soiling.py b/pvlib/tests/test_soiling.py\n--- a/pvlib/tests/test_soiling.py\n+++ b/pvlib/tests/test_soiling.py\n@@ -147,8 +147,9 @@ def test_hsu_variable_time_intervals(rainfall_input, expected_output_3):\n @pytest.fixture\n def greensboro_rain():\n # get TMY3 data with rain\n- greensboro, _ = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990)\n- return greensboro.Lprecipdepth\n+ greensboro, _ = read_tmy3(DATA_DIR / '723170TYA.CSV', coerce_year=1990,\n+ map_variables=True)\n+ return greensboro['Lprecip depth (mm)']\n \n \n @pytest.fixture\n", "problem_statement": "Add variable mapping of read_tmy3\n**Is your feature request related to a problem? Please describe.**\r\nThis PR proposes that a `map_variables` parameter be added to the `read_tmy3` function. Additionally, the current `rename_columns` parameter (which removes the units from the column names) should be deprecated. See #714 for a discussion on the topic.\r\n\r\n**Describe the solution you'd like**\r\nA `map_variables` parameter should be added (defaulting to None), and if specified as True then it should override the `rename_columns` parameter and map the column names to standard pvlib names. A deperecation warning should be added stating that the `rename_columns` parameter will be retired starting in pvlib 0.11.0 - the deprecation warning should be silenced if `map_variables` is specified as either True or False.\r\n\n", "hints_text": "", "created_at": "2022-12-21T16:44:19Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_tmy.py::test_read_tmy3", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_norecolumn", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_raise_valueerror", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_map_variables", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_map_variables_deprecating_warning", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_coerce_year", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_no_coerce_year", "pvlib/tests/iotools/test_tmy.py::test_gh865_read_tmy3_feb_leapyear_hr24", "pvlib/tests/iotools/test_tmy.py::test_solaranywhere_tmy3", "pvlib/tests/test_location.py::test_from_tmy_3", "pvlib/tests/test_soiling.py::test_kimber_nowash", "pvlib/tests/test_soiling.py::test_kimber_manwash", "pvlib/tests/test_soiling.py::test_kimber_norain", "pvlib/tests/test_soiling.py::test_kimber_initial_soil"], "PASS_TO_PASS": ["pvlib/tests/iotools/test_tmy.py::test_read_tmy3_recolumn", "pvlib/tests/iotools/test_tmy.py::test_read_tmy2", "pvlib/tests/test_location.py::test_location_required", "pvlib/tests/test_location.py::test_location_all", "pvlib/tests/test_location.py::test_location_tz[tz0]", "pvlib/tests/test_location.py::test_location_tz[America/Phoenix]", "pvlib/tests/test_location.py::test_location_tz[-7]", "pvlib/tests/test_location.py::test_location_tz[-7.0]", "pvlib/tests/test_location.py::test_location_tz[tz4]", "pvlib/tests/test_location.py::test_location_invalid_tz", "pvlib/tests/test_location.py::test_location_invalid_tz_type", "pvlib/tests/test_location.py::test_location_print_all", "pvlib/tests/test_location.py::test_location_print_pytz", "pvlib/tests/test_location.py::test_get_clearsky", "pvlib/tests/test_location.py::test_get_clearsky_ineichen_supply_linke", "pvlib/tests/test_location.py::test_get_clearsky_haurwitz", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_apparent_elevation", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_dni_extra", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_pressure", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_aod_pw", "pvlib/tests/test_location.py::test_get_clearsky_valueerror", "pvlib/tests/test_location.py::test_from_tmy_2", "pvlib/tests/test_location.py::test_from_epw", "pvlib/tests/test_location.py::test_get_solarposition", "pvlib/tests/test_location.py::test_get_airmass", "pvlib/tests/test_location.py::test_get_airmass_valueerror", "pvlib/tests/test_location.py::test_Location___repr__", "pvlib/tests/test_location.py::test_get_sun_rise_set_transit", "pvlib/tests/test_location.py::test_get_sun_rise_set_transit_valueerror", "pvlib/tests/test_location.py::test_extra_kwargs", "pvlib/tests/test_location.py::test_lookup_altitude", "pvlib/tests/test_soiling.py::test_hsu_no_cleaning", "pvlib/tests/test_soiling.py::test_hsu", "pvlib/tests/test_soiling.py::test_hsu_defaults", "pvlib/tests/test_soiling.py::test_hsu_variable_time_intervals"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1273", "base_commit": "0e6fea6219618c0da944e6ed686c10f5b1e244a2", "patch": "diff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -458,7 +458,9 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n sun_vec = np.array([xp, yp, zp])\n \n # calculate angle-of-incidence on panel\n- aoi = np.degrees(np.arccos(np.abs(np.sum(sun_vec*panel_norm, axis=0))))\n+ # TODO: use irradiance.aoi\n+ projection = np.clip(np.sum(sun_vec*panel_norm, axis=0), -1, 1)\n+ aoi = np.degrees(np.arccos(projection))\n \n # Calculate panel tilt and azimuth in a coordinate system where the panel\n # tilt is the angle from horizontal, and the panel azimuth is the compass\n", "test_patch": "diff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -502,3 +502,18 @@ def test_slope_aware_backtracking():\n np.testing.assert_allclose(\n truetracking['tracker_theta'], expected_data['TrueTracking'],\n rtol=1e-3, atol=1e-3)\n+\n+\n+def test_singleaxis_aoi_gh1221():\n+ # vertical tracker\n+ loc = pvlib.location.Location(40.1134, -88.3695)\n+ dr = pd.date_range(\n+ start='02-Jun-1998 00:00:00', end='02-Jun-1998 23:55:00', freq='5T',\n+ tz='Etc/GMT+6')\n+ sp = loc.get_solarposition(dr)\n+ tr = pvlib.tracking.singleaxis(\n+ sp['apparent_zenith'], sp['azimuth'], axis_tilt=90, axis_azimuth=180,\n+ max_angle=0.001, backtrack=False)\n+ fixed = pvlib.irradiance.aoi(90, 180, sp['apparent_zenith'], sp['azimuth'])\n+ fixed[np.isnan(tr['aoi'])] = np.nan\n+ assert np.allclose(tr['aoi'], fixed, equal_nan=True)\n", "problem_statement": "Incorrect AOI from pvlib.tracking.singleaxis\n`pvlib.tracking.singleaxis` produces an incorrect AOI when the sun is above the earth horizon but behind the module plane.\r\n\r\n**To Reproduce**\r\nModel a fixed tilt system (90 tilt, 180 azimuth) and compare to a vertical single axis tracker with very small rotation limit.\r\n\r\n```\r\n\r\nimport pandas as pd\r\nimport pytz\r\nimport pvlib\r\nfrom matplotlib import pyplot as plt\r\n\r\nloc = pvlib.location.Location(40.1134, -88.3695)\r\n\r\ndr = pd.date_range(start='02-Jun-1998 00:00:00', end='02-Jun-1998 23:55:00',\r\n freq='5T')\r\ntz = pytz.timezone('Etc/GMT+6')\r\ndr = dr.tz_localize(tz)\r\nhr = dr.hour + dr.minute/60\r\n\r\nsp = loc.get_solarposition(dr)\r\n\r\ncs = loc.get_clearsky(dr)\r\n\r\ntr = pvlib.tracking.singleaxis(sp['apparent_zenith'], sp['azimuth'],\r\n axis_tilt=90, axis_azimuth=180, max_angle=0.01,\r\n backtrack=False)\r\n\r\nfixed = pvlib.irradiance.aoi(90, 180, sp['apparent_zenith'], sp['azimuth'])\r\n\r\nplt.plot(hr, fixed)\r\nplt.plot(hr, tr['aoi'])\r\nplt.plot(hr, sp[['apparent_elevation']])\r\nplt.show()\r\n\r\nplt.legend(['aoi - fixed', 'aoi - tracked', 'apparent_elevation'])\r\n```\r\n\r\n**Expected behavior**\r\nThe AOI for the fixed tilt system shows values greater than 90 when the sun is behind the module plane. The AOI from `singleaxis` does not.\r\n\r\nI think the source of the error is the use of `abs` in [this ](https://github.com/pvlib/pvlib-python/blob/ca61503fa83e76631f84fb4237d9e11ae99f3c77/pvlib/tracking.py#L446)line.\r\n\r\n**Screenshots**\r\n\r\n\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.8.1\r\n\r\nFirst reported by email from Jim Wilzcak (NOAA) for the PVlib Matlab function [pvl_singleaxis.m](https://github.com/sandialabs/MATLAB_PV_LIB/blob/master/pvl_singleaxis.m)\r\n\n", "hints_text": "I agree that `abs` looks like a problem.\nThis is an ancient line first committed April 3, 2015:\r\nhttps://github.com/pvlib/pvlib-python/blob/46f69bf9ae2869d75f74664684b4de3b3b3e9bf2/pvlib/tracking.py#L219\nYes, my initial port of the matlab code was as close to 1:1 as I could make it. I don't recall second guessing the `abs` at the time, but I certainly should have.\nWe (Dan and I) concluded that line is in error, in the matlab code.\nShould we just replace that entire line with a call to `irradiance.aoi`?\n@kanderso-nrel the shortcoming with using `irradiance.aoi` afaict is that it calls [`irradiance.aoi_projection`](https://github.com/pvlib/pvlib-python/blob/0e6fea6219618c0da944e6ed686c10f5b1e244a2/pvlib/irradiance.py#L153) which is redundant because the single axis tracker already calculates the solar vector and rotates it into the tracker reference frame to use the `x` and `z` components to calculate the tracker rotation. \r\n\r\nCOINCIDENTALLY, `irradiance.aoi` is already used in the `SingleAzisTracker` method `get_aoi` which afaict should be a static or class method because it NEVER uses self. I guess that's a separate issue. Anyway, it says this method isn't necessary, b/c `singleaxis` already returns AOI.\r\n\r\nALSO, I was thrown for a bit in `irradiance.aoi_projection` which doesn't have a lot of commentary, because when calculating the dot product of surface normal and solar vector, it shows `z=cos(tilt)*cos(ze)` first and `x=sin(tilt)*sin(ze)*cos(az-surfaz)` last. Whatever\r\n\r\nAnyway, back to this, should we consider adjusting `irradiance.aoi` to allow the user to pass in the AOI projection as an alternate parameter? Seems a bit like a hacky workaround, but something like this:\r\n\r\n```python\r\n# in irradiance.py\r\ndef aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\r\n projection=None):\r\n if projection is None:\r\n projection = aoi_projection(\r\n surface_tilt, surface_azimuth, solar_zenith, solar_azimuth)\r\n # from here it's the same\r\n aoi_value = np.rad2deg(np.arccos(projection))\r\n ...\r\n```\r\n\r\nthen in `singleaxis` we change it to this:\r\n\r\n```python\r\n # calculate angle-of-incidence on panel\r\n # aoi = np.degrees(np.arccos(np.abs(np.sum(sun_vec*panel_norm, axis=0))))\r\n projection = (xp * panel_norm[0]\r\n + yp * panel_norm[1]\r\n + zp * panel_norm[2])\r\n # can't use np.dot for 2D matrices\r\n # expanding arrays is about 1.5x faster than sum\r\n # can skip sun_vec array formation, but still need panel norm for later\r\n aoi = irradiance.aoi(None, None, None, None, projection=projection)\r\n```\nor maybe just to get this ball roling we use clip for now and just close it with a #TODO", "created_at": "2021-08-08T05:20:56Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_tracking.py::test_singleaxis_aoi_gh1221"], "PASS_TO_PASS": ["pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_get_irradiance", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_calc_axis_tilt", "pvlib/tests/test_tracking.py::test_slope_aware_backtracking"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1186", "base_commit": "d5d8ffaa9d1201fc943bb0b3e29f7179a65ed995", "patch": "diff --git a/pvlib/iotools/__init__.py b/pvlib/iotools/__init__.py\n--- a/pvlib/iotools/__init__.py\n+++ b/pvlib/iotools/__init__.py\n@@ -13,6 +13,8 @@\n from pvlib.iotools.psm3 import read_psm3 # noqa: F401\n from pvlib.iotools.psm3 import parse_psm3 # noqa: F401\n from pvlib.iotools.pvgis import get_pvgis_tmy, read_pvgis_tmy # noqa: F401\n+from pvlib.iotools.pvgis import read_pvgis_hourly # noqa: F401\n+from pvlib.iotools.pvgis import get_pvgis_hourly # noqa: F401\n from pvlib.iotools.bsrn import read_bsrn # noqa: F401\n from pvlib.iotools.sodapro import get_cams # noqa: F401\n from pvlib.iotools.sodapro import read_cams # noqa: F401\ndiff --git a/pvlib/iotools/pvgis.py b/pvlib/iotools/pvgis.py\n--- a/pvlib/iotools/pvgis.py\n+++ b/pvlib/iotools/pvgis.py\n@@ -23,6 +23,345 @@\n \n URL = 'https://re.jrc.ec.europa.eu/api/'\n \n+# Dictionary mapping PVGIS names to pvlib names\n+PVGIS_VARIABLE_MAP = {\n+ 'G(h)': 'ghi',\n+ 'Gb(n)': 'dni',\n+ 'Gd(h)': 'dhi',\n+ 'G(i)': 'poa_global',\n+ 'Gb(i)': 'poa_direct',\n+ 'Gd(i)': 'poa_sky_diffuse',\n+ 'Gr(i)': 'poa_ground_diffuse',\n+ 'H_sun': 'solar_elevation',\n+ 'T2m': 'temp_air',\n+ 'RH': 'relative_humidity',\n+ 'SP': 'pressure',\n+ 'WS10m': 'wind_speed',\n+ 'WD10m': 'wind_direction',\n+}\n+\n+\n+def get_pvgis_hourly(latitude, longitude, start=None, end=None,\n+ raddatabase=None, components=True,\n+ surface_tilt=0, surface_azimuth=0,\n+ outputformat='json',\n+ usehorizon=True, userhorizon=None,\n+ pvcalculation=False,\n+ peakpower=None, pvtechchoice='crystSi',\n+ mountingplace='free', loss=0, trackingtype=0,\n+ optimal_surface_tilt=False, optimalangles=False,\n+ url=URL, map_variables=True, timeout=30):\n+ \"\"\"Get hourly solar irradiation and modeled PV power output from PVGIS.\n+\n+ PVGIS data is freely available at [1]_.\n+\n+ Parameters\n+ ----------\n+ latitude: float\n+ In decimal degrees, between -90 and 90, north is positive (ISO 19115)\n+ longitude: float\n+ In decimal degrees, between -180 and 180, east is positive (ISO 19115)\n+ start: int or datetime like, default: None\n+ First year of the radiation time series. Defaults to first year\n+ available.\n+ end: int or datetime like, default: None\n+ Last year of the radiation time series. Defaults to last year\n+ available.\n+ raddatabase: str, default: None\n+ Name of radiation database. Options depend on location, see [3]_.\n+ components: bool, default: True\n+ Output solar radiation components (beam, diffuse, and reflected).\n+ Otherwise only global irradiance is returned.\n+ surface_tilt: float, default: 0\n+ Tilt angle from horizontal plane. Ignored for two-axis tracking.\n+ surface_azimuth: float, default: 0\n+ Orientation (azimuth angle) of the (fixed) plane. 0=south, 90=west,\n+ -90: east. Ignored for tracking systems.\n+ usehorizon: bool, default: True\n+ Include effects of horizon\n+ userhorizon: list of float, default: None\n+ Optional user specified elevation of horizon in degrees, at equally\n+ spaced azimuth clockwise from north, only valid if `usehorizon` is\n+ true, if `usehorizon` is true but `userhorizon` is `None` then PVGIS\n+ will calculate the horizon [4]_\n+ pvcalculation: bool, default: False\n+ Return estimate of hourly PV production.\n+ peakpower: float, default: None\n+ Nominal power of PV system in kW. Required if pvcalculation=True.\n+ pvtechchoice: {'crystSi', 'CIS', 'CdTe', 'Unknown'}, default: 'crystSi'\n+ PV technology.\n+ mountingplace: {'free', 'building'}, default: free\n+ Type of mounting for PV system. Options of 'free' for free-standing\n+ and 'building' for building-integrated.\n+ loss: float, default: 0\n+ Sum of PV system losses in percent. Required if pvcalculation=True\n+ trackingtype: {0, 1, 2, 3, 4, 5}, default: 0\n+ Type of suntracking. 0=fixed, 1=single horizontal axis aligned\n+ north-south, 2=two-axis tracking, 3=vertical axis tracking, 4=single\n+ horizontal axis aligned east-west, 5=single inclined axis aligned\n+ north-south.\n+ optimal_surface_tilt: bool, default: False\n+ Calculate the optimum tilt angle. Ignored for two-axis tracking\n+ optimalangles: bool, default: False\n+ Calculate the optimum tilt and azimuth angles. Ignored for two-axis\n+ tracking.\n+ outputformat: str, default: 'json'\n+ Must be in ``['json', 'csv']``. See PVGIS hourly data\n+ documentation [2]_ for more info.\n+ url: str, default: const:`pvlib.iotools.pvgis.URL`\n+ Base url of PVGIS API. ``seriescalc`` is appended to get hourly data\n+ endpoint.\n+ map_variables: bool, default: True\n+ When true, renames columns of the Dataframe to pvlib variable names\n+ where applicable. See variable PVGIS_VARIABLE_MAP.\n+ timeout: int, default: 30\n+ Time in seconds to wait for server response before timeout\n+\n+ Returns\n+ -------\n+ data : pandas.DataFrame\n+ Time-series of hourly data, see Notes for fields\n+ inputs : dict\n+ Dictionary of the request input parameters\n+ metadata : dict\n+ Dictionary containing metadata\n+\n+ Raises\n+ ------\n+ requests.HTTPError\n+ If the request response status is ``HTTP/1.1 400 BAD REQUEST``, then\n+ the error message in the response will be raised as an exception,\n+ otherwise raise whatever ``HTTP/1.1`` error occurred\n+\n+ Hint\n+ ----\n+ PVGIS provides access to a number of different solar radiation datasets,\n+ including satellite-based (SARAH, CMSAF, and NSRDB PSM3) and re-analysis\n+ products (ERA5 and COSMO). Each data source has a different geographical\n+ coverage and time stamp convention, e.g., SARAH and CMSAF provide\n+ instantaneous values, whereas values from ERA5 are averages for the hour.\n+\n+ Notes\n+ -----\n+ data includes the following fields:\n+\n+ =========================== ====== ======================================\n+ raw, mapped Format Description\n+ =========================== ====== ======================================\n+ *Mapped field names are returned when the map_variables argument is True*\n+ ---------------------------------------------------------------------------\n+ P\u2020 float PV system power (W)\n+ G(i), poa_global\u2021 float Global irradiance on inclined plane (W/m^2)\n+ Gb(i), poa_direct\u2021 float Beam (direct) irradiance on inclined plane (W/m^2)\n+ Gd(i), poa_sky_diffuse\u2021 float Diffuse irradiance on inclined plane (W/m^2)\n+ Gr(i), poa_ground_diffuse\u2021 float Reflected irradiance on inclined plane (W/m^2)\n+ H_sun, solar_elevation float Sun height/elevation (degrees)\n+ T2m, temp_air float Air temperature at 2 m (degrees Celsius)\n+ WS10m, wind_speed float Wind speed at 10 m (m/s)\n+ Int int Solar radiation reconstructed (1/0)\n+ =========================== ====== ======================================\n+\n+ \u2020P (PV system power) is only returned when pvcalculation=True.\n+\n+ \u2021Gb(i), Gd(i), and Gr(i) are returned when components=True, otherwise the\n+ sum of the three components, G(i), is returned.\n+\n+ See Also\n+ --------\n+ pvlib.iotools.read_pvgis_hourly, pvlib.iotools.get_pvgis_tmy\n+\n+ References\n+ ----------\n+ .. [1] `PVGIS <https://ec.europa.eu/jrc/en/pvgis>`_\n+ .. [2] `PVGIS Hourly Radiation\n+ <https://ec.europa.eu/jrc/en/PVGIS/tools/hourly-radiation>`_\n+ .. [3] `PVGIS Non-interactive service\n+ <https://ec.europa.eu/jrc/en/PVGIS/docs/noninteractive>`_\n+ .. [4] `PVGIS horizon profile tool\n+ <https://ec.europa.eu/jrc/en/PVGIS/tools/horizon>`_\n+ \"\"\" # noqa: E501\n+ # use requests to format the query string by passing params dictionary\n+ params = {'lat': latitude, 'lon': longitude, 'outputformat': outputformat,\n+ 'angle': surface_tilt, 'aspect': surface_azimuth,\n+ 'pvcalculation': int(pvcalculation),\n+ 'pvtechchoice': pvtechchoice, 'mountingplace': mountingplace,\n+ 'trackingtype': trackingtype, 'components': int(components),\n+ 'usehorizon': int(usehorizon),\n+ 'optimalangles': int(optimalangles),\n+ 'optimalinclination': int(optimalangles), 'loss': loss}\n+ # pvgis only takes 0 for False, and 1 for True, not strings\n+ if userhorizon is not None:\n+ params['userhorizon'] = ','.join(str(x) for x in userhorizon)\n+ if raddatabase is not None:\n+ params['raddatabase'] = raddatabase\n+ if start is not None:\n+ params['startyear'] = start if isinstance(start, int) else start.year\n+ if end is not None:\n+ params['endyear'] = end if isinstance(end, int) else end.year\n+ if peakpower is not None:\n+ params['peakpower'] = peakpower\n+\n+ # The url endpoint for hourly radiation is 'seriescalc'\n+ res = requests.get(url + 'seriescalc', params=params, timeout=timeout)\n+ # PVGIS returns really well formatted error messages in JSON for HTTP/1.1\n+ # 400 BAD REQUEST so try to return that if possible, otherwise raise the\n+ # HTTP/1.1 error caught by requests\n+ if not res.ok:\n+ try:\n+ err_msg = res.json()\n+ except Exception:\n+ res.raise_for_status()\n+ else:\n+ raise requests.HTTPError(err_msg['message'])\n+\n+ return read_pvgis_hourly(io.StringIO(res.text), pvgis_format=outputformat,\n+ map_variables=map_variables)\n+\n+\n+def _parse_pvgis_hourly_json(src, map_variables):\n+ inputs = src['inputs']\n+ metadata = src['meta']\n+ data = pd.DataFrame(src['outputs']['hourly'])\n+ data.index = pd.to_datetime(data['time'], format='%Y%m%d:%H%M', utc=True)\n+ data = data.drop('time', axis=1)\n+ data = data.astype(dtype={'Int': 'int'}) # The 'Int' column to be integer\n+ if map_variables:\n+ data = data.rename(columns=PVGIS_VARIABLE_MAP)\n+ return data, inputs, metadata\n+\n+\n+def _parse_pvgis_hourly_csv(src, map_variables):\n+ # The first 4 rows are latitude, longitude, elevation, radiation database\n+ inputs = {}\n+ # 'Latitude (decimal degrees): 45.000\\r\\n'\n+ inputs['latitude'] = float(src.readline().split(':')[1])\n+ # 'Longitude (decimal degrees): 8.000\\r\\n'\n+ inputs['longitude'] = float(src.readline().split(':')[1])\n+ # Elevation (m): 1389.0\\r\\n\n+ inputs['elevation'] = float(src.readline().split(':')[1])\n+ # 'Radiation database: \\tPVGIS-SARAH\\r\\n'\n+ inputs['radiation_database'] = src.readline().split(':')[1].strip()\n+ # Parse through the remaining metadata section (the number of lines for\n+ # this section depends on the requested parameters)\n+ while True:\n+ line = src.readline()\n+ if line.startswith('time,'): # The data header starts with 'time,'\n+ # The last line of the metadata section contains the column names\n+ names = line.strip().split(',')\n+ break\n+ # Only retrieve metadata from non-empty lines\n+ elif line.strip() != '':\n+ inputs[line.split(':')[0]] = line.split(':')[1].strip()\n+ elif line == '': # If end of file is reached\n+ raise ValueError('No data section was detected. File has probably '\n+ 'been modified since being downloaded from PVGIS')\n+ # Save the entries from the data section to a list, until an empty line is\n+ # reached an empty line. The length of the section depends on the request\n+ data_lines = []\n+ while True:\n+ line = src.readline()\n+ if line.strip() == '':\n+ break\n+ else:\n+ data_lines.append(line.strip().split(','))\n+ data = pd.DataFrame(data_lines, columns=names)\n+ data.index = pd.to_datetime(data['time'], format='%Y%m%d:%H%M', utc=True)\n+ data = data.drop('time', axis=1)\n+ if map_variables:\n+ data = data.rename(columns=PVGIS_VARIABLE_MAP)\n+ # All columns should have the dtype=float, except 'Int' which should be\n+ # integer. It is necessary to convert to float, before converting to int\n+ data = data.astype(float).astype(dtype={'Int': 'int'})\n+ # Generate metadata dictionary containing description of parameters\n+ metadata = {}\n+ for line in src.readlines():\n+ if ':' in line:\n+ metadata[line.split(':')[0]] = line.split(':')[1].strip()\n+ return data, inputs, metadata\n+\n+\n+def read_pvgis_hourly(filename, pvgis_format=None, map_variables=True):\n+ \"\"\"Read a PVGIS hourly file.\n+\n+ Parameters\n+ ----------\n+ filename : str, pathlib.Path, or file-like buffer\n+ Name, path, or buffer of hourly data file downloaded from PVGIS.\n+ pvgis_format : str, default None\n+ Format of PVGIS file or buffer. Equivalent to the ``outputformat``\n+ parameter in the PVGIS API. If `filename` is a file and\n+ `pvgis_format` is ``None`` then the file extension will be used to\n+ determine the PVGIS format to parse. If `filename` is a buffer, then\n+ `pvgis_format` is required and must be in ``['csv', 'json']``.\n+ map_variables: bool, default True\n+ When true, renames columns of the DataFrame to pvlib variable names\n+ where applicable. See variable PVGIS_VARIABLE_MAP.\n+\n+ Returns\n+ -------\n+ data : pandas.DataFrame\n+ the time series data\n+ inputs : dict\n+ the inputs\n+ metadata : dict\n+ metadata\n+\n+ Raises\n+ ------\n+ ValueError\n+ if `pvgis_format` is ``None`` and the file extension is neither\n+ ``.csv`` nor ``.json`` or if `pvgis_format` is provided as\n+ input but isn't in ``['csv', 'json']``\n+ TypeError\n+ if `pvgis_format` is ``None`` and `filename` is a buffer\n+\n+ See Also\n+ --------\n+ get_pvgis_hourly, read_pvgis_tmy\n+ \"\"\"\n+ # get the PVGIS outputformat\n+ if pvgis_format is None:\n+ # get the file extension from suffix, but remove the dot and make sure\n+ # it's lower case to compare with csv, or json\n+ # NOTE: basic format is not supported for PVGIS Hourly as the data\n+ # format does not include a header\n+ # NOTE: raises TypeError if filename is a buffer\n+ outputformat = Path(filename).suffix[1:].lower()\n+ else:\n+ outputformat = pvgis_format\n+\n+ # parse the pvgis file based on the output format, either 'json' or 'csv'\n+ # NOTE: json and csv output formats have parsers defined as private\n+ # functions in this module\n+\n+ # JSON: use Python built-in json module to convert file contents to a\n+ # Python dictionary, and pass the dictionary to the\n+ # _parse_pvgis_hourly_json() function from this module\n+ if outputformat == 'json':\n+ try:\n+ src = json.load(filename)\n+ except AttributeError: # str/path has no .read() attribute\n+ with open(str(filename), 'r') as fbuf:\n+ src = json.load(fbuf)\n+ return _parse_pvgis_hourly_json(src, map_variables=map_variables)\n+\n+ # CSV: use _parse_pvgis_hourly_csv()\n+ if outputformat == 'csv':\n+ try:\n+ pvgis_data = _parse_pvgis_hourly_csv(\n+ filename, map_variables=map_variables)\n+ except AttributeError: # str/path has no .read() attribute\n+ with open(str(filename), 'r') as fbuf:\n+ pvgis_data = _parse_pvgis_hourly_csv(\n+ fbuf, map_variables=map_variables)\n+ return pvgis_data\n+\n+ # raise exception if pvgis format isn't in ['csv', 'json']\n+ err_msg = (\n+ \"pvgis format '{:s}' was unknown, must be either 'json' or 'csv'\")\\\n+ .format(outputformat)\n+ raise ValueError(err_msg)\n+\n \n def get_pvgis_tmy(lat, lon, outputformat='json', usehorizon=True,\n userhorizon=None, startyear=None, endyear=None, url=URL,\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_pvgis.py b/pvlib/tests/iotools/test_pvgis.py\n--- a/pvlib/tests/iotools/test_pvgis.py\n+++ b/pvlib/tests/iotools/test_pvgis.py\n@@ -4,12 +4,301 @@\n import json\n import numpy as np\n import pandas as pd\n+import io\n import pytest\n import requests\n from pvlib.iotools import get_pvgis_tmy, read_pvgis_tmy\n-from ..conftest import DATA_DIR, RERUNS, RERUNS_DELAY\n+from pvlib.iotools import get_pvgis_hourly, read_pvgis_hourly\n+from ..conftest import DATA_DIR, RERUNS, RERUNS_DELAY, assert_frame_equal\n+\n+\n+# PVGIS Hourly tests\n+# The test files are actual files from PVGIS where the data section have been\n+# reduced to only a few lines\n+testfile_radiation_csv = DATA_DIR / \\\n+ 'pvgis_hourly_Timeseries_45.000_8.000_SA_30deg_0deg_2016_2016.csv'\n+testfile_pv_json = DATA_DIR / \\\n+ 'pvgis_hourly_Timeseries_45.000_8.000_CM_10kWp_CIS_5_2a_2013_2014.json'\n+\n+index_radiation_csv = \\\n+ pd.date_range('20160101 00:10', freq='1h', periods=14, tz='UTC')\n+index_pv_json = \\\n+ pd.date_range('2013-01-01 00:55', freq='1h', periods=10, tz='UTC')\n+\n+columns_radiation_csv = [\n+ 'Gb(i)', 'Gd(i)', 'Gr(i)', 'H_sun', 'T2m', 'WS10m', 'Int']\n+columns_radiation_csv_mapped = [\n+ 'poa_direct', 'poa_sky_diffuse', 'poa_ground_diffuse', 'solar_elevation',\n+ 'temp_air', 'wind_speed', 'Int']\n+columns_pv_json = [\n+ 'P', 'Gb(i)', 'Gd(i)', 'Gr(i)', 'H_sun', 'T2m', 'WS10m', 'Int']\n+columns_pv_json_mapped = [\n+ 'P', 'poa_direct', 'poa_sky_diffuse', 'poa_ground_diffuse',\n+ 'solar_elevation', 'temp_air', 'wind_speed', 'Int']\n+\n+data_radiation_csv = [\n+ [0.0, 0.0, 0.0, 0.0, 3.44, 1.43, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 2.94, 1.47, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 2.43, 1.51, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 1.93, 1.54, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 2.03, 1.62, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 2.14, 1.69, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 2.25, 1.77, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 3.06, 1.49, 0.0],\n+ [26.71, 8.28, 0.21, 8.06, 3.87, 1.22, 1.0],\n+ [14.69, 5.76, 0.16, 14.8, 4.67, 0.95, 1.0],\n+ [2.19, 0.94, 0.03, 19.54, 5.73, 0.77, 1.0],\n+ [2.11, 0.94, 0.03, 21.82, 6.79, 0.58, 1.0],\n+ [4.25, 1.88, 0.05, 21.41, 7.84, 0.4, 1.0],\n+ [0.0, 0.0, 0.0, 0.0, 7.43, 0.72, 0.0]]\n+data_pv_json = [\n+ [0.0, 0.0, 0.0, 0.0, 0.0, 3.01, 1.23, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 0.0, 2.22, 1.46, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 0.0, 1.43, 1.7, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.64, 1.93, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.77, 1.8, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.91, 1.66, 0.0],\n+ [0.0, 0.0, 0.0, 0.0, 0.0, 1.05, 1.53, 0.0],\n+ [3464.5, 270.35, 91.27, 6.09, 6.12, 1.92, 1.44, 0.0],\n+ [1586.9, 80.76, 83.95, 9.04, 13.28, 2.79, 1.36, 0.0],\n+ [713.3, 5.18, 70.57, 7.31, 18.56, 3.66, 1.27, 0.0]]\n+\n+inputs_radiation_csv = {'latitude': 45.0, 'longitude': 8.0, 'elevation': 250.0,\n+ 'radiation_database': 'PVGIS-SARAH',\n+ 'Slope': '30 deg.', 'Azimuth': '0 deg.'}\n+\n+metadata_radiation_csv = {\n+ 'Gb(i)': 'Beam (direct) irradiance on the inclined plane (plane of the array) (W/m2)', # noqa: E501\n+ 'Gd(i)': 'Diffuse irradiance on the inclined plane (plane of the array) (W/m2)', # noqa: E501\n+ 'Gr(i)': 'Reflected irradiance on the inclined plane (plane of the array) (W/m2)', # noqa: E501\n+ 'H_sun': 'Sun height (degree)',\n+ 'T2m': '2-m air temperature (degree Celsius)',\n+ 'WS10m': '10-m total wind speed (m/s)',\n+ 'Int': '1 means solar radiation values are reconstructed'}\n+\n+inputs_pv_json = {\n+ 'location': {'latitude': 45.0, 'longitude': 8.0, 'elevation': 250.0},\n+ 'meteo_data': {'radiation_db': 'PVGIS-CMSAF', 'meteo_db': 'ERA-Interim',\n+ 'year_min': 2013, 'year_max': 2014, 'use_horizon': True,\n+ 'horizon_db': None, 'horizon_data': 'DEM-calculated'},\n+ 'mounting_system': {'two_axis': {\n+ 'slope': {'value': '-', 'optimal': '-'},\n+ 'azimuth': {'value': '-', 'optimal': '-'}}},\n+ 'pv_module': {'technology': 'CIS', 'peak_power': 10.0, 'system_loss': 5.0}}\n+\n+metadata_pv_json = {\n+ 'inputs': {\n+ 'location': {'description': 'Selected location', 'variables': {\n+ 'latitude': {'description': 'Latitude', 'units': 'decimal degree'},\n+ 'longitude': {'description': 'Longitude', 'units': 'decimal degree'}, # noqa: E501\n+ 'elevation': {'description': 'Elevation', 'units': 'm'}}},\n+ 'meteo_data': {\n+ 'description': 'Sources of meteorological data',\n+ 'variables': {\n+ 'radiation_db': {'description': 'Solar radiation database'},\n+ 'meteo_db': {'description': 'Database used for meteorological variables other than solar radiation'}, # noqa: E501\n+ 'year_min': {'description': 'First year of the calculations'},\n+ 'year_max': {'description': 'Last year of the calculations'},\n+ 'use_horizon': {'description': 'Include horizon shadows'},\n+ 'horizon_db': {'description': 'Source of horizon data'}}},\n+ 'mounting_system': {\n+ 'description': 'Mounting system',\n+ 'choices': 'fixed, vertical_axis, inclined_axis, two_axis',\n+ 'fields': {\n+ 'slope': {'description': 'Inclination angle from the horizontal plane', 'units': 'degree'}, # noqa: E501\n+ 'azimuth': {'description': 'Orientation (azimuth) angle of the (fixed) PV system (0 = S, 90 = W, -90 = E)', 'units': 'degree'}}}, # noqa: E501\n+ 'pv_module': {\n+ 'description': 'PV module parameters',\n+ 'variables': {\n+ 'technology': {'description': 'PV technology'},\n+ 'peak_power': {'description': 'Nominal (peak) power of the PV module', 'units': 'kW'}, # noqa: E501\n+ 'system_loss': {'description': 'Sum of system losses', 'units': '%'}}}}, # noqa: E501\n+ 'outputs': {\n+ 'hourly': {\n+ 'type': 'time series', 'timestamp': 'hourly averages',\n+ 'variables': {\n+ 'P': {'description': 'PV system power', 'units': 'W'},\n+ 'Gb(i)': {'description': 'Beam (direct) irradiance on the inclined plane (plane of the array)', 'units': 'W/m2'}, # noqa: E501\n+ 'Gd(i)': {'description': 'Diffuse irradiance on the inclined plane (plane of the array)', 'units': 'W/m2'}, # noqa: E501\n+ 'Gr(i)': {'description': 'Reflected irradiance on the inclined plane (plane of the array)', 'units': 'W/m2'}, # noqa: E501\n+ 'H_sun': {'description': 'Sun height', 'units': 'degree'},\n+ 'T2m': {'description': '2-m air temperature', 'units': 'degree Celsius'}, # noqa: E501\n+ 'WS10m': {'description': '10-m total wind speed', 'units': 'm/s'}, # noqa: E501\n+ 'Int': {'description': '1 means solar radiation values are reconstructed'}}}}} # noqa: E501\n+\n+\n+def generate_expected_dataframe(values, columns, index):\n+ \"\"\"Create dataframe from arrays of values, columns and index, in order to\n+ use this dataframe to compare to.\n+ \"\"\"\n+ expected = pd.DataFrame(index=index, data=values, columns=columns)\n+ expected['Int'] = expected['Int'].astype(int)\n+ expected.index.name = 'time'\n+ expected.index.freq = None\n+ return expected\n+\n+\[email protected]\n+def expected_radiation_csv():\n+ expected = generate_expected_dataframe(\n+ data_radiation_csv, columns_radiation_csv, index_radiation_csv)\n+ return expected\n+\n+\[email protected]\n+def expected_radiation_csv_mapped():\n+ expected = generate_expected_dataframe(\n+ data_radiation_csv, columns_radiation_csv_mapped, index_radiation_csv)\n+ return expected\n \n \[email protected]\n+def expected_pv_json():\n+ expected = generate_expected_dataframe(\n+ data_pv_json, columns_pv_json, index_pv_json)\n+ return expected\n+\n+\[email protected]\n+def expected_pv_json_mapped():\n+ expected = generate_expected_dataframe(\n+ data_pv_json, columns_pv_json_mapped, index_pv_json)\n+ return expected\n+\n+\n+# Test read_pvgis_hourly function using two different files with different\n+# input arguments (to test variable mapping and pvgis_format)\n+# pytest request.getfixturevalue is used to simplify the input arguments\[email protected]('testfile,expected_name,metadata_exp,inputs_exp,map_variables,pvgis_format', [ # noqa: E501\n+ (testfile_radiation_csv, 'expected_radiation_csv', metadata_radiation_csv,\n+ inputs_radiation_csv, False, None),\n+ (testfile_radiation_csv, 'expected_radiation_csv_mapped',\n+ metadata_radiation_csv, inputs_radiation_csv, True, 'csv'),\n+ (testfile_pv_json, 'expected_pv_json', metadata_pv_json, inputs_pv_json,\n+ False, None),\n+ (testfile_pv_json, 'expected_pv_json_mapped', metadata_pv_json,\n+ inputs_pv_json, True, 'json')])\n+def test_read_pvgis_hourly(testfile, expected_name, metadata_exp,\n+ inputs_exp, map_variables, pvgis_format, request):\n+ # Get expected dataframe from fixture\n+ expected = request.getfixturevalue(expected_name)\n+ # Read data from file\n+ out, inputs, metadata = read_pvgis_hourly(\n+ testfile, map_variables=map_variables, pvgis_format=pvgis_format)\n+ # Assert whether dataframe, metadata, and inputs are as expected\n+ assert_frame_equal(out, expected)\n+ assert inputs == inputs_exp\n+ assert metadata == metadata_exp\n+\n+\n+def test_read_pvgis_hourly_bad_extension():\n+ # Test if ValueError is raised if file extension cannot be recognized and\n+ # pvgis_format is not specified\n+ with pytest.raises(ValueError, match=\"pvgis format 'txt' was unknown\"):\n+ read_pvgis_hourly('filename.txt')\n+ # Test if ValueError is raised if an unkonwn pvgis_format is specified\n+ with pytest.raises(ValueError, match=\"pvgis format 'txt' was unknown\"):\n+ read_pvgis_hourly(testfile_pv_json, pvgis_format='txt')\n+ # Test if TypeError is raised if input is a buffer and pvgis_format=None\n+ with pytest.raises(TypeError, match=\"expected str, bytes or os.PathLike\"):\n+ read_pvgis_hourly(io.StringIO())\n+\n+\n+args_radiation_csv = {\n+ 'surface_tilt': 30, 'surface_azimuth': 0, 'outputformat': 'csv',\n+ 'usehorizon': False, 'userhorizon': None, 'raddatabase': 'PVGIS-SARAH',\n+ 'start': 2016, 'end': 2016, 'pvcalculation': False, 'components': True}\n+\n+url_hourly_radiation_csv = 'https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=csv&angle=30&aspect=0&usehorizon=0&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&raddatabase=PVGIS-SARAH&startyear=2016&endyear=2016' # noqa: E501\n+\n+args_pv_json = {\n+ 'surface_tilt': 30, 'surface_azimuth': 0, 'outputformat': 'json',\n+ 'usehorizon': True, 'userhorizon': None, 'raddatabase': 'PVGIS-CMSAF',\n+ 'start': pd.Timestamp(2013, 1, 1), 'end': pd.Timestamp(2014, 5, 1),\n+ 'pvcalculation': True, 'peakpower': 10, 'pvtechchoice': 'CIS', 'loss': 5,\n+ 'trackingtype': 2, 'optimalangles': True, 'components': True}\n+\n+url_pv_json = 'https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=json&angle=30&aspect=0&pvtechchoice=CIS&mountingplace=free&trackingtype=2&components=1&usehorizon=1&raddatabase=PVGIS-CMSAF&startyear=2013&endyear=2014&pvcalculation=1&peakpower=10&loss=5&optimalangles=1' # noqa: E501\n+\n+\[email protected]('testfile,expected_name,args,map_variables,url_test', [ # noqa: E501\n+ (testfile_radiation_csv, 'expected_radiation_csv',\n+ args_radiation_csv, False, url_hourly_radiation_csv),\n+ (testfile_radiation_csv, 'expected_radiation_csv_mapped',\n+ args_radiation_csv, True, url_hourly_radiation_csv),\n+ (testfile_pv_json, 'expected_pv_json', args_pv_json, False, url_pv_json),\n+ (testfile_pv_json, 'expected_pv_json_mapped', args_pv_json, True,\n+ url_pv_json)])\n+def test_get_pvgis_hourly(requests_mock, testfile, expected_name, args,\n+ map_variables, url_test, request):\n+ \"\"\"Test that get_pvgis_hourly generates the correct URI request and that\n+ _parse_pvgis_hourly_json and _parse_pvgis_hourly_csv is called correctly\"\"\"\n+ # Open local test file containing McClear monthly data\n+ with open(testfile, 'r') as test_file:\n+ mock_response = test_file.read()\n+ # Specify the full URI of a specific example, this ensures that all of the\n+ # inputs are passing on correctly\n+ requests_mock.get(url_test, text=mock_response)\n+ # Make API call - an error is raised if requested URI does not match\n+ out, inputs, metadata = get_pvgis_hourly(\n+ latitude=45, longitude=8, map_variables=map_variables, **args)\n+ # Get expected dataframe from fixture\n+ expected = request.getfixturevalue(expected_name)\n+ # Compare out and expected dataframes\n+ assert_frame_equal(out, expected)\n+\n+\n+def test_get_pvgis_hourly_bad_status_code(requests_mock):\n+ # Test if a HTTPError is raised if a bad request is returned\n+ requests_mock.get(url_pv_json, status_code=400)\n+ with pytest.raises(requests.HTTPError):\n+ get_pvgis_hourly(latitude=45, longitude=8, **args_pv_json)\n+ # Test if HTTPError is raised and error message is returned if avaiable\n+ requests_mock.get(url_pv_json, status_code=400,\n+ json={'message': 'peakpower Mandatory'})\n+ with pytest.raises(requests.HTTPError):\n+ get_pvgis_hourly(latitude=45, longitude=8, **args_pv_json)\n+\n+\n+url_bad_outputformat = 'https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=basic&angle=0&aspect=0&pvcalculation=0&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&usehorizon=1&optimalangles=0&optimalinclination=0&loss=0' # noqa: E501\n+\n+\n+def test_get_pvgis_hourly_bad_outputformat(requests_mock):\n+ # Test if a ValueError is raised if an unsupported outputformat is used\n+ # E.g. 'basic' is a valid PVGIS format, but is not supported by pvlib\n+ requests_mock.get(url_bad_outputformat)\n+ with pytest.raises(ValueError):\n+ get_pvgis_hourly(latitude=45, longitude=8, outputformat='basic')\n+\n+\n+url_additional_inputs = 'https://re.jrc.ec.europa.eu/api/seriescalc?lat=55.6814&lon=12.5758&outputformat=csv&angle=0&aspect=0&pvcalculation=1&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&usehorizon=1&optimalangles=1&optimalinclination=1&loss=2&userhorizon=10%2C15%2C20%2C10&peakpower=5' # noqa: E501\n+\n+\n+def test_get_pvgis_hourly_additional_inputs(requests_mock):\n+ # Test additional inputs, including userhorizons\n+ # Necessary to pass a test file in order for the parser not to fail\n+ with open(testfile_radiation_csv, 'r') as test_file:\n+ mock_response = test_file.read()\n+ requests_mock.get(url_additional_inputs, text=mock_response)\n+ # Make request with userhorizon specified\n+ # Test passes if the request made by get_pvgis_hourly matches exactly the\n+ # url passed to the mock request (url_additional_inputs)\n+ get_pvgis_hourly(\n+ latitude=55.6814, longitude=12.5758, outputformat='csv',\n+ usehorizon=True, userhorizon=[10, 15, 20, 10], pvcalculation=True,\n+ peakpower=5, loss=2, trackingtype=0, components=True,\n+ optimalangles=True)\n+\n+\n+def test_read_pvgis_hourly_empty_file():\n+ # Check if a IOError is raised if file does not contain a data section\n+ with pytest.raises(ValueError, match='No data section'):\n+ read_pvgis_hourly(\n+ io.StringIO('1:1\\n2:2\\n3:3\\n4:4\\n5:5\\n'),\n+ pvgis_format='csv')\n+\n+\n+# PVGIS TMY tests\n @pytest.fixture\n def expected():\n return pd.read_csv(DATA_DIR / 'pvgis_tmy_test.dat', index_col='time(UTC)')\n", "problem_statement": "getter/parser for PVGIS hourly-radiation\n**Is your feature request related to a problem? Please describe.**\r\nRelated to #845 \r\n\r\n**Describe the solution you'd like**\r\nSimilar to `get_pvgis_tmy` retrieve pvgis hourly radiation data from their api\r\n\r\n**Describe alternatives you've considered**\r\nPvgis is becoming a popular resource more and more people are asking me for it, it is nice because it is a global collection of several different radiation databases including nsrdb and others, and different from cams, the data is complete, ie it has air temperature, wind speed as well as all 3 components of irradiance\r\n\r\n**Additional context**\r\nThis would be part of the `iotool` sub-package. There's already a `pvgis.py` module with a getter for tmy be data\n", "hints_text": "", "created_at": "2021-03-07T19:00:48Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly_bad_extension", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_bad_status_code", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_bad_outputformat", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly_empty_file", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_json", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_epw", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_csv", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_basic", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_exception"], "PASS_TO_PASS": [], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1822", "base_commit": "d2fbfb247979282ba1fba6794dec451c0b1e8d57", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -2652,28 +2652,19 @@ def v_from_i(current, photocurrent, saturation_current, resistance_series,\n parameters of real solar cells using Lambert W-function\", Solar\n Energy Materials and Solar Cells, 81 (2004) 269-277.\n '''\n+ args = (current, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth)\n if method.lower() == 'lambertw':\n- return _singlediode._lambertw_v_from_i(\n- current, photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth\n- )\n+ return _singlediode._lambertw_v_from_i(*args)\n else:\n # Calculate points on the IV curve using either 'newton' or 'brentq'\n # methods. Voltages are determined by first solving the single diode\n # equation for the diode voltage V_d then backing out voltage\n- args = (current, photocurrent, saturation_current,\n- resistance_series, resistance_shunt, nNsVth)\n V = _singlediode.bishop88_v_from_i(*args, method=method.lower())\n- # find the right size and shape for returns\n- size, shape = _singlediode._get_size_and_shape(args)\n- if size <= 1:\n- if shape is not None:\n- V = np.tile(V, shape)\n- if np.isnan(V).any() and size <= 1:\n- V = np.repeat(V, size)\n- if shape is not None:\n- V = V.reshape(shape)\n- return V\n+ if all(map(np.isscalar, args)):\n+ return V\n+ shape = _singlediode._shape_of_max_size(*args)\n+ return np.broadcast_to(V, shape)\n \n \n def i_from_v(voltage, photocurrent, saturation_current, resistance_series,\n@@ -2743,28 +2734,19 @@ def i_from_v(voltage, photocurrent, saturation_current, resistance_series,\n parameters of real solar cells using Lambert W-function\", Solar\n Energy Materials and Solar Cells, 81 (2004) 269-277.\n '''\n+ args = (voltage, photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth)\n if method.lower() == 'lambertw':\n- return _singlediode._lambertw_i_from_v(\n- voltage, photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth\n- )\n+ return _singlediode._lambertw_i_from_v(*args)\n else:\n # Calculate points on the IV curve using either 'newton' or 'brentq'\n # methods. Voltages are determined by first solving the single diode\n # equation for the diode voltage V_d then backing out voltage\n- args = (voltage, photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth)\n current = _singlediode.bishop88_i_from_v(*args, method=method.lower())\n- # find the right size and shape for returns\n- size, shape = _singlediode._get_size_and_shape(args)\n- if size <= 1:\n- if shape is not None:\n- current = np.tile(current, shape)\n- if np.isnan(current).any() and size <= 1:\n- current = np.repeat(current, size)\n- if shape is not None:\n- current = current.reshape(shape)\n- return current\n+ if all(map(np.isscalar, args)):\n+ return current\n+ shape = _singlediode._shape_of_max_size(*args)\n+ return np.broadcast_to(current, shape)\n \n \n def scale_voltage_current_power(data, voltage=1, current=1):\ndiff --git a/pvlib/singlediode.py b/pvlib/singlediode.py\n--- a/pvlib/singlediode.py\n+++ b/pvlib/singlediode.py\n@@ -287,8 +287,8 @@ def bishop88_i_from_v(voltage, photocurrent, saturation_current,\n ... method_kwargs={'full_output': True})\n \"\"\"\n # collect args\n- args = (photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth, d2mutau, NsVbi,\n+ args = (photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth, d2mutau, NsVbi,\n breakdown_factor, breakdown_voltage, breakdown_exp)\n method = method.lower()\n \n@@ -319,14 +319,11 @@ def vd_from_brent(voc, v, iph, isat, rs, rsh, gamma, d2mutau, NsVbi,\n vd_from_brent_vectorized = np.vectorize(vd_from_brent)\n vd = vd_from_brent_vectorized(voc_est, voltage, *args)\n elif method == 'newton':\n- # make sure all args are numpy arrays if max size > 1\n- # if voltage is an array, then make a copy to use for initial guess, v0\n- args, v0, method_kwargs = \\\n- _prepare_newton_inputs((voltage,), args, voltage, method_kwargs)\n- vd = newton(func=lambda x, *a: fv(x, voltage, *a), x0=v0,\n+ x0, (voltage, *args), method_kwargs = \\\n+ _prepare_newton_inputs(voltage, (voltage, *args), method_kwargs)\n+ vd = newton(func=lambda x, *a: fv(x, voltage, *a), x0=x0,\n fprime=lambda x, *a: bishop88(x, *a, gradients=True)[4],\n- args=args,\n- **method_kwargs)\n+ args=args, **method_kwargs)\n else:\n raise NotImplementedError(\"Method '%s' isn't implemented\" % method)\n \n@@ -422,9 +419,9 @@ def bishop88_v_from_i(current, photocurrent, saturation_current,\n ... method_kwargs={'full_output': True})\n \"\"\"\n # collect args\n- args = (photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth, d2mutau, NsVbi, breakdown_factor,\n- breakdown_voltage, breakdown_exp)\n+ args = (photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth, d2mutau, NsVbi,\n+ breakdown_factor, breakdown_voltage, breakdown_exp)\n method = method.lower()\n \n # method_kwargs create dict if not provided\n@@ -454,14 +451,11 @@ def vd_from_brent(voc, i, iph, isat, rs, rsh, gamma, d2mutau, NsVbi,\n vd_from_brent_vectorized = np.vectorize(vd_from_brent)\n vd = vd_from_brent_vectorized(voc_est, current, *args)\n elif method == 'newton':\n- # make sure all args are numpy arrays if max size > 1\n- # if voc_est is an array, then make a copy to use for initial guess, v0\n- args, v0, method_kwargs = \\\n- _prepare_newton_inputs((current,), args, voc_est, method_kwargs)\n- vd = newton(func=lambda x, *a: fi(x, current, *a), x0=v0,\n+ x0, (current, *args), method_kwargs = \\\n+ _prepare_newton_inputs(voc_est, (current, *args), method_kwargs)\n+ vd = newton(func=lambda x, *a: fi(x, current, *a), x0=x0,\n fprime=lambda x, *a: bishop88(x, *a, gradients=True)[3],\n- args=args,\n- **method_kwargs)\n+ args=args, **method_kwargs)\n else:\n raise NotImplementedError(\"Method '%s' isn't implemented\" % method)\n \n@@ -555,9 +549,9 @@ def bishop88_mpp(photocurrent, saturation_current, resistance_series,\n ... method='newton', method_kwargs={'full_output': True})\n \"\"\"\n # collect args\n- args = (photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth, d2mutau, NsVbi, breakdown_factor,\n- breakdown_voltage, breakdown_exp)\n+ args = (photocurrent, saturation_current,\n+ resistance_series, resistance_shunt, nNsVth, d2mutau, NsVbi,\n+ breakdown_factor, breakdown_voltage, breakdown_exp)\n method = method.lower()\n \n # method_kwargs create dict if not provided\n@@ -584,12 +578,11 @@ def fmpp(x, *a):\n elif method == 'newton':\n # make sure all args are numpy arrays if max size > 1\n # if voc_est is an array, then make a copy to use for initial guess, v0\n- args, v0, method_kwargs = \\\n- _prepare_newton_inputs((), args, voc_est, method_kwargs)\n- vd = newton(\n- func=fmpp, x0=v0,\n- fprime=lambda x, *a: bishop88(x, *a, gradients=True)[7], args=args,\n- **method_kwargs)\n+ x0, args, method_kwargs = \\\n+ _prepare_newton_inputs(voc_est, args, method_kwargs)\n+ vd = newton(func=fmpp, x0=x0,\n+ fprime=lambda x, *a: bishop88(x, *a, gradients=True)[7],\n+ args=args, **method_kwargs)\n else:\n raise NotImplementedError(\"Method '%s' isn't implemented\" % method)\n \n@@ -603,46 +596,42 @@ def fmpp(x, *a):\n return bishop88(vd, *args)\n \n \n-def _get_size_and_shape(args):\n- # find the right size and shape for returns\n- size, shape = 0, None # 0 or None both mean scalar\n- for arg in args:\n- try:\n- this_shape = arg.shape # try to get shape\n- except AttributeError:\n- this_shape = None\n- try:\n- this_size = len(arg) # try to get the size\n- except TypeError:\n- this_size = 0\n- else:\n- this_size = arg.size # if it has shape then it also has size\n- if shape is None:\n- shape = this_shape # set the shape if None\n- # update size and shape\n- if this_size > size:\n- size = this_size\n- if this_shape is not None:\n- shape = this_shape\n- return size, shape\n-\n-\n-def _prepare_newton_inputs(i_or_v_tup, args, v0, method_kwargs):\n- # broadcast arguments for newton method\n- # the first argument should be a tuple, eg: (i,), (v,) or ()\n- size, shape = _get_size_and_shape(i_or_v_tup + args)\n- if size > 1:\n- args = [np.asarray(arg) for arg in args]\n- # newton uses initial guess for the output shape\n- # copy v0 to a new array and broadcast it to the shape of max size\n- if shape is not None:\n- v0 = np.broadcast_to(v0, shape).copy()\n+def _shape_of_max_size(*args):\n+ return max(((np.size(a), np.shape(a)) for a in args),\n+ key=lambda t: t[0])[1]\n+\n+\n+def _prepare_newton_inputs(x0, args, method_kwargs):\n+ \"\"\"\n+ Make inputs compatible with Scipy's newton by:\n+ - converting all arugments (`x0` and `args`) into numpy.ndarrays if any\n+ argument is not a scalar.\n+ - broadcasting the initial guess `x0` to the shape of the argument with\n+ the greatest size.\n+\n+ Parameters\n+ ----------\n+ x0: numeric\n+ Initial guess for newton.\n+ args: Iterable(numeric)\n+ Iterable of additional arguments to use in SciPy's newton.\n+ method_kwargs: dict\n+ Options to pass to newton.\n+\n+ Returns\n+ -------\n+ tuple\n+ The updated initial guess, arguments, and options for newton.\n+ \"\"\"\n+ if not (np.isscalar(x0) and all(map(np.isscalar, args))):\n+ args = tuple(map(np.asarray, args))\n+ x0 = np.broadcast_to(x0, _shape_of_max_size(x0, *args))\n \n # set abs tolerance and maxiter from method_kwargs if not provided\n # apply defaults, but giving priority to user-specified values\n method_kwargs = {**NEWTON_DEFAULT_PARAMS, **method_kwargs}\n \n- return args, v0, method_kwargs\n+ return x0, args, method_kwargs\n \n \n def _lambertw_v_from_i(current, photocurrent, saturation_current,\n", "test_patch": "diff --git a/pvlib/tests/test_singlediode.py b/pvlib/tests/test_singlediode.py\n--- a/pvlib/tests/test_singlediode.py\n+++ b/pvlib/tests/test_singlediode.py\n@@ -557,3 +557,14 @@ def test_bishop88_full_output_kwarg(method, bishop88_arguments):\n assert isinstance(ret_val[1], tuple) # second is output from optimizer\n # any root finder returns at least 2 elements with full_output=True\n assert len(ret_val[1]) >= 2\n+\n+\[email protected]('method', ['newton', 'brentq'])\n+def test_bishop88_pdSeries_len_one(method, bishop88_arguments):\n+ for k, v in bishop88_arguments.items():\n+ bishop88_arguments[k] = pd.Series([v])\n+\n+ # should not raise error\n+ bishop88_i_from_v(pd.Series([0]), **bishop88_arguments, method=method)\n+ bishop88_v_from_i(pd.Series([0]), **bishop88_arguments, method=method)\n+ bishop88_mpp(**bishop88_arguments, method=method)\n", "problem_statement": "singlediode: newton solver fails with Series input of length one\nThe vectorized newton solver doesn't work if parameters are Series of length one.\r\n\r\n```\r\n\r\nimport pandas as pd\r\nimport pvlib\r\n\r\n\r\nargs = (0.001, 1.5, 6., 5e-9, 1000., 0.5)\r\nparams = pvlib.pvsystem.calcparams_desoto(1000., 25, *args)\r\nparams_series = pvlib.pvsystem.calcparams_desoto(pd.Series(data=[1000.]),\r\n pd.Series([25.]), *args)\r\nparams_series2 = pvlib.pvsystem.calcparams_desoto(pd.Series(data=[1000., 1000.]),\r\n pd.Series([25., 25.]), *args)\r\n# works with each input as float\r\nresult = pvlib.pvsystem.singlediode(*params, method='newton')\r\n\r\n# works with Series if length > 1\r\nresult_series2 = pvlib.pvsystem.singlediode(*params_series2, method='newton')\r\n\r\n# errors with Series if length is 1\r\nresult_series = pvlib.pvsystem.singlediode(*params_series, method='newton')\r\n```\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.9.5\r\n\n", "hints_text": "", "created_at": "2023-08-01T22:56:22Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_singlediode.py::test_bishop88_pdSeries_len_one[newton]"], "PASS_TO_PASS": ["pvlib/tests/test_singlediode.py::test_method_spr_e20_327[brentq]", "pvlib/tests/test_singlediode.py::test_method_spr_e20_327[newton]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[brentq]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_singlediode_lambert_negative_voc", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params1-recomb_params1-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params1-recomb_params1-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_transfer[newton-method_kwargs0]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_transfer[brentq-method_kwargs1]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_fails[newton-method_kwargs0]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_fails[brentq-method_kwargs1]", "pvlib/tests/test_singlediode.py::test_bishop88_full_output_kwarg[newton]", "pvlib/tests/test_singlediode.py::test_bishop88_full_output_kwarg[brentq]", "pvlib/tests/test_singlediode.py::test_bishop88_pdSeries_len_one[brentq]"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1165", "base_commit": "b40df75ddbc467a113b87643c1faef073cc37b3e", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -1572,11 +1572,13 @@ def _prepare_temperature(self, data=None):\n \"\"\"\n poa = _irrad_for_celltemp(self.results.total_irrad,\n self.results.effective_irradiance)\n- if not isinstance(data, tuple) and self.system.num_arrays > 1:\n+ # handle simple case first, single array, data not iterable\n+ if not isinstance(data, tuple) and self.system.num_arrays == 1:\n+ return self._prepare_temperature_single_array(data, poa)\n+ if not isinstance(data, tuple):\n # broadcast data to all arrays\n data = (data,) * self.system.num_arrays\n- elif not isinstance(data, tuple):\n- return self._prepare_temperature_single_array(data, poa)\n+ # find where cell or module temperature is specified in input data\n given_cell_temperature = tuple(itertools.starmap(\n self._get_cell_temperature,\n zip(data, poa, self.system.temperature_model_parameters)\n@@ -1587,23 +1589,7 @@ def _prepare_temperature(self, data=None):\n self.results.cell_temperature = given_cell_temperature\n return self\n # Calculate cell temperature from weather data. If cell_temperature\n- # has not been provided for some arrays then it is computed with\n- # ModelChain.temperature_model(). Because this operates on all Arrays\n- # simultaneously, 'poa_global' must be known for all arrays, including\n- # those that have a known cell temperature.\n- try:\n- self._verify_df(self.results.total_irrad, ['poa_global'])\n- except ValueError:\n- # Provide a more informative error message. Because only\n- # run_model_from_effective_irradiance() can get to this point\n- # without known POA we can suggest a very specific remedy in the\n- # error message.\n- raise ValueError(\"Incomplete input data. Data must contain \"\n- \"'poa_global'. For systems with multiple Arrays \"\n- \"if you have provided 'cell_temperature' for \"\n- \"only a subset of Arrays you must provide \"\n- \"'poa_global' for all Arrays, including those \"\n- \"that have a known 'cell_temperature'.\")\n+ # has not been provided for some arrays then it is computed.\n self.temperature_model()\n # replace calculated cell temperature with temperature given in `data`\n # where available.\n@@ -1814,6 +1800,7 @@ def run_model_from_effective_irradiance(self, data=None):\n \"\"\"\n data = _to_tuple(data)\n self._check_multiple_input(data)\n+ self._verify_df(data, required=['effective_irradiance'])\n self._assign_weather(data)\n self._assign_total_irrad(data)\n self.results.effective_irradiance = _tuple_from_dfs(\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -985,26 +985,44 @@ def test_run_model_from_poa_tracking(sapm_dc_snl_ac_system, location,\n assert_series_equal(ac, expected)\n \n \[email protected](\"input_type\", [lambda x: x[0], tuple, list])\n def test_run_model_from_effective_irradiance(sapm_dc_snl_ac_system, location,\n- weather, total_irrad):\n+ weather, total_irrad, input_type):\n data = weather.copy()\n data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad\n data['effective_irradiance'] = data['poa_global']\n mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss',\n spectral_model='no_loss')\n- ac = mc.run_model_from_effective_irradiance(data).results.ac\n+ ac = mc.run_model_from_effective_irradiance(input_type((data,))).results.ac\n expected = pd.Series(np.array([149.280238, 96.678385]),\n index=data.index)\n assert_series_equal(ac, expected)\n \n \[email protected](\"input_type\", [tuple, list])\n+def test_run_model_from_effective_irradiance_multi_array(\n+ sapm_dc_snl_ac_system_Array, location, weather, total_irrad,\n+ input_type):\n+ data = weather.copy()\n+ data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad\n+ data['effective_irradiance'] = data['poa_global']\n+ mc = ModelChain(sapm_dc_snl_ac_system_Array, location, aoi_model='no_loss',\n+ spectral_model='no_loss')\n+ mc.run_model_from_effective_irradiance(input_type((data, data)))\n+ # arrays have different orientation, but should give same dc power\n+ # because we are the same passing POA irradiance and air\n+ # temperature.\n+ assert_frame_equal(mc.results.dc[0], mc.results.dc[1])\n+\n+\[email protected](\"input_type\", [lambda x: x[0], tuple, list])\n def test_run_model_from_effective_irradiance_no_poa_global(\n- sapm_dc_snl_ac_system, location, weather, total_irrad):\n+ sapm_dc_snl_ac_system, location, weather, total_irrad, input_type):\n data = weather.copy()\n data['effective_irradiance'] = total_irrad['poa_global']\n mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss',\n spectral_model='no_loss')\n- ac = mc.run_model_from_effective_irradiance(data).results.ac\n+ ac = mc.run_model_from_effective_irradiance(input_type((data,))).results.ac\n expected = pd.Series(np.array([149.280238, 96.678385]),\n index=data.index)\n assert_series_equal(ac, expected)\n@@ -1087,23 +1105,6 @@ def test_run_model_from_effective_irradiance_minimal_input(\n assert not mc.results.ac.empty\n \n \n-def test_run_model_from_effective_irradiance_missing_poa(\n- sapm_dc_snl_ac_system_Array, location, total_irrad):\n- data_incomplete = pd.DataFrame(\n- {'effective_irradiance': total_irrad['poa_global'],\n- 'poa_global': total_irrad['poa_global']},\n- index=total_irrad.index)\n- data_complete = pd.DataFrame(\n- {'effective_irradiance': total_irrad['poa_global'],\n- 'cell_temperature': 30},\n- index=total_irrad.index)\n- mc = ModelChain(sapm_dc_snl_ac_system_Array, location)\n- with pytest.raises(ValueError,\n- match=\"you must provide 'poa_global' for all Arrays\"):\n- mc.run_model_from_effective_irradiance(\n- (data_complete, data_incomplete))\n-\n-\n def test_run_model_singleton_weather_single_array(cec_dc_snl_ac_system,\n location, weather):\n mc = ModelChain(cec_dc_snl_ac_system, location,\n", "problem_statement": "ValueError: ModelChain.run_from_effective_irradiance([weather]) when only providing temp_air and wind_speed\n**Describe the bug**\r\nAccording to the (new) docstring for `ModelChain.run_from_effective_irradiance`, cell temperature can be calculated from temperature_model using `'effective_irradiance'`. This is not the case when using one or more arrays \r\nhttps://github.com/pvlib/pvlib-python/blame/master/pvlib/modelchain.py#L1589-L1606\r\n\r\n**To Reproduce**\r\n```python\r\nfrom copy import deepcopy\r\nimport pandas as pd\r\nfrom pvlib.location import Location\r\nfrom pvlib.pvsystem import Array, PVSystem\r\nfrom pvlib.modelchain import ModelChain\r\n\r\n\r\narray_params = {\r\n \"surface_tilt\": 32.0,\r\n \"surface_azimuth\": 180.0,\r\n \"module\": \"Canadian_Solar_Inc__CS5P_220M\",\r\n \"albedo\": 0.2,\r\n \"temperature_model_parameters\": {\r\n \"u_c\": 29.0,\r\n \"u_v\": 0.0,\r\n \"eta_m\": 0.1,\r\n \"alpha_absorption\": 0.9,\r\n },\r\n \"strings\": 5,\r\n \"modules_per_string\": 7,\r\n \"module_parameters\": {\r\n \"alpha_sc\": 0.004539,\r\n \"gamma_ref\": 1.2,\r\n \"mu_gamma\": -0.003,\r\n \"I_L_ref\": 5.11426,\r\n \"I_o_ref\": 8.10251e-10,\r\n \"R_sh_ref\": 381.254,\r\n \"R_sh_0\": 400.0,\r\n \"R_s\": 1.06602,\r\n \"cells_in_series\": 96,\r\n \"R_sh_exp\": 5.5,\r\n \"EgRef\": 1.121,\r\n },\r\n}\r\ninverter_parameters = {\r\n \"Paco\": 250.0,\r\n \"Pdco\": 259.589,\r\n \"Vdco\": 40.0,\r\n \"Pso\": 2.08961,\r\n \"C0\": -4.1e-05,\r\n \"C1\": -9.1e-05,\r\n \"C2\": 0.000494,\r\n \"C3\": -0.013171,\r\n \"Pnt\": 0.075,\r\n}\r\n\r\n\r\nlocation = Location(latitude=33.98, longitude=-115.323, altitude=2300)\r\n\r\narray_sys = PVSystem(\r\n arrays=[\r\n Array(**array_params, name=0),\r\n ],\r\n inverter_parameters=inverter_parameters,\r\n)\r\nweather = pd.DataFrame(\r\n {\r\n \"effective_irradiance\": [1100.0, 1101.0],\r\n \"temp_air\": [25.0, 26.0],\r\n \"wind_speed\": [10.0, 10.0],\r\n },\r\n index=pd.DatetimeIndex(\r\n [pd.Timestamp(\"2021-01-20T12:00-05:00\"), pd.Timestamp(\"2021-01-20T12:05-05:00\")]\r\n ),\r\n)\r\nmc0 = ModelChain(\r\n array_sys,\r\n location,\r\n aoi_model=\"no_loss\",\r\n spectral_model=\"no_loss\",\r\n)\r\nmc1 = deepcopy(mc0)\r\n\r\nmc0.run_model_from_effective_irradiance(weather)\r\nassert isinstance(mc0.results.cell_temperature, pd.Series)\r\n\r\n\r\nmc1.run_model_from_effective_irradiance([weather]) # ValueError\r\n\r\n```\r\n\r\n**Expected behavior**\r\nRunning the model with both `weather` and `[weather]` work\r\n\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.9.0-alpha.2+5.gb40df75\n", "hints_text": "@cwhanse we overlooked updating this in #1129:\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/b40df75ddbc467a113b87643c1faef073cc37b3e/pvlib/modelchain.py#L1594-L1598\r\n\r\nOne possible solution is \r\n\r\n```python\r\nif any(p is None for p in poa):\r\n raise ValueError\r\n```", "created_at": "2021-02-06T18:01:53Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_run_model_tracker_list", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1026", "base_commit": "27872b83b0932cc419116f79e442963cced935bb", "patch": "diff --git a/pvlib/iotools/crn.py b/pvlib/iotools/crn.py\n--- a/pvlib/iotools/crn.py\n+++ b/pvlib/iotools/crn.py\n@@ -33,7 +33,7 @@\n \n # specify dtypes for potentially problematic values\n DTYPES = [\n- 'int64', 'int64', 'int64', 'int64', 'int64', 'int64', 'float64', 'float64',\n+ 'int64', 'int64', 'int64', 'int64', 'int64', 'str', 'float64', 'float64',\n 'float64', 'float64', 'float64', 'int64', 'float64', 'O', 'int64',\n 'float64', 'int64', 'float64', 'float64', 'int64', 'int64', 'float64',\n 'int64'\n@@ -67,6 +67,13 @@ def read_crn(filename):\n e.g. `SOLAR_RADIATION` becomes `ghi`. See the\n `pvlib.iotools.crn.VARIABLE_MAP` dict for the complete mapping.\n \n+ CRN files occasionally have a set of null characters on a line\n+ instead of valid data. This function drops those lines. Sometimes\n+ these null characters appear on a line of their own and sometimes\n+ they occur on the same line as valid data. In the latter case, the\n+ valid data will not be returned. Users may manually remove the null\n+ characters and reparse the file if they need that line.\n+\n References\n ----------\n .. [1] U.S. Climate Reference Network\n@@ -78,9 +85,13 @@ def read_crn(filename):\n Amer. Meteor. Soc., 94, 489-498. :doi:`10.1175/BAMS-D-12-00170.1`\n \"\"\"\n \n- # read in data\n+ # read in data. set fields with NUL characters to NaN\n data = pd.read_fwf(filename, header=None, names=HEADERS.split(' '),\n- widths=WIDTHS)\n+ widths=WIDTHS, na_values=['\\x00\\x00\\x00\\x00\\x00\\x00'])\n+ # at this point we only have NaNs from NUL characters, not -999 etc.\n+ # these bad rows need to be removed so that dtypes can be set.\n+ # NaNs require float dtype so we run into errors if we don't do this.\n+ data = data.dropna(axis=0)\n # loop here because dtype kwarg not supported in read_fwf until 0.20\n for (col, _dtype) in zip(data.columns, DTYPES):\n data[col] = data[col].astype(_dtype)\n@@ -98,8 +109,11 @@ def read_crn(filename):\n except TypeError:\n pass\n \n- # set nans\n+ # Now we can set nans. This could be done a per column basis to be\n+ # safer, since in principle a real -99 value could occur in a -9999\n+ # column. Very unlikely to see that in the real world.\n for val in [-99, -999, -9999]:\n+ # consider replacing with .replace([-99, -999, -9999])\n data = data.where(data != val, np.nan)\n \n data = data.rename(columns=VARIABLE_MAP)\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_crn.py b/pvlib/tests/iotools/test_crn.py\n--- a/pvlib/tests/iotools/test_crn.py\n+++ b/pvlib/tests/iotools/test_crn.py\n@@ -8,18 +8,39 @@\n \n \n @pytest.fixture\n-def testfile():\n- return DATA_DIR / 'CRNS0101-05-2019-AZ_Tucson_11_W.txt'\n-\n-\n-def test_read_crn(testfile):\n- columns = [\n+def columns():\n+ return [\n 'WBANNO', 'UTC_DATE', 'UTC_TIME', 'LST_DATE', 'LST_TIME', 'CRX_VN',\n 'longitude', 'latitude', 'temp_air', 'PRECIPITATION', 'ghi',\n 'ghi_flag',\n 'SURFACE_TEMPERATURE', 'ST_TYPE', 'ST_FLAG', 'relative_humidity',\n 'relative_humidity_flag', 'SOIL_MOISTURE_5', 'SOIL_TEMPERATURE_5',\n 'WETNESS', 'WET_FLAG', 'wind_speed', 'wind_speed_flag']\n+\n+\[email protected]\n+def dtypes():\n+ return [\n+ dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'),\n+ dtype('int64'), dtype('O'), dtype('float64'), dtype('float64'),\n+ dtype('float64'), dtype('float64'), dtype('float64'),\n+ dtype('int64'), dtype('float64'), dtype('O'), dtype('int64'),\n+ dtype('float64'), dtype('int64'), dtype('float64'),\n+ dtype('float64'), dtype('int64'), dtype('int64'), dtype('float64'),\n+ dtype('int64')]\n+\n+\[email protected]\n+def testfile():\n+ return DATA_DIR / 'CRNS0101-05-2019-AZ_Tucson_11_W.txt'\n+\n+\[email protected]\n+def testfile_problems():\n+ return DATA_DIR / 'CRN_with_problems.txt'\n+\n+\n+def test_read_crn(testfile, columns, dtypes):\n index = pd.DatetimeIndex(['2019-01-01 16:10:00',\n '2019-01-01 16:15:00',\n '2019-01-01 16:20:00',\n@@ -34,16 +55,26 @@ def test_read_crn(testfile):\n 0.0, 340.0, 0, 4.3, 'C', 0, 83.0, 0, nan, nan, 1183, 0, 0.53, 0],\n [53131, 20190101, 1625, 20190101, 925, 3, -111.17, 32.24, 4.0,\n 0.0, 393.0, 0, 4.8, 'C', 0, 81.0, 0, nan, nan, 1223, 0, 0.64, 0]])\n- dtypes = [\n- dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'),\n- dtype('int64'), dtype('int64'), dtype('float64'), dtype('float64'),\n- dtype('float64'), dtype('float64'), dtype('float64'),\n- dtype('int64'), dtype('float64'), dtype('O'), dtype('int64'),\n- dtype('float64'), dtype('int64'), dtype('float64'),\n- dtype('float64'), dtype('int64'), dtype('int64'), dtype('float64'),\n- dtype('int64')]\n expected = pd.DataFrame(values, columns=columns, index=index)\n for (col, _dtype) in zip(expected.columns, dtypes):\n expected[col] = expected[col].astype(_dtype)\n out = crn.read_crn(testfile)\n assert_frame_equal(out, expected)\n+\n+\n+def test_read_crn_problems(testfile_problems, columns, dtypes):\n+ # GH1025\n+ index = pd.DatetimeIndex(['2020-07-06 12:00:00',\n+ '2020-07-06 13:10:00'],\n+ freq=None).tz_localize('UTC')\n+ values = np.array([\n+ [92821, 20200706, 1200, 20200706, 700, '3', -80.69, 28.62, 24.9,\n+ 0.0, 190.0, 0, 25.5, 'C', 0, 93.0, 0, nan, nan, 990, 0, 1.57, 0],\n+ [92821, 20200706, 1310, 20200706, 810, '2.623', -80.69, 28.62,\n+ 26.9, 0.0, 430.0, 0, 30.2, 'C', 0, 87.0, 0, nan, nan, 989, 0,\n+ 1.64, 0]])\n+ expected = pd.DataFrame(values, columns=columns, index=index)\n+ for (col, _dtype) in zip(expected.columns, dtypes):\n+ expected[col] = expected[col].astype(_dtype)\n+ out = crn.read_crn(testfile_problems)\n+ assert_frame_equal(out, expected)\n", "problem_statement": "make read_crn accomodate bad files\nA couple of issues with our `read_crn` function. \r\n\r\nFirst, the character sequence '\\x00\\x00\\x00\\x00\\x00\\x00' occasionally shows up and trips up pandas. This can be fixed by adding `na_values=['\\x00\\x00\\x00\\x00\\x00\\x00']` to the reader.\r\n\r\nSecond, we try to set the `CRX_VN` column to dtype int, but it occasionally has floats that cannot be coerced. The [documentation](https://www1.ncdc.noaa.gov/pub/data/uscrn/products/subhourly01/README.txt) says it should be treated like a string.\r\n\r\nExample below shows both issues in `'CRNS0101-05-2020-FL_Titusville_7_E.txt'`\r\n\r\n```\r\n92821 20200706 1145 20200706 0645 3 -80.69 28.62 24.5 0.0 151 0 24.7 C 0 94 0 -99.000 -9999.0 990 0 1.23 0\r\n92821 20200706 1150 20200706 0650 3 -80.69 28.62 24.7 0.0 168 0 25.0 C 0 94 0 -99.000 -9999.0 990 0 1.28 0\r\n92821 20200706 1155 20200706 0655 3 -80.69 28.62 24.9 0.0 173 0 25.3 C 0 93 0 -99.000 -9999.0 990 0 1.48 0\r\n92821 20200706 1200 20200706 0700 3 -80.69 28.62 24.9 0.0 190 0 25.5 C 0 93 0 -99.000 -9999.0 990 0 1.57 0\r\n\\x00\\x00\\x00\\x00\\x00\\x00 repeated\r\n92821 20200706 1305 20200706 0805 2.623 -80.69 28.62 26.8 0.0 409 0 30.0 C 0 87 0 -99.000 -9999.0 988 0 1.44 0\r\n92821 20200706 1310 20200706 0810 2.623 -80.69 28.62 26.9 0.0 430 0 30.2 C 0 87 0 -99.000 -9999.0 989 0 1.64 0\r\n92821 20200706 1315 20200706 0815 2.623 -80.69 28.62 27.0 0.0 445 0 30.4 C 0 86 0 -99.000 -9999.0 989 0 1.94 0\r\n92821 20200706 1320 20200706 0820 2.623 -80.69 28.62 27.3 0.0 463 0 30.8 C 0 86 0 -99.000 -9999.0 988 0 1.50 0\r\n92821 20200706 1325 20200706 0825 2.623 -80.69 28.62 27.6 0.0 478 0 31.1 C 0 85 0 -99.000 -9999.0 988 0 1.54 0\r\n92821 20200706 1330 20200706 0830 2.623 -80.69 28.62 27.6 0.0 496 0 31.5 C 0 84 0 -99.000 -9999.0 988 0 1.48 0\r\n```\r\n\r\nfyi @lboeman \n", "hints_text": "", "created_at": "2020-08-21T16:27:41Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_crn.py::test_read_crn"], "PASS_TO_PASS": [], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1616", "base_commit": "25af86599845f23b0ce57dc1cbe743b3a1e68d1a", "patch": "diff --git a/pvlib/iam.py b/pvlib/iam.py\n--- a/pvlib/iam.py\n+++ b/pvlib/iam.py\n@@ -11,7 +11,7 @@\n import numpy as np\n import pandas as pd\n import functools\n-from pvlib.tools import cosd, sind, tand, asind\n+from pvlib.tools import cosd, sind\n \n # a dict of required parameter names for each IAM model\n # keys are the function names for the IAM models\n@@ -91,21 +91,22 @@ def ashrae(aoi, b=0.05):\n return iam\n \n \n-def physical(aoi, n=1.526, K=4., L=0.002):\n+def physical(aoi, n=1.526, K=4.0, L=0.002, *, n_ar=None):\n r\"\"\"\n Determine the incidence angle modifier using refractive index ``n``,\n- extinction coefficient ``K``, and glazing thickness ``L``.\n+ extinction coefficient ``K``, glazing thickness ``L`` and refractive\n+ index ``n_ar`` of an optional anti-reflective coating.\n \n ``iam.physical`` calculates the incidence angle modifier as described in\n- [1]_, Section 3. The calculation is based on a physical model of absorbtion\n+ [1]_, Section 3, with additional support of an anti-reflective coating.\n+ The calculation is based on a physical model of reflections, absorption,\n and transmission through a transparent cover.\n \n Parameters\n ----------\n aoi : numeric\n The angle of incidence between the module normal vector and the\n- sun-beam vector in degrees. Angles of 0 are replaced with 1e-06\n- to ensure non-nan results. Angles of nan will result in nan.\n+ sun-beam vector in degrees. Angles of nan will result in nan.\n \n n : numeric, default 1.526\n The effective index of refraction (unitless). Reference [1]_\n@@ -121,6 +122,11 @@ def physical(aoi, n=1.526, K=4., L=0.002):\n indicates that 0.002 meters (2 mm) is reasonable for most\n glass-covered PV panels.\n \n+ n_ar : numeric, optional\n+ The effective index of refraction of the anti-reflective (AR) coating\n+ (unitless). If n_ar is None (default), no AR coating is applied.\n+ A typical value for the effective index of an AR coating is 1.29.\n+\n Returns\n -------\n iam : numeric\n@@ -149,48 +155,65 @@ def physical(aoi, n=1.526, K=4., L=0.002):\n pvlib.iam.interp\n pvlib.iam.sapm\n \"\"\"\n- zeroang = 1e-06\n-\n- # hold a new reference to the input aoi object since we're going to\n- # overwrite the aoi reference below, but we'll need it for the\n- # series check at the end of the function\n- aoi_input = aoi\n-\n- aoi = np.where(aoi == 0, zeroang, aoi)\n-\n- # angle of reflection\n- thetar_deg = asind(1.0 / n * (sind(aoi)))\n-\n- # reflectance and transmittance for normal incidence light\n- rho_zero = ((1-n) / (1+n)) ** 2\n- tau_zero = np.exp(-K*L)\n-\n- # reflectance for parallel and perpendicular polarized light\n- rho_para = (tand(thetar_deg - aoi) / tand(thetar_deg + aoi)) ** 2\n- rho_perp = (sind(thetar_deg - aoi) / sind(thetar_deg + aoi)) ** 2\n-\n- # transmittance for non-normal light\n- tau = np.exp(-K * L / cosd(thetar_deg))\n-\n- # iam is ratio of non-normal to normal incidence transmitted light\n- # after deducting the reflected portion of each\n- iam = ((1 - (rho_para + rho_perp) / 2) / (1 - rho_zero) * tau / tau_zero)\n-\n- with np.errstate(invalid='ignore'):\n- # angles near zero produce nan, but iam is defined as one\n- small_angle = 1e-06\n- iam = np.where(np.abs(aoi) < small_angle, 1.0, iam)\n-\n- # angles at 90 degrees can produce tiny negative values,\n- # which should be zero. this is a result of calculation precision\n- # rather than the physical model\n- iam = np.where(iam < 0, 0, iam)\n-\n- # for light coming from behind the plane, none can enter the module\n- iam = np.where(aoi > 90, 0, iam)\n-\n- if isinstance(aoi_input, pd.Series):\n- iam = pd.Series(iam, index=aoi_input.index)\n+ n1, n3 = 1, n\n+ if n_ar is None or np.allclose(n_ar, n1):\n+ # no AR coating\n+ n2 = n\n+ else:\n+ n2 = n_ar\n+\n+ # incidence angle\n+ costheta = np.maximum(0, cosd(aoi)) # always >= 0\n+ sintheta = np.sqrt(1 - costheta**2) # always >= 0\n+ n1costheta1 = n1 * costheta\n+ n2costheta1 = n2 * costheta\n+\n+ # refraction angle of first interface\n+ sintheta = n1 / n2 * sintheta\n+ costheta = np.sqrt(1 - sintheta**2)\n+ n1costheta2 = n1 * costheta\n+ n2costheta2 = n2 * costheta\n+\n+ # reflectance of s-, p-polarized, and normal light by the first interface\n+ rho12_s = ((n1costheta1 - n2costheta2) / (n1costheta1 + n2costheta2)) ** 2\n+ rho12_p = ((n1costheta2 - n2costheta1) / (n1costheta2 + n2costheta1)) ** 2\n+ rho12_0 = ((n1 - n2) / (n1 + n2)) ** 2\n+\n+ # transmittance through the first interface\n+ tau_s = 1 - rho12_s\n+ tau_p = 1 - rho12_p\n+ tau_0 = 1 - rho12_0\n+\n+ if not np.allclose(n3, n2): # AR coated glass\n+ n3costheta2 = n3 * costheta\n+ # refraction angle of second interface\n+ sintheta = n2 / n3 * sintheta\n+ costheta = np.sqrt(1 - sintheta**2)\n+ n2costheta3 = n2 * costheta\n+ n3costheta3 = n3 * costheta\n+\n+ # reflectance by the second interface\n+ rho23_s = (\n+ (n2costheta2 - n3costheta3) / (n2costheta2 + n3costheta3)\n+ ) ** 2\n+ rho23_p = (\n+ (n2costheta3 - n3costheta2) / (n2costheta3 + n3costheta2)\n+ ) ** 2\n+ rho23_0 = ((n2 - n3) / (n2 + n3)) ** 2\n+\n+ # transmittance through the coating, including internal reflections\n+ # 1 + rho23*rho12 + (rho23*rho12)^2 + ... = 1/(1 - rho23*rho12)\n+ tau_s *= (1 - rho23_s) / (1 - rho23_s * rho12_s)\n+ tau_p *= (1 - rho23_p) / (1 - rho23_p * rho12_p)\n+ tau_0 *= (1 - rho23_0) / (1 - rho23_0 * rho12_0)\n+\n+ # transmittance after absorption in the glass\n+ tau_s *= np.exp(-K * L / costheta)\n+ tau_p *= np.exp(-K * L / costheta)\n+ tau_0 *= np.exp(-K * L)\n+\n+ # incidence angle modifier\n+ iam = (tau_s + tau_p) / 2 / tau_0\n \n return iam\n \n", "test_patch": "diff --git a/pvlib/tests/test_iam.py b/pvlib/tests/test_iam.py\n--- a/pvlib/tests/test_iam.py\n+++ b/pvlib/tests/test_iam.py\n@@ -42,7 +42,7 @@ def test_physical():\n expected = np.array([0, 0.8893998, 0.98797788, 0.99926198, 1, 0.99926198,\n 0.98797788, 0.8893998, 0, np.nan])\n iam = _iam.physical(aoi, 1.526, 0.002, 4)\n- assert_allclose(iam, expected, equal_nan=True)\n+ assert_allclose(iam, expected, atol=1e-7, equal_nan=True)\n \n # GitHub issue 397\n aoi = pd.Series(aoi)\n@@ -51,6 +51,22 @@ def test_physical():\n assert_series_equal(iam, expected)\n \n \n+def test_physical_ar():\n+ aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan])\n+ expected = np.array([1, 0.99944171, 0.9917463, 0.91506158, 0, 0, np.nan])\n+ iam = _iam.physical(aoi, n_ar=1.29)\n+ assert_allclose(iam, expected, atol=1e-7, equal_nan=True)\n+\n+\n+def test_physical_noar():\n+ aoi = np.array([0, 22.5, 45, 67.5, 90, 100, np.nan])\n+ expected = _iam.physical(aoi)\n+ iam0 = _iam.physical(aoi, n_ar=1)\n+ iam1 = _iam.physical(aoi, n_ar=1.526)\n+ assert_allclose(iam0, expected, equal_nan=True)\n+ assert_allclose(iam1, expected, equal_nan=True)\n+\n+\n def test_physical_scalar():\n aoi = -45.\n iam = _iam.physical(aoi, 1.526, 0.002, 4)\n", "problem_statement": "IAM that supports AR coating like Fresnel\n# Problem\r\nCurrently pvlib supports the DeSoto physical model (similar to normal glass), ASHRAE, Martin & Ruiz, and SAPM polynomial, but it doesn't have a pure Fresnel model that allows additional interfaces like an AR coating. \r\n\r\n* DeSoto physical model is most similar to the Fresnel for normal glass but only has one interface, so is limited to IAM curves below it only, while an AR coating would have a greater ρ \r\n* Martin & Ruiz could be used to approximate an AR coated glass if the correct `a_r` were known. The default of `a_r=0.16` is slightly above the normal glass Fresnel IAM, but an `a_r=0.14` seems to match an AR coating with index of refraction of 1.2 most closely.\r\n\r\n\r\n\r\n\r\n# Proposal\r\na new method in `pvl.iam.fresnel_ar(aoi, n_ar=1.2, n_air=1.0, n_glass=1.56)` that implements the [Fresnel equation](https://en.wikipedia.org/wiki/Fresnel_equations)\r\n\r\n# Alternative\r\nSuggest readers to use Martin & Ruiz with `a_r=0.14` instead of default.\r\n\r\n# additional content\r\nPVsyst has switched to Fresnel equations. We can duplicate [their methods](https://www.pvsyst.com/help/iam_loss.htm) ignoring additional reflections and the encapsulant layer:\r\n\r\n\r\n<details>\r\n\r\n```python\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nplt.ion()\r\n\r\n\r\n# constants\r\nn_glass = 1.56\r\nn_air = 1.0\r\ntheta_inc = np.linspace(0, 88, 100)\r\n\r\n\r\ndef snell(theta_1, n1, n2):\r\n \"\"\"Snell's equation\"\"\"\r\n sintheta_2 = n1/n2 * np.sin(np.radians(theta_1))\r\n return sintheta_2, np.degrees(np.arcsin(sintheta_2))\r\n\r\n\r\ndef refl_s(theta_1, theta_2, n1, n2):\r\n \"\"\"Fresnel's equation\"\"\"\r\n n1_costheta_1 = n1*np.cos(np.radians(theta_1))\r\n n2_costheta_2 = n2*np.cos(np.radians(theta_2))\r\n return np.abs((n1_costheta_1 - n2_costheta_2)/(n1_costheta_1 + n2_costheta_2))**2\r\n\r\n\r\ndef refl_p(theta_1, theta_2, n1, n2):\r\n \"\"\"Fresnel's equation\"\"\"\r\n n1_costheta_2 = n1*np.cos(np.radians(theta_2))\r\n n2_costheta_1 = n2*np.cos(np.radians(theta_1))\r\n return np.abs((n1_costheta_2 - n2_costheta_1)/(n1_costheta_2 + n2_costheta_1))**2\r\n\r\n\r\ndef refl_eff(rs, rp):\r\n \"\"\"effective reflectivity\"\"\"\r\n return (rs+rp)/2\r\n\r\n\r\ndef trans(refl):\r\n \"\"\"transmissivity\"\"\"\r\n return 1-refl\r\n\r\n\r\ndef refl0(n1, n2):\r\n \"\"\"reflectivity at normal incidence\"\"\"\r\n return np.abs((n1-n2)/(n1+n2))**2\r\n\r\n\r\ndef fresnel(theta_inc, n1=n_air, n2=n_glass):\r\n \"\"\"calculate IAM using Fresnel's Law\"\"\"\r\n _, theta_tr = snell(theta_inc, n1, n2)\r\n rs = refl_s(theta_inc, theta_tr, n1, n2)\r\n rp = refl_p(theta_inc, theta_tr, n1, n2)\r\n reff = refl_eff(rs, rp)\r\n r0 = refl0(n1, n2)\r\n return trans(reff)/trans(r0)\r\n\r\n\r\ndef ashrae(theta_inc, b0=0.05):\r\n \"\"\"ASHRAE equation\"\"\"\r\n return 1 - b0*(1/np.cos(np.radians(theta_inc)) - 1)\r\n\r\n\r\ndef fresnel_ar(theta_inc, n_ar, n1=n_air, n2=n_glass):\r\n \"\"\"calculate IAM using Fresnel's law with AR\"\"\"\r\n # use fresnel() for n2=n_ar\r\n _, theta_ar = snell(theta_inc, n1, n_ar)\r\n rs_ar1 = refl_s(theta_inc, theta_ar, n1, n_ar)\r\n rp_ar1 = refl_p(theta_inc, theta_ar, n1, n_ar)\r\n r0_ar1 = refl0(n1, n_ar)\r\n # repeat with fresnel() with n1=n_ar\r\n _, theta_tr = snell(theta_ar, n_ar, n2)\r\n rs = refl_s(theta_ar, theta_tr, n_ar, n2)\r\n rp = refl_p(theta_ar, theta_tr, n_ar, n2)\r\n # note that combined reflectivity is product of transmissivity!\r\n # so... rho12 = 1 - (1-rho1)(1-rho2) \r\n reff = refl_eff(1-(1-rs_ar1)*(1-rs), 1-(1-rp_ar1)*(1-rp))\r\n r0 = 1-(1-refl0(n_ar, n2))*(1-r0_ar1)\r\n return trans(reff)/trans(r0)\r\n\r\n\r\n# plot Fresnel for normal glass and ASHRAE\r\nplt.plot(theta_inc, fresnel(theta_inc))\r\nplt.plot(theta_inc, ashrae(theta_inc))\r\n\r\n# calculate IAM for AR with n=1.1 and plot\r\niam_ar11 = fresnel_ar(theta_inc, n_ar=1.1)\r\nplt.plot(theta_inc, iam_ar11)\r\n\r\n# repeat for AR with n=1.2\r\niam_ar12 = fresnel_ar(theta_inc, n_ar=1.2)\r\nplt.plot(theta_inc, iam_ar12)\r\n\r\n# make plot pretty\r\nplt.legend(['Fresnel, normal glass', 'ASHRAE, $b_0=0.05$', 'Fresnel $n_{AR}=1.1$', 'Fresnel $n_{AR}=1.2$'])\r\nplt.title(\"IAM correction, Fresnel vs. ASHRAE, using basic eqn's\")\r\nplt.ylabel('IAM')\r\nplt.xlabel(r'incidence angle $\\theta_{inc} [\\degree]$')\r\nplt.grid()\r\nplt.ylim([0.55,1.05])\r\n```\r\n</details>\r\n\r\n\n", "hints_text": "+1. This [reference](https://www.sciencedirect.com/science/article/abs/pii/S0038092X96001375) might be relevant.\nI seem to recall from somewhere that PVsyst actually interpolates from a fixed set of pre-calculated values when simulating.\nPVsyst allows a user specified custom IAM v AOI lookup table in the module PAN file, but that presupposes there exist qualified IAM measurements either from a lab or the manufacturer. Otherwise they use Fresnel as of v6.67. See https://www.pvsyst.com/help/iam_loss.htm\nYes, what I meant is that they use the Fresnel equations to populate the table for interpolation. At least this is my recollection.", "created_at": "2022-12-16T11:52:35Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_iam.py::test_physical_ar", "pvlib/tests/test_iam.py::test_physical_noar"], "PASS_TO_PASS": ["pvlib/tests/test_iam.py::test_ashrae", "pvlib/tests/test_iam.py::test_ashrae_scalar", "pvlib/tests/test_iam.py::test_physical", "pvlib/tests/test_iam.py::test_physical_scalar", "pvlib/tests/test_iam.py::test_martin_ruiz", "pvlib/tests/test_iam.py::test_martin_ruiz_exception", "pvlib/tests/test_iam.py::test_martin_ruiz_diffuse", "pvlib/tests/test_iam.py::test_iam_interp", "pvlib/tests/test_iam.py::test_sapm[45-0.9975036250000002]", "pvlib/tests/test_iam.py::test_sapm[aoi1-expected1]", "pvlib/tests/test_iam.py::test_sapm[aoi2-expected2]", "pvlib/tests/test_iam.py::test_sapm_limits", "pvlib/tests/test_iam.py::test_marion_diffuse_model", "pvlib/tests/test_iam.py::test_marion_diffuse_kwargs", "pvlib/tests/test_iam.py::test_marion_diffuse_invalid", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[sky-180-0.9596085829811408]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[horizon-1800-0.8329070417832541]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[ground-180-0.719823559106309]", "pvlib/tests/test_iam.py::test_marion_integrate_list[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_list[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_list[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_series[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_series[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_series[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_ground_flat", "pvlib/tests/test_iam.py::test_marion_integrate_invalid", "pvlib/tests/test_iam.py::test_schlick", "pvlib/tests/test_iam.py::test_schlick_diffuse"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1740", "base_commit": "275e6718caf7486cb5b7dcf29acd59499ad51f7f", "patch": "diff --git a/pvlib/iotools/sodapro.py b/pvlib/iotools/sodapro.py\n--- a/pvlib/iotools/sodapro.py\n+++ b/pvlib/iotools/sodapro.py\n@@ -9,6 +9,8 @@\n import warnings\n \n \n+URL = 'api.soda-solardata.com'\n+\n CAMS_INTEGRATED_COLUMNS = [\n 'TOA', 'Clear sky GHI', 'Clear sky BHI', 'Clear sky DHI', 'Clear sky BNI',\n 'GHI', 'BHI', 'DHI', 'BNI',\n@@ -44,7 +46,7 @@\n def get_cams(latitude, longitude, start, end, email, identifier='mcclear',\n altitude=None, time_step='1h', time_ref='UT', verbose=False,\n integrated=False, label=None, map_variables=True,\n- server='www.soda-is.com', timeout=30):\n+ server=URL, timeout=30):\n \"\"\"\n Retrieve time-series of radiation and/or clear-sky global, beam, and\n diffuse radiation from CAMS (see [1]_). Data is retrieved from SoDa [2]_.\n@@ -91,8 +93,8 @@ def get_cams(latitude, longitude, start, end, email, identifier='mcclear',\n map_variables: bool, default: True\n When true, renames columns of the DataFrame to pvlib variable names\n where applicable. See variable :const:`VARIABLE_MAP`.\n- server: str, default: 'www.soda-is.com'\n- Main server (www.soda-is.com) or backup mirror server (pro.soda-is.com)\n+ server: str, default: :const:`pvlib.iotools.sodapro.URL`\n+ Base url of the SoDa Pro CAMS Radiation API.\n timeout : int, default: 30\n Time in seconds to wait for server response before timeout\n \n@@ -344,13 +346,13 @@ def read_cams(filename, integrated=False, label=None, map_variables=True):\n all time steps except for '1M' which has a default of 'right'.\n map_variables: bool, default: True\n When true, renames columns of the Dataframe to pvlib variable names\n- where applicable. See variable VARIABLE_MAP.\n+ where applicable. See variable :const:`VARIABLE_MAP`.\n \n Returns\n -------\n data: pandas.DataFrame\n- Timeseries data from CAMS Radiation or McClear\n- :func:`pvlib.iotools.get_cams` for fields\n+ Timeseries data from CAMS Radiation or McClear.\n+ See :func:`pvlib.iotools.get_cams` for fields.\n metadata: dict\n Metadata available in the file.\n \n", "test_patch": "diff --git a/pvlib/tests/iotools/test_sodapro.py b/pvlib/tests/iotools/test_sodapro.py\n--- a/pvlib/tests/iotools/test_sodapro.py\n+++ b/pvlib/tests/iotools/test_sodapro.py\n@@ -209,7 +209,7 @@ def test_get_cams(requests_mock, testfile, index, columns, values, dtypes,\n mock_response = test_file.read()\n # Specify the full URI of a specific example, this ensures that all of the\n # inputs are passing on correctly\n- url_test_cams = f'https://www.soda-is.com/service/wps?DataInputs=latitude=55.7906;longitude=12.5251;altitude=80;date_begin=2020-01-01;date_end=2020-05-04;time_ref=UT;summarization=P01M;username=pvlib-admin%2540googlegroups.com;verbose=false&Service=WPS&Request=Execute&Identifier=get_{identifier}&version=1.0.0&RawDataOutput=irradiation' # noqa: E501\n+ url_test_cams = f'https://api.soda-solardata.com/service/wps?DataInputs=latitude=55.7906;longitude=12.5251;altitude=80;date_begin=2020-01-01;date_end=2020-05-04;time_ref=UT;summarization=P01M;username=pvlib-admin%2540googlegroups.com;verbose=false&Service=WPS&Request=Execute&Identifier=get_{identifier}&version=1.0.0&RawDataOutput=irradiation' # noqa: E501\n \n requests_mock.get(url_test_cams, text=mock_response,\n headers={'Content-Type': 'application/csv'})\n", "problem_statement": "Update CAMS/SoDa URL\nSoDa has developed a new load-balancing solution, such that requests are automatically redirected to the fastest server. This means that it might be advisable for us to update the URL in the [``pvlib.iotools.get_cams``](https://pvlib-python.readthedocs.io/en/stable/reference/generated/pvlib.iotools.get_cams.html?highlight=get_cams#pvlib.iotools.get_cams) function. \r\n\r\nEmail from SoDa (March 7th, 2023):\r\n> Our beta load balancing system for SoDa/CAMS API requests is extended to March 13th. All requests made on the beta-api.soda-solardata.com WILL NOT BE COUNTED in your subscription. The beta access will last until then. **From March 14th, the service will be fully operational and you have to use api.soda-solardata.com to process your API (machine to machine) requests.**\r\n\r\nand email from February 22nd, 2023:\r\n> This new functionality will automatically redirect any request to the fastest available SoDa server. As a result, future updates/maintenances won't need any action from your part as server switches will be completely autonomous.\r\n\r\nI will be following up on this issue in a couple of weeks.\r\n\r\n*Edit: email from March 20th, 2023*\r\n> We strongly advise you to switch your automatic commands on the load balancing system (api.soda-solardata.com). In that way, all future updates won't need any actions from your side. \n", "hints_text": "", "created_at": "2023-05-17T00:26:10Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_sodapro.py::test_get_cams[testfile0-index0-columns0-values0-dtypes0-mcclear]", "pvlib/tests/iotools/test_sodapro.py::test_get_cams[testfile1-index1-columns1-values1-dtypes1-cams_radiation]"], "PASS_TO_PASS": ["pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile0-index0-columns0-values0-dtypes0]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile1-index1-columns1-values1-dtypes1]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile2-index2-columns2-values2-dtypes2]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile3-index3-columns3-values3-dtypes3]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams_integrated_unmapped_label", "pvlib/tests/iotools/test_sodapro.py::test_read_cams_metadata", "pvlib/tests/iotools/test_sodapro.py::test_get_cams_bad_request"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1225", "base_commit": "0415365031ca8d0b2867f2a2877e0ad9d7098ffc", "patch": "diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py\n--- a/pvlib/irradiance.py\n+++ b/pvlib/irradiance.py\n@@ -14,7 +14,7 @@\n from pvlib import atmosphere, solarposition, tools\n \n \n-# see References section of grounddiffuse function\n+# see References section of get_ground_diffuse function\n SURFACE_ALBEDOS = {'urban': 0.18,\n 'grass': 0.20,\n 'fresh grass': 0.26,\n@@ -323,38 +323,51 @@ def get_total_irradiance(surface_tilt, surface_azimuth,\n Parameters\n ----------\n surface_tilt : numeric\n- Panel tilt from horizontal.\n+ Panel tilt from horizontal. [degree]\n surface_azimuth : numeric\n- Panel azimuth from north.\n+ Panel azimuth from north. [degree]\n solar_zenith : numeric\n- Solar zenith angle.\n+ Solar zenith angle. [degree]\n solar_azimuth : numeric\n- Solar azimuth angle.\n+ Solar azimuth angle. [degree]\n dni : numeric\n- Direct Normal Irradiance\n+ Direct Normal Irradiance. [W/m2]\n ghi : numeric\n- Global horizontal irradiance\n+ Global horizontal irradiance. [W/m2]\n dhi : numeric\n- Diffuse horizontal irradiance\n+ Diffuse horizontal irradiance. [W/m2]\n dni_extra : None or numeric, default None\n- Extraterrestrial direct normal irradiance\n+ Extraterrestrial direct normal irradiance. [W/m2]\n airmass : None or numeric, default None\n- Airmass\n+ Relative airmass (not adjusted for pressure). [unitless]\n albedo : numeric, default 0.25\n- Surface albedo\n- surface_type : None or String, default None\n- Surface type. See grounddiffuse.\n- model : String, default 'isotropic'\n- Irradiance model.\n- model_perez : String, default 'allsitescomposite1990'\n- Used only if model='perez'. See :py:func:`perez`.\n+ Surface albedo. [unitless]\n+ surface_type : None or str, default None\n+ Surface type. See :py:func:`~pvlib.irradiance.get_ground_diffuse` for\n+ the list of accepted values.\n+ model : str, default 'isotropic'\n+ Irradiance model. Can be one of ``'isotropic'``, ``'klucher'``,\n+ ``'haydavies'``, ``'reindl'``, ``'king'``, ``'perez'``.\n+ model_perez : str, default 'allsitescomposite1990'\n+ Used only if ``model='perez'``. See :py:func:`~pvlib.irradiance.perez`.\n \n Returns\n -------\n total_irrad : OrderedDict or DataFrame\n Contains keys/columns ``'poa_global', 'poa_direct', 'poa_diffuse',\n 'poa_sky_diffuse', 'poa_ground_diffuse'``.\n+\n+ Notes\n+ -----\n+ Models ``'haydavies'``, ``'reindl'``, or ``'perez'`` require\n+ ``'dni_extra'``. Values can be calculated using\n+ :py:func:`~pvlib.irradiance.get_extra_radiation`.\n+\n+ The ``'perez'`` model requires relative airmass (``airmass``) as input. If\n+ ``airmass`` is not provided, it is calculated using the defaults in\n+ :py:func:`~pvlib.atmosphere.get_relative_airmass`.\n \"\"\"\n+\n poa_sky_diffuse = get_sky_diffuse(\n surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n dni, ghi, dhi, dni_extra=dni_extra, airmass=airmass, model=model,\n@@ -387,34 +400,56 @@ def get_sky_diffuse(surface_tilt, surface_azimuth,\n Parameters\n ----------\n surface_tilt : numeric\n- Panel tilt from horizontal.\n+ Panel tilt from horizontal. [degree]\n surface_azimuth : numeric\n- Panel azimuth from north.\n+ Panel azimuth from north. [degree]\n solar_zenith : numeric\n- Solar zenith angle.\n+ Solar zenith angle. [degree]\n solar_azimuth : numeric\n- Solar azimuth angle.\n+ Solar azimuth angle. [degree]\n dni : numeric\n- Direct Normal Irradiance\n+ Direct Normal Irradiance. [W/m2]\n ghi : numeric\n- Global horizontal irradiance\n+ Global horizontal irradiance. [W/m2]\n dhi : numeric\n- Diffuse horizontal irradiance\n+ Diffuse horizontal irradiance. [W/m2]\n dni_extra : None or numeric, default None\n- Extraterrestrial direct normal irradiance\n+ Extraterrestrial direct normal irradiance. [W/m2]\n airmass : None or numeric, default None\n- Airmass\n- model : String, default 'isotropic'\n- Irradiance model.\n- model_perez : String, default 'allsitescomposite1990'\n- See perez.\n+ Relative airmass (not adjusted for pressure). [unitless]\n+ model : str, default 'isotropic'\n+ Irradiance model. Can be one of ``'isotropic'``, ``'klucher'``,\n+ ``'haydavies'``, ``'reindl'``, ``'king'``, ``'perez'``.\n+ model_perez : str, default 'allsitescomposite1990'\n+ Used only if ``model='perez'``. See :py:func:`~pvlib.irradiance.perez`.\n \n Returns\n -------\n poa_sky_diffuse : numeric\n+ Sky diffuse irradiance in the plane of array. [W/m2]\n+\n+ Raises\n+ ------\n+ ValueError\n+ If model is one of ``'haydavies'``, ``'reindl'``, or ``'perez'`` and\n+ ``dni_extra`` is ``None``.\n+\n+ Notes\n+ -----\n+ Models ``'haydavies'``, ``'reindl'``, and ``'perez``` require 'dni_extra'.\n+ Values can be calculated using\n+ :py:func:`~pvlib.irradiance.get_extra_radiation`.\n+\n+ The ``'perez'`` model requires relative airmass (``airmass``) as input. If\n+ ``airmass`` is not provided, it is calculated using the defaults in\n+ :py:func:`~pvlib.atmosphere.get_relative_airmass`.\n \"\"\"\n \n model = model.lower()\n+\n+ if (model in {'haydavies', 'reindl', 'perez'}) and (dni_extra is None):\n+ raise ValueError(f'dni_extra is required for model {model}')\n+\n if model == 'isotropic':\n sky = isotropic(surface_tilt, dhi)\n elif model == 'klucher':\n@@ -429,6 +464,8 @@ def get_sky_diffuse(surface_tilt, surface_azimuth,\n elif model == 'king':\n sky = king(surface_tilt, dhi, ghi, solar_zenith)\n elif model == 'perez':\n+ if airmass is None:\n+ airmass = atmosphere.get_relative_airmass(solar_zenith)\n sky = perez(surface_tilt, surface_azimuth, dhi, dni, dni_extra,\n solar_zenith, solar_azimuth, airmass,\n model=model_perez)\n@@ -501,7 +538,7 @@ def poa_components(aoi, dni, poa_sky_diffuse, poa_ground_diffuse):\n def get_ground_diffuse(surface_tilt, ghi, albedo=.25, surface_type=None):\n '''\n Estimate diffuse irradiance from ground reflections given\n- irradiance, albedo, and surface tilt\n+ irradiance, albedo, and surface tilt.\n \n Function to determine the portion of irradiance on a tilted surface\n due to ground reflections. Any of the inputs may be DataFrames or\n@@ -515,7 +552,7 @@ def get_ground_diffuse(surface_tilt, ghi, albedo=.25, surface_type=None):\n (e.g. surface facing up = 0, surface facing horizon = 90).\n \n ghi : numeric\n- Global horizontal irradiance in W/m^2.\n+ Global horizontal irradiance. [W/m^2]\n \n albedo : numeric, default 0.25\n Ground reflectance, typically 0.1-0.4 for surfaces on Earth\n@@ -531,7 +568,7 @@ def get_ground_diffuse(surface_tilt, ghi, albedo=.25, surface_type=None):\n Returns\n -------\n grounddiffuse : numeric\n- Ground reflected irradiances in W/m^2.\n+ Ground reflected irradiance. [W/m^2]\n \n \n References\n", "test_patch": "diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py\n--- a/pvlib/tests/test_irradiance.py\n+++ b/pvlib/tests/test_irradiance.py\n@@ -281,13 +281,35 @@ def test_sky_diffuse_zenith_close_to_90(model):\n assert sky_diffuse < 100\n \n \n-def test_get_sky_diffuse_invalid():\n+def test_get_sky_diffuse_model_invalid():\n with pytest.raises(ValueError):\n irradiance.get_sky_diffuse(\n 30, 180, 0, 180, 1000, 1100, 100, dni_extra=1360, airmass=1,\n model='invalid')\n \n \n+def test_get_sky_diffuse_missing_dni_extra():\n+ msg = 'dni_extra is required'\n+ with pytest.raises(ValueError, match=msg):\n+ irradiance.get_sky_diffuse(\n+ 30, 180, 0, 180, 1000, 1100, 100, airmass=1,\n+ model='haydavies')\n+\n+\n+def test_get_sky_diffuse_missing_airmass(irrad_data, ephem_data, dni_et):\n+ # test assumes location is Tucson, AZ\n+ # calculated airmass should be the equivalent to fixture airmass\n+ dni = irrad_data['dni'].copy()\n+ dni.iloc[2] = np.nan\n+ out = irradiance.get_sky_diffuse(\n+ 40, 180, ephem_data['apparent_zenith'], ephem_data['azimuth'], dni,\n+ irrad_data['ghi'], irrad_data['dhi'], dni_et, model='perez')\n+ expected = pd.Series(np.array(\n+ [0., 31.46046871, np.nan, 45.45539877]),\n+ index=irrad_data.index)\n+ assert_series_equal(out, expected, check_less_precise=2)\n+\n+\n def test_campbell_norman():\n expected = pd.DataFrame(np.array(\n [[863.859736967, 653.123094076, 220.65905025]]),\n@@ -299,7 +321,8 @@ def test_campbell_norman():\n assert_frame_equal(out, expected)\n \n \n-def test_get_total_irradiance(irrad_data, ephem_data, dni_et, relative_airmass):\n+def test_get_total_irradiance(irrad_data, ephem_data, dni_et,\n+ relative_airmass):\n models = ['isotropic', 'klucher',\n 'haydavies', 'reindl', 'king', 'perez']\n \n@@ -337,6 +360,30 @@ def test_get_total_irradiance_scalars(model):\n assert np.isnan(np.array(list(total.values()))).sum() == 0\n \n \n+def test_get_total_irradiance_missing_dni_extra():\n+ msg = 'dni_extra is required'\n+ with pytest.raises(ValueError, match=msg):\n+ irradiance.get_total_irradiance(\n+ 32, 180,\n+ 10, 180,\n+ dni=1000, ghi=1100,\n+ dhi=100,\n+ model='haydavies')\n+\n+\n+def test_get_total_irradiance_missing_airmass():\n+ total = irradiance.get_total_irradiance(\n+ 32, 180,\n+ 10, 180,\n+ dni=1000, ghi=1100,\n+ dhi=100,\n+ dni_extra=1400,\n+ model='perez')\n+ assert list(total.keys()) == ['poa_global', 'poa_direct',\n+ 'poa_diffuse', 'poa_sky_diffuse',\n+ 'poa_ground_diffuse']\n+\n+\n def test_poa_components(irrad_data, ephem_data, dni_et, relative_airmass):\n aoi = irradiance.aoi(40, 180, ephem_data['apparent_zenith'],\n ephem_data['azimuth'])\n", "problem_statement": "Improve docstring or behavior for irradiance.get_total_irradiance and irradiance.get_sky_diffuse\n`pvlib.irradiance.get_total_irradiance` accepts kwargs `dni_extra` and `airmass`, both default to `None`. However, values for these kwargs are required for several of the irradiance transposition models. \r\n\r\nSee discussion [here](https://groups.google.com/d/msg/pvlib-python/ZPMdpQOD6F4/cs1t23w8AwAJ)\r\n\r\nDocstring should specify when `dni_extra` and `airmass` are required, and which airmass is appropriate for each model.\r\n\r\nCould also test for kwarg values if e.g. `model=='perez'`\n", "hints_text": "Consider also specifying it is relative airmass.\nThis came up again in @mikofski's thread [here](https://groups.google.com/g/pvlib-python/c/AUQ_hsbL_B8/m/0y83YIRrBgAJ). \r\n\r\n@mikofski proposed calculating values if needed and not provided.\r\n\r\n@kanderso-nrel proposed a couple of solutions to provide more informative error messages: 1. hard coding the failure modes in `get_sky_diffuse` and 2. using a decorator to communicate the failure modes.\r\n\r\nAnd repeating my take from the thread:\r\n\r\nI'd rather not introduce the complexity of decorators to the lower level pvlib functions to solve this problem.\r\n\r\nIdeas that I support:\r\n* calculate if not provided (Mark's original idea)\r\n* reraising a more informative message.\r\n* require all of the arguments in get_sky_diffuse and get_total_irradiance regardless of whether or not they're used.\r\n* remove the arguments from get_sky_diffuse and get_total_irradiance and do the calculation if it's needed\r\n* ~remove get_sky_diffuse and get_total_irradiance. I'm not convinced they're a net positive for the library.~ (let's try to fix it before throwing up our hands)\r\n\r\nDoes someone want to tackle this in 0.8.0 or should we kick it down the road?\nI think it's tempting to add it in v0.8, but I'm in favor of freezing features now and pushing out the release sooner with the features we already have queued. It's been a while, and I think we should deploy more often with less features per release. I believe this will make it easier to blame issues and get more testing done on new features and fixes faster.\nI'll volunteer to take this up for v0.8.1, since I was the complainer.\n`PVSystem.get_irradiance` has some relevant shim code:\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/04a523fafbd61bc2e49420963b84ed8e2bd1b3cf/pvlib/pvsystem.py#L289-L294", "created_at": "2021-05-10T16:32:59Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_airmass", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_airmass"], "PASS_TO_PASS": ["pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_float", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_reindl", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_model_invalid", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1093", "base_commit": "11c356f9a89fc88b4d3ff368ce1aae170a97ebd7", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -1133,7 +1133,7 @@ def prepare_inputs(self, weather):\n ModelChain.complete_irradiance\n \"\"\"\n \n- self._verify_df(weather, required=['ghi', 'dni', 'ghi'])\n+ self._verify_df(weather, required=['ghi', 'dni', 'dhi'])\n self._assign_weather(weather)\n \n self.times = self.weather.index\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -249,6 +249,16 @@ def test_prepare_inputs_no_irradiance(sapm_dc_snl_ac_system, location):\n mc.prepare_inputs(weather)\n \n \[email protected](\"missing\", ['dhi', 'ghi', 'dni'])\n+def test_prepare_inputs_missing_irrad_component(\n+ sapm_dc_snl_ac_system, location, missing):\n+ mc = ModelChain(sapm_dc_snl_ac_system, location)\n+ weather = pd.DataFrame({'dhi': [1, 2], 'dni': [1, 2], 'ghi': [1, 2]})\n+ weather.drop(columns=missing, inplace=True)\n+ with pytest.raises(ValueError):\n+ mc.prepare_inputs(weather)\n+\n+\n def test_run_model_perez(sapm_dc_snl_ac_system, location):\n mc = ModelChain(sapm_dc_snl_ac_system, location,\n transposition_model='perez')\n", "problem_statement": "ModelChain.prepare_inputs can succeed with missing dhi\nFrom the docstring for `ModelChain.prepare_inputs()` I believe the method should fail if `weather` does not have a `dhi` column.\r\n\r\nThe validation checks for `'ghi'` twice, but not `'dhi`'\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/11c356f9a89fc88b4d3ff368ce1aae170a97ebd7/pvlib/modelchain.py#L1136\n", "hints_text": "", "created_at": "2020-11-20T22:36:43Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_infer_temp_model_no_params", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[snlinverter]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[adrinverter]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_deprecated_09[snlinverter]", "pvlib/tests/test_modelchain.py::test_deprecated_09[adrinverter]", "pvlib/tests/test_modelchain.py::test_ModelChain_kwargs_deprecated_09", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1193", "base_commit": "684b2478e4e174c5eeb10d49a709bbe947921abc", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -1519,10 +1519,14 @@ def _prepare_temperature(self, data=None):\n if not isinstance(data, tuple):\n # broadcast data to all arrays\n data = (data,) * self.system.num_arrays\n+ # data is tuple, so temperature_model_parameters must also be\n+ # tuple. system.temperature_model_parameters is reduced to a dict\n+ # if system.num_arrays == 1, so manually access parameters. GH 1192\n+ t_mod_params = tuple(array.temperature_model_parameters\n+ for array in self.system.arrays)\n # find where cell or module temperature is specified in input data\n given_cell_temperature = tuple(itertools.starmap(\n- self._get_cell_temperature,\n- zip(data, poa, self.system.temperature_model_parameters)\n+ self._get_cell_temperature, zip(data, poa, t_mod_params)\n ))\n # If cell temperature has been specified for all arrays return\n # immediately and do not try to compute it.\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -830,6 +830,38 @@ def test__prepare_temperature(sapm_dc_snl_ac_system, location, weather,\n assert_series_equal(mc.results.cell_temperature, data['cell_temperature'])\n \n \n+def test__prepare_temperature_len1_weather_tuple(\n+ sapm_dc_snl_ac_system, location, weather, total_irrad):\n+ # GH 1192\n+ weather['module_temperature'] = [40., 30.]\n+ data = weather.copy()\n+\n+ mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss',\n+ spectral_model='no_loss')\n+ mc.run_model([data])\n+ expected = pd.Series([42.617244212941394, 30.0], index=data.index)\n+ assert_series_equal(mc.results.cell_temperature[0], expected)\n+\n+ data = weather.copy().rename(\n+ columns={\n+ \"ghi\": \"poa_global\", \"dhi\": \"poa_diffuse\", \"dni\": \"poa_direct\"}\n+ )\n+ mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss',\n+ spectral_model='no_loss')\n+ mc.run_model_from_poa([data])\n+ expected = pd.Series([41.5, 30.0], index=data.index)\n+ assert_series_equal(mc.results.cell_temperature[0], expected)\n+\n+ data = weather.copy()[[\"module_temperature\", \"ghi\"]].rename(\n+ columns={\"ghi\": \"effective_irradiance\"}\n+ )\n+ mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss',\n+ spectral_model='no_loss')\n+ mc.run_model_from_effective_irradiance([data])\n+ expected = pd.Series([41.5, 30.0], index=data.index)\n+ assert_series_equal(mc.results.cell_temperature[0], expected)\n+\n+\n def test__prepare_temperature_arrays_weather(sapm_dc_snl_ac_system_same_arrays,\n location, weather,\n total_irrad):\n", "problem_statement": "TypeError: running ModelChain with Arrays and module_temperature\n**Describe the bug**\r\nAnother bug using Arrays. This time a TypeError is raised in `pvlib.modelchain._get_cell_temperature` because `self.system.temperature_model_parameters` is zipped with dataframe tuples but is never a tuple itself\r\nhttps://github.com/pvlib/pvlib-python/blob/dc617d0c182bc8eec57898a039cb5115b425645f/pvlib/modelchain.py#L1525\r\n\r\n**To Reproduce**\r\n```python\r\nimport traceback\r\nimport pandas as pd\r\nfrom pvlib.location import Location\r\nfrom pvlib.pvsystem import Array, PVSystem\r\nfrom pvlib.modelchain import ModelChain\r\n\r\n\r\narray_params = {\r\n \"surface_tilt\": 32.0,\r\n \"surface_azimuth\": 180.0,\r\n \"module\": \"Canadian_Solar_Inc__CS5P_220M\",\r\n \"albedo\": 0.2,\r\n \"temperature_model_parameters\": {\r\n \"a\": -3.47,\r\n \"b\": -0.0594,\r\n \"deltaT\": 3.0,\r\n },\r\n \"strings\": 5,\r\n \"modules_per_string\": 7,\r\n \"module_parameters\": {\r\n \"alpha_sc\": 0.004539,\r\n \"gamma_ref\": 1.2,\r\n \"mu_gamma\": -0.003,\r\n \"I_L_ref\": 5.11426,\r\n \"I_o_ref\": 8.10251e-10,\r\n \"R_sh_ref\": 381.254,\r\n \"R_sh_0\": 400.0,\r\n \"R_s\": 1.06602,\r\n \"cells_in_series\": 96,\r\n \"R_sh_exp\": 5.5,\r\n \"EgRef\": 1.121,\r\n },\r\n}\r\ninverter_parameters = {\r\n \"Paco\": 250.0,\r\n \"Pdco\": 259.589,\r\n \"Vdco\": 40.0,\r\n \"Pso\": 2.08961,\r\n \"C0\": -4.1e-05,\r\n \"C1\": -9.1e-05,\r\n \"C2\": 0.000494,\r\n \"C3\": -0.013171,\r\n \"Pnt\": 0.075,\r\n}\r\n\r\n\r\nlocation = Location(latitude=33.98, longitude=-115.323, altitude=2300)\r\n\r\narray_sys = PVSystem(\r\n arrays=[\r\n Array(**array_params, name=0),\r\n ],\r\n inverter_parameters=inverter_parameters,\r\n)\r\npoa = pd.DataFrame(\r\n {\r\n \"poa_global\": [1100.0, 1101.0],\r\n \"poa_direct\": [1000.0, 1001.0],\r\n \"poa_diffuse\": [100.0, 100.0],\r\n \"module_temperature\": [35.0, 33.0],\r\n },\r\n index=pd.DatetimeIndex(\r\n [pd.Timestamp(\"2021-01-20T12:00-05:00\"), pd.Timestamp(\"2021-01-20T12:05-05:00\")]\r\n ),\r\n)\r\nstandard = poa.copy().rename(\r\n columns={\"poa_global\": \"ghi\", \"poa_direct\": \"dni\", \"poa_diffuse\": \"dhi\"}\r\n)\r\neffective = poa.copy()[[\"module_temperature\", \"poa_global\"]].rename(\r\n columns={\"poa_global\": \"effective_irradiance\"}\r\n)\r\nmc = ModelChain(\r\n array_sys,\r\n location,\r\n aoi_model=\"no_loss\",\r\n spectral_model=\"no_loss\",\r\n)\r\ntry:\r\n mc.run_model([standard])\r\nexcept TypeError:\r\n print(traceback.format_exc())\r\nelse:\r\n raise RuntimeError(\"expected a type error\")\r\ntry:\r\n mc.run_model_from_poa([poa])\r\nexcept TypeError:\r\n print(traceback.format_exc())\r\nelse:\r\n raise RuntimeError(\"expected a type error\")\r\ntry:\r\n mc.run_model_from_effective_irradiance([effective])\r\nexcept TypeError:\r\n print(traceback.format_exc())\r\nelse:\r\n raise RuntimeError(\"expected a type error\")\r\n\r\n```\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: master/g684b247\r\n\n", "hints_text": "", "created_at": "2021-03-12T03:55:07Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test__prepare_temperature_len1_weather_tuple"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_run_model_tracker_list", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1176", "base_commit": "f80068c86b9fc14c9395b52fac39a8e9fae5ef27", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -11,6 +11,9 @@\n from urllib.request import urlopen\n import numpy as np\n import pandas as pd\n+from dataclasses import dataclass\n+from abc import ABC, abstractmethod\n+from typing import Optional\n \n from pvlib._deprecation import deprecated\n \n@@ -234,8 +237,7 @@ def __init__(self,\n array_losses_parameters = _build_kwargs(['dc_ohmic_percent'],\n losses_parameters)\n self.arrays = (Array(\n- surface_tilt,\n- surface_azimuth,\n+ FixedMount(surface_tilt, surface_azimuth, racking_model),\n albedo,\n surface_type,\n module,\n@@ -244,7 +246,6 @@ def __init__(self,\n temperature_model_parameters,\n modules_per_string,\n strings_per_inverter,\n- racking_model,\n array_losses_parameters,\n ),)\n elif len(arrays) == 0:\n@@ -299,7 +300,6 @@ def _validate_per_array(self, values, system_wide=False):\n \n @_unwrap_single_value\n def _infer_cell_type(self):\n-\n \"\"\"\n Examines module_parameters and maps the Technology key for the CEC\n database and the Material key for the Sandia database to a common\n@@ -813,11 +813,13 @@ def fuentes_celltemp(self, poa_global, temp_air, wind_speed):\n The Fuentes thermal model uses the module surface tilt for convection\n modeling. The SAM implementation of PVWatts hardcodes the surface tilt\n value at 30 degrees, ignoring whatever value is used for irradiance\n- transposition. This method defaults to using ``self.surface_tilt``, but\n- if you want to match the PVWatts behavior, you can override it by\n- including a ``surface_tilt`` value in ``temperature_model_parameters``.\n+ transposition. If you want to match the PVWatts behavior you can\n+ either leave ``surface_tilt`` unspecified to use the PVWatts default\n+ of 30, or specify a ``surface_tilt`` value in the Array's\n+ ``temperature_model_parameters``.\n \n- The `temp_air` and `wind_speed` parameters may be passed as tuples\n+ The `temp_air`, `wind_speed`, and `surface_tilt` parameters may be\n+ passed as tuples\n to provide different values for each Array in the system. If not\n passed as a tuple then the same value is used for input to each Array.\n If passed as a tuple the length must be the same as the number of\n@@ -867,7 +869,6 @@ def noct_sam_celltemp(self, poa_global, temp_air, wind_speed,\n \n @_unwrap_single_value\n def first_solar_spectral_loss(self, pw, airmass_absolute):\n-\n \"\"\"\n Use the :py:func:`first_solar_spectral_correction` function to\n calculate the spectral loss modifier. The model coefficients are\n@@ -1165,25 +1166,25 @@ def temperature_model_parameters(self, value):\n @_unwrap_single_value\n @_check_deprecated_passthrough\n def surface_tilt(self):\n- return tuple(array.surface_tilt for array in self.arrays)\n+ return tuple(array.mount.surface_tilt for array in self.arrays)\n \n @surface_tilt.setter\n @_check_deprecated_passthrough\n def surface_tilt(self, value):\n for array in self.arrays:\n- array.surface_tilt = value\n+ array.mount.surface_tilt = value\n \n @property\n @_unwrap_single_value\n @_check_deprecated_passthrough\n def surface_azimuth(self):\n- return tuple(array.surface_azimuth for array in self.arrays)\n+ return tuple(array.mount.surface_azimuth for array in self.arrays)\n \n @surface_azimuth.setter\n @_check_deprecated_passthrough\n def surface_azimuth(self, value):\n for array in self.arrays:\n- array.surface_azimuth = value\n+ array.mount.surface_azimuth = value\n \n @property\n @_unwrap_single_value\n@@ -1201,13 +1202,13 @@ def albedo(self, value):\n @_unwrap_single_value\n @_check_deprecated_passthrough\n def racking_model(self):\n- return tuple(array.racking_model for array in self.arrays)\n+ return tuple(array.mount.racking_model for array in self.arrays)\n \n @racking_model.setter\n @_check_deprecated_passthrough\n def racking_model(self, value):\n for array in self.arrays:\n- array.racking_model = value\n+ array.mount.racking_model = value\n \n @property\n @_unwrap_single_value\n@@ -1243,20 +1244,16 @@ class Array:\n \"\"\"\n An Array is a set of of modules at the same orientation.\n \n- Specifically, an array is defined by tilt, azimuth, the\n+ Specifically, an array is defined by its mount, the\n module parameters, the number of parallel strings of modules\n and the number of modules on each string.\n \n Parameters\n ----------\n- surface_tilt: float or array-like, default 0\n- Surface tilt angles in decimal degrees.\n- The tilt angle is defined as degrees from horizontal\n- (e.g. surface facing up = 0, surface facing horizon = 90)\n-\n- surface_azimuth: float or array-like, default 180\n- Azimuth angle of the module surface.\n- North=0, East=90, South=180, West=270.\n+ mount: FixedMount, SingleAxisTrackerMount, or other\n+ Mounting for the array, either on fixed-tilt racking or horizontal\n+ single axis tracker. Mounting is used to determine module orientation.\n+ If not provided, a FixedMount with zero tilt is used.\n \n albedo : None or float, default None\n The ground albedo. If ``None``, will attempt to use\n@@ -1290,26 +1287,22 @@ class Array:\n strings: int, default 1\n Number of parallel strings in the array.\n \n- racking_model : None or string, default None\n- Valid strings are 'open_rack', 'close_mount', and 'insulated_back'.\n- Used to identify a parameter set for the SAPM cell temperature model.\n-\n array_losses_parameters: None, dict or Series, default None.\n Supported keys are 'dc_ohmic_percent'.\n \n+ name: None or str, default None\n+ Name of Array instance.\n \"\"\"\n \n- def __init__(self,\n- surface_tilt=0, surface_azimuth=180,\n+ def __init__(self, mount,\n albedo=None, surface_type=None,\n module=None, module_type=None,\n module_parameters=None,\n temperature_model_parameters=None,\n modules_per_string=1, strings=1,\n- racking_model=None, array_losses_parameters=None,\n+ array_losses_parameters=None,\n name=None):\n- self.surface_tilt = surface_tilt\n- self.surface_azimuth = surface_azimuth\n+ self.mount = mount\n \n self.surface_type = surface_type\n if albedo is None:\n@@ -1324,7 +1317,6 @@ def __init__(self,\n self.module_parameters = module_parameters\n \n self.module_type = module_type\n- self.racking_model = racking_model\n \n self.strings = strings\n self.modules_per_string = modules_per_string\n@@ -1343,10 +1335,11 @@ def __init__(self,\n self.name = name\n \n def __repr__(self):\n- attrs = ['name', 'surface_tilt', 'surface_azimuth', 'module',\n- 'albedo', 'racking_model', 'module_type',\n+ attrs = ['name', 'mount', 'module',\n+ 'albedo', 'module_type',\n 'temperature_model_parameters',\n 'strings', 'modules_per_string']\n+\n return 'Array:\\n ' + '\\n '.join(\n f'{attr}: {getattr(self, attr)}' for attr in attrs\n )\n@@ -1354,7 +1347,7 @@ def __repr__(self):\n def _infer_temperature_model_params(self):\n # try to infer temperature model parameters from from racking_model\n # and module_type\n- param_set = f'{self.racking_model}_{self.module_type}'\n+ param_set = f'{self.mount.racking_model}_{self.module_type}'\n if param_set in temperature.TEMPERATURE_MODEL_PARAMETERS['sapm']:\n return temperature._temperature_model_params('sapm', param_set)\n elif 'freestanding' in param_set:\n@@ -1424,7 +1417,9 @@ def get_aoi(self, solar_zenith, solar_azimuth):\n aoi : Series\n Then angle of incidence.\n \"\"\"\n- return irradiance.aoi(self.surface_tilt, self.surface_azimuth,\n+ orientation = self.mount.get_orientation(solar_zenith, solar_azimuth)\n+ return irradiance.aoi(orientation['surface_tilt'],\n+ orientation['surface_azimuth'],\n solar_zenith, solar_azimuth)\n \n def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n@@ -1473,8 +1468,9 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n if airmass is None:\n airmass = atmosphere.get_relative_airmass(solar_zenith)\n \n- return irradiance.get_total_irradiance(self.surface_tilt,\n- self.surface_azimuth,\n+ orientation = self.mount.get_orientation(solar_zenith, solar_azimuth)\n+ return irradiance.get_total_irradiance(orientation['surface_tilt'],\n+ orientation['surface_azimuth'],\n solar_zenith, solar_azimuth,\n dni, ghi, dhi,\n dni_extra=dni_extra,\n@@ -1595,13 +1591,11 @@ def get_cell_temperature(self, poa_global, temp_air, wind_speed, model,\n func = temperature.fuentes\n required = _build_tcell_args(['noct_installed'])\n optional = _build_kwargs([\n- 'module_height', 'wind_height', 'emissivity', 'absorption',\n+ 'wind_height', 'emissivity', 'absorption',\n 'surface_tilt', 'module_width', 'module_length'],\n self.temperature_model_parameters)\n- # default to using the Array attribute, but allow user to override\n- # with a custom surface_tilt value in temperature_model_parameters\n- if 'surface_tilt' not in optional:\n- optional['surface_tilt'] = self.surface_tilt\n+ if self.mount.module_height is not None:\n+ optional['module_height'] = self.mount.module_height\n elif model == 'noct_sam':\n func = functools.partial(temperature.noct_sam,\n effective_irradiance=effective_irradiance)\n@@ -1683,6 +1677,145 @@ def dc_ohms_from_percent(self):\n self.strings)\n \n \n+@dataclass\n+class AbstractMount(ABC):\n+ \"\"\"\n+ A base class for Mount classes to extend. It is not intended to be\n+ instantiated directly.\n+ \"\"\"\n+\n+ @abstractmethod\n+ def get_orientation(self, solar_zenith, solar_azimuth):\n+ \"\"\"\n+ Determine module orientation.\n+\n+ Parameters\n+ ----------\n+ solar_zenith : numeric\n+ Solar apparent zenith angle [degrees]\n+ solar_azimuth : numeric\n+ Solar azimuth angle [degrees]\n+\n+ Returns\n+ -------\n+ orientation : dict-like\n+ A dict-like object with keys `'surface_tilt', 'surface_azimuth'`\n+ (typically a dict or pandas.DataFrame)\n+ \"\"\"\n+\n+\n+@dataclass\n+class FixedMount(AbstractMount):\n+ \"\"\"\n+ Racking at fixed (static) orientation.\n+\n+ Parameters\n+ ----------\n+ surface_tilt : float, default 0\n+ Surface tilt angle. The tilt angle is defined as angle from horizontal\n+ (e.g. surface facing up = 0, surface facing horizon = 90) [degrees]\n+\n+ surface_azimuth : float, default 180\n+ Azimuth angle of the module surface. North=0, East=90, South=180,\n+ West=270. [degrees]\n+\n+ racking_model : str, optional\n+ Valid strings are 'open_rack', 'close_mount', and 'insulated_back'.\n+ Used to identify a parameter set for the SAPM cell temperature model.\n+\n+ module_height : float, optional\n+ The height above ground of the center of the module [m]. Used for\n+ the Fuentes cell temperature model.\n+ \"\"\"\n+\n+ surface_tilt: float = 0.0\n+ surface_azimuth: float = 180.0\n+ racking_model: Optional[str] = None\n+ module_height: Optional[float] = None\n+\n+ def get_orientation(self, solar_zenith, solar_azimuth):\n+ # note -- docstring is automatically inherited from AbstractMount\n+ return {\n+ 'surface_tilt': self.surface_tilt,\n+ 'surface_azimuth': self.surface_azimuth,\n+ }\n+\n+\n+@dataclass\n+class SingleAxisTrackerMount(AbstractMount):\n+ \"\"\"\n+ Single-axis tracker racking for dynamic solar tracking.\n+\n+ Parameters\n+ ----------\n+ axis_tilt : float, default 0\n+ The tilt of the axis of rotation (i.e, the y-axis defined by\n+ axis_azimuth) with respect to horizontal. [degrees]\n+\n+ axis_azimuth : float, default 180\n+ A value denoting the compass direction along which the axis of\n+ rotation lies, measured east of north. [degrees]\n+\n+ max_angle : float, default 90\n+ A value denoting the maximum rotation angle\n+ of the one-axis tracker from its horizontal position (horizontal\n+ if axis_tilt = 0). A max_angle of 90 degrees allows the tracker\n+ to rotate to a vertical position to point the panel towards a\n+ horizon. max_angle of 180 degrees allows for full rotation. [degrees]\n+\n+ backtrack : bool, default True\n+ Controls whether the tracker has the capability to \"backtrack\"\n+ to avoid row-to-row shading. False denotes no backtrack\n+ capability. True denotes backtrack capability.\n+\n+ gcr : float, default 2.0/7.0\n+ A value denoting the ground coverage ratio of a tracker system\n+ which utilizes backtracking; i.e. the ratio between the PV array\n+ surface area to total ground area. A tracker system with modules\n+ 2 meters wide, centered on the tracking axis, with 6 meters\n+ between the tracking axes has a gcr of 2/6=0.333. If gcr is not\n+ provided, a gcr of 2/7 is default. gcr must be <=1. [unitless]\n+\n+ cross_axis_tilt : float, default 0.0\n+ The angle, relative to horizontal, of the line formed by the\n+ intersection between the slope containing the tracker axes and a plane\n+ perpendicular to the tracker axes. Cross-axis tilt should be specified\n+ using a right-handed convention. For example, trackers with axis\n+ azimuth of 180 degrees (heading south) will have a negative cross-axis\n+ tilt if the tracker axes plane slopes down to the east and positive\n+ cross-axis tilt if the tracker axes plane slopes up to the east. Use\n+ :func:`~pvlib.tracking.calc_cross_axis_tilt` to calculate\n+ `cross_axis_tilt`. [degrees]\n+\n+ racking_model : str, optional\n+ Valid strings are 'open_rack', 'close_mount', and 'insulated_back'.\n+ Used to identify a parameter set for the SAPM cell temperature model.\n+\n+ module_height : float, optional\n+ The height above ground of the center of the module [m]. Used for\n+ the Fuentes cell temperature model.\n+ \"\"\"\n+ axis_tilt: float = 0.0\n+ axis_azimuth: float = 0.0\n+ max_angle: float = 90.0\n+ backtrack: bool = True\n+ gcr: float = 2.0/7.0\n+ cross_axis_tilt: float = 0.0\n+ racking_model: Optional[str] = None\n+ module_height: Optional[float] = None\n+\n+ def get_orientation(self, solar_zenith, solar_azimuth):\n+ # note -- docstring is automatically inherited from AbstractMount\n+ from pvlib import tracking # avoid circular import issue\n+ tracking_data = tracking.singleaxis(\n+ solar_zenith, solar_azimuth,\n+ self.axis_tilt, self.axis_azimuth,\n+ self.max_angle, self.backtrack,\n+ self.gcr, self.cross_axis_tilt\n+ )\n+ return tracking_data\n+\n+\n def calcparams_desoto(effective_irradiance, temp_cell,\n alpha_sc, a_ref, I_L_ref, I_o_ref, R_sh_ref, R_s,\n EgRef=1.121, dEgdT=-0.0002677,\ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -2,10 +2,14 @@\n import pandas as pd\n \n from pvlib.tools import cosd, sind, tand\n-from pvlib.pvsystem import PVSystem, _unwrap_single_value\n+from pvlib.pvsystem import (\n+ PVSystem, Array, SingleAxisTrackerMount, _unwrap_single_value\n+)\n from pvlib import irradiance, atmosphere\n+from pvlib._deprecation import deprecated\n \n \n+@deprecated('0.9.0', alternative='PVSystem with SingleAxisTrackerMount')\n class SingleAxisTracker(PVSystem):\n \"\"\"\n A class for single-axis trackers that inherits the PV modeling methods from\n@@ -76,20 +80,31 @@ class SingleAxisTracker(PVSystem):\n def __init__(self, axis_tilt=0, axis_azimuth=0, max_angle=90,\n backtrack=True, gcr=2.0/7.0, cross_axis_tilt=0.0, **kwargs):\n \n- arrays = kwargs.get('arrays', [])\n- if len(arrays) > 1:\n- raise ValueError(\"SingleAxisTracker does not support \"\n- \"multiple arrays.\")\n- elif len(arrays) == 1:\n- surface_tilt = arrays[0].surface_tilt\n- surface_azimuth = arrays[0].surface_azimuth\n- if surface_tilt is not None or surface_azimuth is not None:\n- raise ValueError(\n- \"Array must not have surface_tilt or \"\n- \"surface_azimuth assigned. You must pass an \"\n- \"Array with these fields set to None.\"\n- )\n-\n+ mount_kwargs = {\n+ k: kwargs.pop(k) for k in ['racking_model', 'module_height']\n+ if k in kwargs\n+ }\n+ mount = SingleAxisTrackerMount(axis_tilt, axis_azimuth, max_angle,\n+ backtrack, gcr, cross_axis_tilt,\n+ **mount_kwargs)\n+\n+ array_defaults = {\n+ 'albedo': None, 'surface_type': None, 'module': None,\n+ 'module_type': None, 'module_parameters': None,\n+ 'temperature_model_parameters': None,\n+ 'modules_per_string': 1,\n+ }\n+ array_kwargs = {\n+ key: kwargs.get(key, array_defaults[key]) for key in array_defaults\n+ }\n+ # strings/strings_per_inverter is a special case\n+ array_kwargs['strings'] = kwargs.get('strings_per_inverter', 1)\n+\n+ array = Array(mount=mount, **array_kwargs)\n+ pass_through_kwargs = { # other args to pass to PVSystem()\n+ k: v for k, v in kwargs.items() if k not in array_defaults\n+ }\n+ # leave these in case someone is using them\n self.axis_tilt = axis_tilt\n self.axis_azimuth = axis_azimuth\n self.max_angle = max_angle\n@@ -97,10 +112,10 @@ def __init__(self, axis_tilt=0, axis_azimuth=0, max_angle=90,\n self.gcr = gcr\n self.cross_axis_tilt = cross_axis_tilt\n \n- kwargs['surface_tilt'] = None\n- kwargs['surface_azimuth'] = None\n+ pass_through_kwargs['surface_tilt'] = None\n+ pass_through_kwargs['surface_azimuth'] = None\n \n- super().__init__(**kwargs)\n+ super().__init__(arrays=[array], **pass_through_kwargs)\n \n def __repr__(self):\n attrs = ['axis_tilt', 'axis_azimuth', 'max_angle', 'backtrack', 'gcr',\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -55,13 +55,13 @@ def cec_dc_snl_ac_arrays(cec_module_cs5p_220m, cec_inverter_parameters,\n module_parameters['dEgdT'] = -0.0002677\n temp_model_params = sapm_temperature_cs5p_220m.copy()\n array_one = pvsystem.Array(\n- surface_tilt=32.2, surface_azimuth=180,\n+ mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180),\n module=module_parameters['Name'],\n module_parameters=module_parameters.copy(),\n temperature_model_parameters=temp_model_params.copy()\n )\n array_two = pvsystem.Array(\n- surface_tilt=42.2, surface_azimuth=220,\n+ mount=pvsystem.FixedMount(surface_tilt=42.2, surface_azimuth=220),\n module=module_parameters['Name'],\n module_parameters=module_parameters.copy(),\n temperature_model_parameters=temp_model_params.copy()\n@@ -109,13 +109,13 @@ def pvsyst_dc_snl_ac_arrays(pvsyst_module_params, cec_inverter_parameters,\n module_parameters['b'] = 0.05\n temp_model_params = sapm_temperature_cs5p_220m.copy()\n array_one = pvsystem.Array(\n- surface_tilt=32.2, surface_azimuth=180,\n+ mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180),\n module=module,\n module_parameters=module_parameters.copy(),\n temperature_model_parameters=temp_model_params.copy()\n )\n array_two = pvsystem.Array(\n- surface_tilt=42.2, surface_azimuth=220,\n+ mount=pvsystem.FixedMount(surface_tilt=42.2, surface_azimuth=220),\n module=module,\n module_parameters=module_parameters.copy(),\n temperature_model_parameters=temp_model_params.copy()\n@@ -172,12 +172,12 @@ def pvwatts_dc_pvwatts_ac_system_arrays(sapm_temperature_cs5p_220m):\n temp_model_params = sapm_temperature_cs5p_220m.copy()\n inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95}\n array_one = pvsystem.Array(\n- surface_tilt=32.2, surface_azimuth=180,\n+ mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180),\n module_parameters=module_parameters.copy(),\n temperature_model_parameters=temp_model_params.copy()\n )\n array_two = pvsystem.Array(\n- surface_tilt=42.2, surface_azimuth=220,\n+ mount=pvsystem.FixedMount(surface_tilt=42.2, surface_azimuth=220),\n module_parameters=module_parameters.copy(),\n temperature_model_parameters=temp_model_params.copy()\n )\n@@ -288,13 +288,15 @@ def sapm_dc_snl_ac_system_Array(sapm_module_params, cec_inverter_parameters,\n module = 'Canadian_Solar_CS5P_220M___2009_'\n module_parameters = sapm_module_params.copy()\n temp_model_params = sapm_temperature_cs5p_220m.copy()\n- array_one = pvsystem.Array(surface_tilt=32, surface_azimuth=180,\n+ array_one = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=32,\n+ surface_azimuth=180),\n albedo=0.2, module=module,\n module_parameters=module_parameters,\n temperature_model_parameters=temp_model_params,\n modules_per_string=1,\n strings=1)\n- array_two = pvsystem.Array(surface_tilt=15, surface_azimuth=180,\n+ array_two = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=15,\n+ surface_azimuth=180),\n albedo=0.2, module=module,\n module_parameters=module_parameters,\n temperature_model_parameters=temp_model_params,\n@@ -312,13 +314,15 @@ def sapm_dc_snl_ac_system_same_arrays(sapm_module_params,\n module = 'Canadian_Solar_CS5P_220M___2009_'\n module_parameters = sapm_module_params.copy()\n temp_model_params = sapm_temperature_cs5p_220m.copy()\n- array_one = pvsystem.Array(surface_tilt=32.2, surface_azimuth=180,\n+ array_one = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=32.2,\n+ surface_azimuth=180),\n module=module,\n module_parameters=module_parameters,\n temperature_model_parameters=temp_model_params,\n modules_per_string=1,\n strings=1)\n- array_two = pvsystem.Array(surface_tilt=32.2, surface_azimuth=180,\n+ array_two = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=32.2,\n+ surface_azimuth=180),\n module=module,\n module_parameters=module_parameters,\n temperature_model_parameters=temp_model_params,\n@@ -365,12 +369,12 @@ def multi_array_sapm_dc_snl_ac_system(\n temp_model_parameters = sapm_temperature_cs5p_220m.copy()\n inverter_parameters = cec_inverter_parameters\n array_one = pvsystem.Array(\n- surface_tilt=32.2, surface_azimuth=180,\n+ mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180),\n module_parameters=module_parameters,\n temperature_model_parameters=temp_model_parameters\n )\n array_two = pvsystem.Array(\n- surface_tilt=32.2, surface_azimuth=220,\n+ mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=220),\n module_parameters=module_parameters,\n temperature_model_parameters=temp_model_parameters\n )\n@@ -696,7 +700,7 @@ def test_run_model_with_weather_fuentes_temp(sapm_dc_snl_ac_system, location,\n weather['wind_speed'] = 5\n weather['temp_air'] = 10\n sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters = {\n- 'noct_installed': 45\n+ 'noct_installed': 45, 'surface_tilt': 30,\n }\n mc = ModelChain(sapm_dc_snl_ac_system, location)\n mc.temperature_model = 'fuentes'\n@@ -730,12 +734,13 @@ def test_run_model_with_weather_noct_sam_temp(sapm_dc_snl_ac_system, location,\n \n \n def test_run_model_tracker(sapm_dc_snl_ac_system, location, weather, mocker):\n- system = SingleAxisTracker(\n- module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters,\n- temperature_model_parameters=(\n- sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters\n- ),\n- inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ system = SingleAxisTracker(\n+ module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters, # noqa: E501\n+ temperature_model_parameters=(\n+ sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters\n+ ),\n+ inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters)\n mocker.spy(system, 'singleaxis')\n mc = ModelChain(system, location)\n mc.run_model(weather)\n@@ -751,12 +756,13 @@ def test_run_model_tracker(sapm_dc_snl_ac_system, location, weather, mocker):\n \n def test_run_model_tracker_list(\n sapm_dc_snl_ac_system, location, weather, mocker):\n- system = SingleAxisTracker(\n- module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters,\n- temperature_model_parameters=(\n- sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters\n- ),\n- inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ system = SingleAxisTracker(\n+ module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters, # noqa: E501\n+ temperature_model_parameters=(\n+ sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters\n+ ),\n+ inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters)\n mocker.spy(system, 'singleaxis')\n mc = ModelChain(system, location)\n mc.run_model([weather])\n@@ -1023,12 +1029,13 @@ def test_run_model_from_poa_arrays_solar_position_weather(\n \n def test_run_model_from_poa_tracking(sapm_dc_snl_ac_system, location,\n total_irrad):\n- system = SingleAxisTracker(\n- module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters,\n- temperature_model_parameters=(\n- sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters\n- ),\n- inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ system = SingleAxisTracker(\n+ module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters, # noqa: E501\n+ temperature_model_parameters=(\n+ sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters\n+ ),\n+ inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters)\n mc = ModelChain(system, location, aoi_model='no_loss',\n spectral_model='no_loss')\n ac = mc.run_model_from_poa(total_irrad).results.ac\n@@ -1439,6 +1446,7 @@ def test_infer_ac_model_invalid_params(location):\n module_parameters = {'pdc0': 1, 'gamma_pdc': 1}\n system = pvsystem.PVSystem(\n arrays=[pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters=module_parameters\n )],\n inverter_parameters={'foo': 1, 'bar': 2}\n@@ -1953,10 +1961,13 @@ def test_inconsistent_array_params(location,\n different_module_system = pvsystem.PVSystem(\n arrays=[\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters=sapm_module_params),\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters=cec_module_params),\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters=cec_module_params)]\n )\n with pytest.raises(ValueError, match=module_error):\n@@ -1964,16 +1975,19 @@ def test_inconsistent_array_params(location,\n different_temp_system = pvsystem.PVSystem(\n arrays=[\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters=cec_module_params,\n temperature_model_parameters={'a': 1,\n 'b': 1,\n 'deltaT': 1}),\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters=cec_module_params,\n temperature_model_parameters={'a': 2,\n 'b': 2,\n 'deltaT': 2}),\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters=cec_module_params,\n temperature_model_parameters={'b': 3, 'deltaT': 3})]\n )\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -15,6 +15,7 @@\n from pvlib import iam as _iam\n from pvlib import irradiance\n from pvlib.location import Location\n+from pvlib.pvsystem import FixedMount\n from pvlib import temperature\n from pvlib._deprecation import pvlibDeprecationWarning\n \n@@ -36,8 +37,10 @@ def test_PVSystem_get_iam(mocker, iam_model, model_params):\n def test_PVSystem_multi_array_get_iam():\n model_params = {'b': 0.05}\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(module_parameters=model_params),\n- pvsystem.Array(module_parameters=model_params)]\n+ arrays=[pvsystem.Array(mount=pvsystem.FixedMount(0, 180),\n+ module_parameters=model_params),\n+ pvsystem.Array(mount=pvsystem.FixedMount(0, 180),\n+ module_parameters=model_params)]\n )\n iam = system.get_iam((1, 5), iam_model='ashrae')\n assert len(iam) == 2\n@@ -226,8 +229,10 @@ def test_PVSystem_sapm(sapm_module_params, mocker):\n \n def test_PVSystem_multi_array_sapm(sapm_module_params):\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(module_parameters=sapm_module_params),\n- pvsystem.Array(module_parameters=sapm_module_params)]\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ module_parameters=sapm_module_params),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ module_parameters=sapm_module_params)]\n )\n effective_irradiance = (100, 500)\n temp_cell = (15, 25)\n@@ -274,8 +279,10 @@ def test_PVSystem_sapm_spectral_loss(sapm_module_params, mocker):\n \n def test_PVSystem_multi_array_sapm_spectral_loss(sapm_module_params):\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(module_parameters=sapm_module_params),\n- pvsystem.Array(module_parameters=sapm_module_params)]\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ module_parameters=sapm_module_params),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ module_parameters=sapm_module_params)]\n )\n loss_one, loss_two = system.sapm_spectral_loss(2)\n assert loss_one == loss_two\n@@ -308,10 +315,12 @@ def test_PVSystem_multi_array_first_solar_spectral_loss():\n system = pvsystem.PVSystem(\n arrays=[\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters={'Technology': 'mc-Si'},\n module_type='multisi'\n ),\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n module_parameters={'Technology': 'mc-Si'},\n module_type='multisi'\n )\n@@ -363,8 +372,10 @@ def test_PVSystem_sapm_effective_irradiance(sapm_module_params, mocker):\n \n def test_PVSystem_multi_array_sapm_effective_irradiance(sapm_module_params):\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(module_parameters=sapm_module_params),\n- pvsystem.Array(module_parameters=sapm_module_params)]\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ module_parameters=sapm_module_params),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ module_parameters=sapm_module_params)]\n )\n poa_direct = (500, 900)\n poa_diffuse = (50, 100)\n@@ -397,10 +408,12 @@ def two_array_system(pvsyst_module_params, cec_module_params):\n return pvsystem.PVSystem(\n arrays=[\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n temperature_model_parameters=temperature_model,\n module_parameters=module_params\n ),\n pvsystem.Array(\n+ mount=pvsystem.FixedMount(0, 180),\n temperature_model_parameters=temperature_model,\n module_parameters=module_params\n )\n@@ -457,8 +470,10 @@ def test_PVSystem_multi_array_sapm_celltemp_different_arrays():\n temp_model_two = temperature.TEMPERATURE_MODEL_PARAMETERS['sapm'][\n 'close_mount_glass_glass']\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(temperature_model_parameters=temp_model_one),\n- pvsystem.Array(temperature_model_parameters=temp_model_two)]\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ temperature_model_parameters=temp_model_one),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ temperature_model_parameters=temp_model_two)]\n )\n temp_one, temp_two = system.get_cell_temperature(\n (1000, 1000), 25, 1, model='sapm'\n@@ -555,6 +570,7 @@ def test_PVSystem_multi_array_celltemp_functions(model, two_array_system):\n irrad_two = pd.Series(500, index=times)\n temp_air = pd.Series(25, index=times)\n wind_speed = pd.Series(1, index=times)\n+\n temp_one, temp_two = two_array_system.get_cell_temperature(\n (irrad_one, irrad_two), temp_air, wind_speed, model=model)\n assert (temp_one != temp_two).all()\n@@ -667,7 +683,7 @@ def test_PVSystem_multi_array_celltemp_poa_length_mismatch(\n \n def test_PVSystem_fuentes_celltemp(mocker):\n noct_installed = 45\n- temp_model_params = {'noct_installed': noct_installed}\n+ temp_model_params = {'noct_installed': noct_installed, 'surface_tilt': 0}\n system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params)\n spy = mocker.spy(temperature, 'fuentes')\n index = pd.date_range('2019-01-01 11:00', freq='h', periods=3)\n@@ -683,47 +699,38 @@ def test_PVSystem_fuentes_celltemp(mocker):\n name='tmod'))\n \n \n-def test_PVSystem_fuentes_celltemp_override(mocker):\n- # test that the surface_tilt value in the cell temp calculation can be\n- # overridden but defaults to the surface_tilt attribute of the PVSystem\n+def test_PVSystem_fuentes_module_height(mocker):\n+ # check that fuentes picks up Array.mount.module_height correctly\n+ # (temperature.fuentes defaults to 5 for module_height)\n+ array = pvsystem.Array(mount=FixedMount(module_height=3),\n+ temperature_model_parameters={'noct_installed': 45})\n spy = mocker.spy(temperature, 'fuentes')\n-\n- noct_installed = 45\n index = pd.date_range('2019-01-01 11:00', freq='h', periods=3)\n temps = pd.Series(25, index)\n irrads = pd.Series(1000, index)\n winds = pd.Series(1, index)\n-\n- # uses default value\n- temp_model_params = {'noct_installed': noct_installed}\n- system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params,\n- surface_tilt=20)\n- system.get_cell_temperature(irrads, temps, winds, model='fuentes')\n- assert spy.call_args[1]['surface_tilt'] == 20\n-\n- # can be overridden\n- temp_model_params = {'noct_installed': noct_installed, 'surface_tilt': 30}\n- system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params,\n- surface_tilt=20)\n- system.get_cell_temperature(irrads, temps, winds, model='fuentes')\n- assert spy.call_args[1]['surface_tilt'] == 30\n+ _ = array.get_cell_temperature(irrads, temps, winds, model='fuentes')\n+ assert spy.call_args[1]['module_height'] == 3\n \n \n def test_Array__infer_temperature_model_params():\n- array = pvsystem.Array(module_parameters={},\n- racking_model='open_rack',\n+ array = pvsystem.Array(mount=FixedMount(0, 180,\n+ racking_model='open_rack'),\n+ module_parameters={},\n module_type='glass_polymer')\n expected = temperature.TEMPERATURE_MODEL_PARAMETERS[\n 'sapm']['open_rack_glass_polymer']\n assert expected == array._infer_temperature_model_params()\n- array = pvsystem.Array(module_parameters={},\n- racking_model='freestanding',\n+ array = pvsystem.Array(mount=FixedMount(0, 180,\n+ racking_model='freestanding'),\n+ module_parameters={},\n module_type='glass_polymer')\n expected = temperature.TEMPERATURE_MODEL_PARAMETERS[\n 'pvsyst']['freestanding']\n assert expected == array._infer_temperature_model_params()\n- array = pvsystem.Array(module_parameters={},\n- racking_model='insulated',\n+ array = pvsystem.Array(mount=FixedMount(0, 180,\n+ racking_model='insulated'),\n+ module_parameters={},\n module_type=None)\n expected = temperature.TEMPERATURE_MODEL_PARAMETERS[\n 'pvsyst']['insulated']\n@@ -731,7 +738,8 @@ def test_Array__infer_temperature_model_params():\n \n \n def test_Array__infer_cell_type():\n- array = pvsystem.Array(module_parameters={})\n+ array = pvsystem.Array(mount=pvsystem.FixedMount(0, 180),\n+ module_parameters={})\n assert array._infer_cell_type() is None\n \n \n@@ -1434,8 +1442,10 @@ def test_PVSystem_scale_voltage_current_power(mocker):\n def test_PVSystem_multi_scale_voltage_current_power(mocker):\n data = (1, 2)\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(modules_per_string=2, strings=3),\n- pvsystem.Array(modules_per_string=3, strings=5)]\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ modules_per_string=2, strings=3),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ modules_per_string=3, strings=5)]\n )\n m = mocker.patch(\n 'pvlib.pvsystem.scale_voltage_current_power', autospec=True\n@@ -1482,7 +1492,8 @@ def test_PVSystem_snlinverter(cec_inverter_parameters):\n def test_PVSystem_get_ac_sandia_multi(cec_inverter_parameters, mocker):\n inv_fun = mocker.spy(inverter, 'sandia_multi')\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(), pvsystem.Array()],\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180)),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180))],\n inverter=cec_inverter_parameters['Name'],\n inverter_parameters=cec_inverter_parameters,\n )\n@@ -1529,7 +1540,8 @@ def test_PVSystem_get_ac_pvwatts_multi(\n systems = [pvwatts_system_defaults, pvwatts_system_kwargs]\n for base_sys, exp in zip(systems, expected):\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(), pvsystem.Array()],\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180)),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180),)],\n inverter_parameters=base_sys.inverter_parameters,\n )\n pdcs = pd.Series([0., 25., 50.])\n@@ -1571,7 +1583,7 @@ def test_PVSystem_get_ac_single_array_tuple_input(\n 'sandia': pd.Series([-0.020000, 132.004308, 250.000000])\n }\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array()],\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180))],\n inverter_parameters=inverter_parameters[model]\n )\n ac = system.get_ac(p_dc=(pdcs[model],), v_dc=(vdcs[model],), model=model)\n@@ -1597,7 +1609,8 @@ def test_PVSystem_get_ac_adr(adr_inverter_parameters, mocker):\n \n def test_PVSystem_get_ac_adr_multi(adr_inverter_parameters):\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(), pvsystem.Array()],\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180)),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180))],\n inverter_parameters=adr_inverter_parameters,\n )\n pdcs = pd.Series([135, 1232, 1170, 420, 551])\n@@ -1625,9 +1638,12 @@ def test_PVSystem_creation():\n \n \n def test_PVSystem_multiple_array_creation():\n- array_one = pvsystem.Array(surface_tilt=32)\n- array_two = pvsystem.Array(surface_tilt=15, module_parameters={'pdc0': 1})\n+ array_one = pvsystem.Array(pvsystem.FixedMount(surface_tilt=32))\n+ array_two = pvsystem.Array(pvsystem.FixedMount(surface_tilt=15),\n+ module_parameters={'pdc0': 1})\n pv_system = pvsystem.PVSystem(arrays=[array_one, array_two])\n+ assert pv_system.arrays[0].module_parameters == {}\n+ assert pv_system.arrays[1].module_parameters == {'pdc0': 1}\n assert pv_system.arrays == (array_one, array_two)\n with pytest.raises(TypeError):\n pvsystem.PVSystem(arrays=array_one)\n@@ -1641,8 +1657,10 @@ def test_PVSystem_get_aoi():\n \n def test_PVSystem_multiple_array_get_aoi():\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(surface_tilt=15, surface_azimuth=135),\n- pvsystem.Array(surface_tilt=32, surface_azimuth=135)]\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(surface_tilt=15,\n+ surface_azimuth=135)),\n+ pvsystem.Array(pvsystem.FixedMount(surface_tilt=32,\n+ surface_azimuth=135))]\n )\n aoi_one, aoi_two = system.get_aoi(30, 225)\n assert np.round(aoi_two, 4) == 42.7408\n@@ -1703,8 +1721,10 @@ def test_PVSystem_get_irradiance_model(mocker):\n \n \n def test_PVSystem_multi_array_get_irradiance():\n- array_one = pvsystem.Array(surface_tilt=32, surface_azimuth=135)\n- array_two = pvsystem.Array(surface_tilt=5, surface_azimuth=150)\n+ array_one = pvsystem.Array(pvsystem.FixedMount(surface_tilt=32,\n+ surface_azimuth=135))\n+ array_two = pvsystem.Array(pvsystem.FixedMount(surface_tilt=5,\n+ surface_azimuth=150))\n system = pvsystem.PVSystem(arrays=[array_one, array_two])\n location = Location(latitude=32, longitude=-111)\n times = pd.date_range(start='20160101 1200-0700',\n@@ -1743,8 +1763,8 @@ def test_PVSystem_multi_array_get_irradiance_multi_irrad():\n for each array when different GHI/DHI/DNI input is given. For the later\n case we verify that the correct irradiance data is passed to each array.\n \"\"\"\n- array_one = pvsystem.Array()\n- array_two = pvsystem.Array()\n+ array_one = pvsystem.Array(pvsystem.FixedMount(0, 180))\n+ array_two = pvsystem.Array(pvsystem.FixedMount(0, 180))\n system = pvsystem.PVSystem(arrays=[array_one, array_two])\n location = Location(latitude=32, longitude=-111)\n times = pd.date_range(start='20160101 1200-0700',\n@@ -1804,40 +1824,6 @@ def test_PVSystem_multi_array_get_irradiance_multi_irrad():\n assert not array_irrad[0].equals(array_irrad[1])\n \n \n-def test_PVSystem_change_surface_azimuth():\n- system = pvsystem.PVSystem(surface_azimuth=180)\n- with pytest.warns(pvlibDeprecationWarning):\n- assert system.surface_azimuth == 180\n- with pytest.warns(pvlibDeprecationWarning):\n- system.surface_azimuth = 90\n- with pytest.warns(pvlibDeprecationWarning):\n- assert system.surface_azimuth == 90\n-\n-\n-def test_PVSystem_get_albedo():\n- system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(albedo=0.5)]\n- )\n- with pytest.warns(pvlibDeprecationWarning):\n- assert system.albedo == 0.5\n-\n-\n-def test_PVSystem_modules_per_string():\n- system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(modules_per_string=5)]\n- )\n- with pytest.warns(pvlibDeprecationWarning):\n- assert system.modules_per_string == 5\n-\n-\n-def test_PVSystem_strings_per_inverter():\n- system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(strings=5)]\n- )\n- with pytest.warns(pvlibDeprecationWarning):\n- assert system.strings_per_inverter == 5\n-\n-\n @fail_on_pvlib_version('0.10')\n @pytest.mark.parametrize('attr', ['module_parameters', 'module', 'module_type',\n 'temperature_model_parameters', 'albedo',\n@@ -1845,8 +1831,8 @@ def test_PVSystem_strings_per_inverter():\n 'racking_model', 'modules_per_string',\n 'strings_per_inverter'])\n def test_PVSystem_multi_array_attributes(attr):\n- array_one = pvsystem.Array()\n- array_two = pvsystem.Array()\n+ array_one = pvsystem.Array(pvsystem.FixedMount())\n+ array_two = pvsystem.Array(pvsystem.FixedMount())\n system = pvsystem.PVSystem(arrays=[array_one, array_two])\n with pytest.raises(AttributeError):\n getattr(system, attr)\n@@ -1871,23 +1857,23 @@ def test_PVSystem___repr__():\n name: pv ftw\n Array:\n name: None\n- surface_tilt: 0\n- surface_azimuth: 180\n+ mount: FixedMount(surface_tilt=0, surface_azimuth=180, racking_model=None, module_height=None)\n module: blah\n albedo: 0.25\n- racking_model: None\n module_type: None\n temperature_model_parameters: {'a': -3.56}\n strings: 1\n modules_per_string: 1\n- inverter: blarg\"\"\"\n+ inverter: blarg\"\"\" # noqa: E501\n assert system.__repr__() == expected\n \n \n def test_PVSystem_multi_array___repr__():\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(surface_tilt=30, surface_azimuth=100),\n- pvsystem.Array(surface_tilt=20, surface_azimuth=220,\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(surface_tilt=30,\n+ surface_azimuth=100)),\n+ pvsystem.Array(pvsystem.FixedMount(surface_tilt=20,\n+ surface_azimuth=220),\n name='foo')],\n inverter='blarg',\n )\n@@ -1895,36 +1881,32 @@ def test_PVSystem_multi_array___repr__():\n name: None\n Array:\n name: None\n- surface_tilt: 30\n- surface_azimuth: 100\n+ mount: FixedMount(surface_tilt=30, surface_azimuth=100, racking_model=None, module_height=None)\n module: None\n albedo: 0.25\n- racking_model: None\n module_type: None\n temperature_model_parameters: {}\n strings: 1\n modules_per_string: 1\n Array:\n name: foo\n- surface_tilt: 20\n- surface_azimuth: 220\n+ mount: FixedMount(surface_tilt=20, surface_azimuth=220, racking_model=None, module_height=None)\n module: None\n albedo: 0.25\n- racking_model: None\n module_type: None\n temperature_model_parameters: {}\n strings: 1\n modules_per_string: 1\n- inverter: blarg\"\"\"\n+ inverter: blarg\"\"\" # noqa: E501\n assert expected == system.__repr__()\n \n \n def test_Array___repr__():\n array = pvsystem.Array(\n- surface_tilt=10, surface_azimuth=100,\n+ mount=pvsystem.FixedMount(surface_tilt=10, surface_azimuth=100,\n+ racking_model='close_mount'),\n albedo=0.15, module_type='glass_glass',\n temperature_model_parameters={'a': -3.56},\n- racking_model='close_mount',\n module_parameters={'foo': 'bar'},\n modules_per_string=100,\n strings=10, module='baz',\n@@ -1932,15 +1914,13 @@ def test_Array___repr__():\n )\n expected = \"\"\"Array:\n name: biz\n- surface_tilt: 10\n- surface_azimuth: 100\n+ mount: FixedMount(surface_tilt=10, surface_azimuth=100, racking_model='close_mount', module_height=None)\n module: baz\n albedo: 0.15\n- racking_model: close_mount\n module_type: glass_glass\n temperature_model_parameters: {'a': -3.56}\n strings: 10\n- modules_per_string: 100\"\"\"\n+ modules_per_string: 100\"\"\" # noqa: E501\n assert array.__repr__() == expected\n \n \n@@ -2035,12 +2015,14 @@ def test_PVSystem_multiple_array_pvwatts_dc():\n 'pdc0': 100, 'gamma_pdc': -0.003, 'temp_ref': 20\n }\n array_one = pvsystem.Array(\n+ pvsystem.FixedMount(0, 180),\n module_parameters=array_one_module_parameters\n )\n array_two_module_parameters = {\n 'pdc0': 150, 'gamma_pdc': -0.002, 'temp_ref': 25\n }\n array_two = pvsystem.Array(\n+ pvsystem.FixedMount(0, 180),\n module_parameters=array_two_module_parameters\n )\n system = pvsystem.PVSystem(arrays=[array_one, array_two])\n@@ -2060,7 +2042,9 @@ def test_PVSystem_multiple_array_pvwatts_dc():\n \n def test_PVSystem_multiple_array_pvwatts_dc_value_error():\n system = pvsystem.PVSystem(\n- arrays=[pvsystem.Array(), pvsystem.Array(), pvsystem.Array()]\n+ arrays=[pvsystem.Array(pvsystem.FixedMount(0, 180)),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180)),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180))]\n )\n error_message = 'Length mismatch for per-array parameter'\n with pytest.raises(ValueError, match=error_message):\n@@ -2118,7 +2102,9 @@ def test_PVSystem_pvwatts_ac_kwargs(pvwatts_system_kwargs, mocker):\n \n def test_PVSystem_num_arrays():\n system_one = pvsystem.PVSystem()\n- system_two = pvsystem.PVSystem(arrays=[pvsystem.Array(), pvsystem.Array()])\n+ system_two = pvsystem.PVSystem(arrays=[\n+ pvsystem.Array(pvsystem.FixedMount(0, 180)),\n+ pvsystem.Array(pvsystem.FixedMount(0, 180))])\n assert system_one.num_arrays == 1\n assert system_two.num_arrays == 2\n \n@@ -2146,6 +2132,49 @@ def test_no_extra_kwargs():\n pvsystem.PVSystem(arbitrary_kwarg='value')\n \n \n+def test_AbstractMount_constructor():\n+ match = \"Can't instantiate abstract class AbstractMount\"\n+ with pytest.raises(TypeError, match=match):\n+ _ = pvsystem.AbstractMount()\n+\n+\[email protected]\n+def fixed_mount():\n+ return pvsystem.FixedMount(20, 180)\n+\n+\[email protected]\n+def single_axis_tracker_mount():\n+ return pvsystem.SingleAxisTrackerMount(axis_tilt=10, axis_azimuth=170,\n+ max_angle=45, backtrack=False,\n+ gcr=0.4, cross_axis_tilt=-5)\n+\n+\n+def test_FixedMount_constructor(fixed_mount):\n+ assert fixed_mount.surface_tilt == 20\n+ assert fixed_mount.surface_azimuth == 180\n+\n+\n+def test_FixedMount_get_orientation(fixed_mount):\n+ expected = {'surface_tilt': 20, 'surface_azimuth': 180}\n+ assert fixed_mount.get_orientation(45, 130) == expected\n+\n+\n+def test_SingleAxisTrackerMount_constructor(single_axis_tracker_mount):\n+ expected = dict(axis_tilt=10, axis_azimuth=170, max_angle=45,\n+ backtrack=False, gcr=0.4, cross_axis_tilt=-5)\n+ for attr_name, expected_value in expected.items():\n+ assert getattr(single_axis_tracker_mount, attr_name) == expected_value\n+\n+\n+def test_SingleAxisTrackerMount_get_orientation(single_axis_tracker_mount):\n+ expected = {'surface_tilt': 19.29835284, 'surface_azimuth': 229.7643755}\n+ actual = single_axis_tracker_mount.get_orientation(45, 190)\n+ for key, expected_value in expected.items():\n+ err_msg = f\"{key} value incorrect\"\n+ assert actual[key] == pytest.approx(expected_value), err_msg\n+\n+\n def test_dc_ohms_from_percent():\n expected = .1425\n out = pvsystem.dc_ohms_from_percent(38, 8, 3, 1, 1)\n@@ -2183,7 +2212,8 @@ def test_Array_dc_ohms_from_percent(mocker):\n \n expected = .1425\n \n- array = pvsystem.Array(array_losses_parameters={'dc_ohmic_percent': 3},\n+ array = pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ array_losses_parameters={'dc_ohmic_percent': 3},\n module_parameters={'I_mp_ref': 8,\n 'V_mp_ref': 38})\n out = array.dc_ohms_from_percent()\n@@ -2196,7 +2226,8 @@ def test_Array_dc_ohms_from_percent(mocker):\n )\n assert_allclose(out, expected)\n \n- array = pvsystem.Array(array_losses_parameters={'dc_ohmic_percent': 3},\n+ array = pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ array_losses_parameters={'dc_ohmic_percent': 3},\n module_parameters={'Impo': 8,\n 'Vmpo': 38})\n out = array.dc_ohms_from_percent()\n@@ -2209,7 +2240,8 @@ def test_Array_dc_ohms_from_percent(mocker):\n )\n assert_allclose(out, expected)\n \n- array = pvsystem.Array(array_losses_parameters={'dc_ohmic_percent': 3},\n+ array = pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ array_losses_parameters={'dc_ohmic_percent': 3},\n module_parameters={'Impp': 8,\n 'Vmpp': 38})\n out = array.dc_ohms_from_percent()\n@@ -2230,7 +2262,8 @@ def test_Array_dc_ohms_from_percent(mocker):\n '{\"V_mp_ref\", \"I_mp_Ref\"}, '\n '{\"Vmpo\", \"Impo\"}, or '\n '{\"Vmpp\", \"Impp\"}.')):\n- array = pvsystem.Array(array_losses_parameters={'dc_ohmic_percent': 3})\n+ array = pvsystem.Array(pvsystem.FixedMount(0, 180),\n+ array_losses_parameters={'dc_ohmic_percent': 3})\n out = array.dc_ohms_from_percent()\n \n \n@@ -2261,7 +2294,7 @@ def test_PVSystem_temperature_deprecated(funcname):\n ])\n def test_Array_temperature_missing_parameters(model, keys):\n # test that a nice error is raised when required temp params are missing\n- array = pvsystem.Array()\n+ array = pvsystem.Array(pvsystem.FixedMount(0, 180))\n index = pd.date_range('2019-01-01', freq='h', periods=5)\n temps = pd.Series(25, index)\n irrads = pd.Series(1000, index)\ndiff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -6,8 +6,9 @@\n from numpy.testing import assert_allclose\n \n import pvlib\n-from pvlib import tracking, pvsystem\n+from pvlib import tracking\n from .conftest import DATA_DIR, assert_frame_equal\n+from pvlib._deprecation import pvlibDeprecationWarning\n \n SINGLEAXIS_COL_ORDER = ['tracker_theta', 'aoi',\n 'surface_azimuth', 'surface_tilt']\n@@ -289,51 +290,11 @@ def test_low_sun_angles():\n assert_allclose(expected[k], v)\n \n \n-def test_SingleAxisTracker_creation():\n- system = tracking.SingleAxisTracker(max_angle=45,\n- gcr=.25,\n- module='blah',\n- inverter='blarg')\n-\n- assert system.max_angle == 45\n- assert system.gcr == .25\n- assert system.arrays[0].module == 'blah'\n- assert system.inverter == 'blarg'\n-\n-\n-def test_SingleAxisTracker_one_array_only():\n- system = tracking.SingleAxisTracker(\n- arrays=[pvsystem.Array(\n- module='foo',\n- surface_tilt=None,\n- surface_azimuth=None\n- )]\n- )\n- assert system.arrays[0].module == 'foo'\n- with pytest.raises(ValueError,\n- match=\"SingleAxisTracker does not support \"\n- r\"multiple arrays\\.\"):\n- tracking.SingleAxisTracker(\n- arrays=[pvsystem.Array(module='foo'),\n- pvsystem.Array(module='bar')]\n- )\n- with pytest.raises(ValueError,\n- match=\"Array must not have surface_tilt \"):\n- tracking.SingleAxisTracker(arrays=[pvsystem.Array(module='foo')])\n- with pytest.raises(ValueError,\n- match=\"Array must not have surface_tilt \"):\n- tracking.SingleAxisTracker(\n- arrays=[pvsystem.Array(surface_azimuth=None)])\n- with pytest.raises(ValueError,\n- match=\"Array must not have surface_tilt \"):\n- tracking.SingleAxisTracker(\n- arrays=[pvsystem.Array(surface_tilt=None)])\n-\n-\n def test_SingleAxisTracker_tracking():\n- system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n- axis_azimuth=180, gcr=2.0/7.0,\n- backtrack=True)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n+ axis_azimuth=180, gcr=2.0/7.0,\n+ backtrack=True)\n \n apparent_zenith = pd.Series([30])\n apparent_azimuth = pd.Series([135])\n@@ -353,9 +314,10 @@ def test_SingleAxisTracker_tracking():\n pvsyst_solar_height = 27.315\n pvsyst_axis_tilt = 20.\n pvsyst_axis_azimuth = 20.\n- pvsyst_system = tracking.SingleAxisTracker(\n- max_angle=60., axis_tilt=pvsyst_axis_tilt,\n- axis_azimuth=180+pvsyst_axis_azimuth, backtrack=False)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ pvsyst_system = tracking.SingleAxisTracker(\n+ max_angle=60., axis_tilt=pvsyst_axis_tilt,\n+ axis_azimuth=180+pvsyst_axis_azimuth, backtrack=False)\n # the definition of azimuth is different from PYsyst\n apparent_azimuth = pd.Series([180+pvsyst_solar_azimuth])\n apparent_zenith = pd.Series([90-pvsyst_solar_height])\n@@ -371,9 +333,10 @@ def test_SingleAxisTracker_tracking():\n \n # see test_irradiance for more thorough testing\n def test_get_aoi():\n- system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n- axis_azimuth=180, gcr=2.0/7.0,\n- backtrack=True)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n+ axis_azimuth=180, gcr=2.0/7.0,\n+ backtrack=True)\n surface_tilt = np.array([30, 0])\n surface_azimuth = np.array([90, 270])\n solar_zenith = np.array([70, 10])\n@@ -385,9 +348,10 @@ def test_get_aoi():\n \n \n def test_get_irradiance():\n- system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n- axis_azimuth=180, gcr=2.0/7.0,\n- backtrack=True)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ system = tracking.SingleAxisTracker(max_angle=90, axis_tilt=30,\n+ axis_azimuth=180, gcr=2.0/7.0,\n+ backtrack=True)\n times = pd.date_range(start='20160101 1200-0700',\n end='20160101 1800-0700', freq='6H')\n # latitude=32, longitude=-111\n@@ -431,9 +395,10 @@ def test_get_irradiance():\n \n \n def test_SingleAxisTracker___repr__():\n- system = tracking.SingleAxisTracker(\n- max_angle=45, gcr=.25, module='blah', inverter='blarg',\n- temperature_model_parameters={'a': -3.56})\n+ with pytest.warns(pvlibDeprecationWarning):\n+ system = tracking.SingleAxisTracker(\n+ max_angle=45, gcr=.25, module='blah', inverter='blarg',\n+ temperature_model_parameters={'a': -3.56})\n expected = \"\"\"SingleAxisTracker:\n axis_tilt: 0\n axis_azimuth: 0\n@@ -444,16 +409,14 @@ def test_SingleAxisTracker___repr__():\n name: None\n Array:\n name: None\n- surface_tilt: None\n- surface_azimuth: None\n+ mount: SingleAxisTrackerMount(axis_tilt=0, axis_azimuth=0, max_angle=45, backtrack=True, gcr=0.25, cross_axis_tilt=0.0, racking_model=None, module_height=None)\n module: blah\n albedo: 0.25\n- racking_model: None\n module_type: None\n temperature_model_parameters: {'a': -3.56}\n strings: 1\n modules_per_string: 1\n- inverter: blarg\"\"\"\n+ inverter: blarg\"\"\" # noqa: E501\n assert system.__repr__() == expected\n \n \n", "problem_statement": "make Array play nicely with fixed tilt systems and trackers\n#1076 is adding an `Array` class that largely describes a fixed-tilt array. However, the composition logic of `PVSystem: def __init__(arrays,...)` combined with the inheritance logic of `SingleAxisTracker(PVSystem)` makes for an odd combination of `Array` objects within `SingleAxisTrackers`. See, for example, https://github.com/pvlib/pvlib-python/pull/1076#discussion_r539704316. \r\n\r\nIn https://github.com/pvlib/pvlib-python/pull/1076#discussion_r539686448 I proposed roughly:\r\n\r\nSplit the `Array` into `BaseArray`, `FixedTiltArray(BaseArray)`, `SingleAxisTrackingArray(BaseArray)`? Basic idea:\r\n\r\n```python\r\nclass FixedTiltArray(BaseArray)\r\n \"\"\"\r\n Parameters\r\n ----------\r\n surface_tilt: float or array-like, default 0\r\n Surface tilt angles in decimal degrees.\r\n The tilt angle is defined as degrees from horizontal\r\n (e.g. surface facing up = 0, surface facing horizon = 90)\r\n\r\n surface_azimuth: float or array-like, default 180\r\n Azimuth angle of the module surface.\r\n North=0, East=90, South=180, West=270.\r\n\r\n **kwargs\r\n Passed to Array. Or copy remainder of Array doc string to be explicit.\r\n \"\"\"\r\n\r\n\r\n# could be in pvsystem.py (module is gradually becoming just the objects) or could be in tracking.py\r\nclass SingleAxisTrackerArray(BaseArray)\r\n \"\"\"\r\n Parameters\r\n ----------\r\n axis_tilt : float, default 0\r\n The tilt of the axis of rotation (i.e, the y-axis defined by\r\n axis_azimuth) with respect to horizontal, in decimal degrees.\r\n\r\n etc.\r\n\r\n **kwargs\r\n Passed to Array. Or copy remainder of Array doc string to be explicit.\r\n \"\"\"\r\n```\r\n\r\nI believe the only major challenge is that the `get_aoi` and `get_irradiance` methods would either need to differ in signature (as they do now, and thus present a challenge to a `PVSystem` wrapper) or in implementation (tracker methods would include a call to `singleaxis`, and thus would be less efficient in some workflows). @wfvining suggests that the consistent signature is more important and I'm inclined to agree.\r\n\r\nWe'd also deprecate the old `SingleAxisTracking` class.\r\n\r\nWe should resolve this issue before releasing the new Array code into the wild in 0.9.\n", "hints_text": "I like the idea of depreciating the `SingleAxisTracking` class and wrapping tracking functionality more directly into `PVSystem` and `Array`. I don't quite picture yet how it would work on the user side. They can directly create a `SingleAxisTrackerArray` and then pass that to a `PVSystem`? Or create a `FixedTiltArray` and pass that? \r\n\r\nI think we should keep in mind though that when you have a tracking system you are probably very likely going to have a uniform system and a single `Array` per `PVsystem`. So if I am going to create a tracking PVSystem, I am likely going to want to create it straight from a `PVSystem` as the most direct route rather than having to create the array first. (Unless the intent is to depreciate that functionality eventually and push always creating an `Array` first). In that sense, keeping `SingleAxisTracker` as a `PVSystem` class and just having it create a `SingleAxisTrackingArray` instead of a `Array` may be more user friendly. But I do think there is opportunity to come up with a system to wrap everything together better. \r\n\r\nI also like the simplicity of `Array` and `PVsystem`, and worry about now adding different types of `Array`. \r\n\r\nJust throwing this out there, what if `Array` had a `tracking_model` attribute that right now could be either `fixed` or `single_axis`? Depending on what is passed it sets the appropriate `get_iam` and `get_irradiance` methods, and initiates the appropriate default attributes (`surface_tilt`, `surface_azimuth`, `axis_angle`, `max_angle` etc)? \n> They can directly create a SingleAxisTrackerArray and then pass that to a PVSystem? Or create a FixedTiltArray and pass that?\r\n\r\nYes.\r\n\r\n> I think we should keep in mind though that when you have a tracking system you are probably very likely going to have a uniform system and a single Array per PVsystem. \r\n\r\nTrue. The main application that I can see for mixing a `SingleAxisTrackerArray` with something else is for modeling systems with a mix of broken and working trackers, so it would look something like:\r\n\r\n```python\r\nother_params = {} # module_parameters, etc\r\nPVSystem([\r\n Array(surface_tilt=45, surface_azimuth=90, **other_params), \r\n SingleAxisTrackerArray(**other_params)\r\n])\r\n```\r\n\r\n> So if I am going to create a tracking PVSystem, I am likely going to want to create it straight from a PVSystem as the most direct route rather than having to create the array first. (Unless the intent is to depreciate that functionality eventually and push always creating an Array first). In that sense, keeping SingleAxisTracker as a PVSystem class and just having it create a SingleAxisTrackingArray instead of a Array may be more user friendly. \r\n\r\nWe discussed deprecating that functionality but haven't committed to it. \r\n\r\n> Just throwing this out there, what if Array had a tracking_model attribute that right now could be either fixed or single_axis? Depending on what is passed it sets the appropriate get_iam and get_irradiance methods, and initiates the appropriate default attributes (surface_tilt, surface_azimuth, axis_angle, max_angle etc)?\r\n\r\nInteresting idea. I could see this working at the `PVSystem` level so that you can retain the ability to create the system with a single function call despite the removal of `SingleAxisTracker`.", "created_at": "2021-02-23T18:12:23Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_noct_sam_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_run_model_tracker_list", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_len1_weather_tuple", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params4-noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_dc_model_incomplete", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_ohms_from_percent", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_no_dc_ohmic_loss", "pvlib/tests/test_modelchain.py::test_dc_ohmic_ext_def", "pvlib/tests/test_modelchain.py::test_dc_ohmic_not_a_model", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_type]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[temperature_model_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[albedo]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_tilt]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_azimuth]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[racking_model]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[modules_per_string]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[strings_per_inverter]", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]", "pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_get_irradiance", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_calc_axis_tilt", "pvlib/tests/test_tracking.py::test_slope_aware_backtracking"], "PASS_TO_PASS": [], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1157", "base_commit": "0b8f24c265d76320067a5ee908a57d475cd1bb24", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -268,22 +268,47 @@ class ModelChainResult:\n _T = TypeVar('T')\n PerArray = Union[_T, Tuple[_T, ...]]\n \"\"\"Type for fields that vary between arrays\"\"\"\n+\n+ # these attributes are used in __setattr__ to determine the correct type.\n+ _singleton_tuples: bool = field(default=False)\n+ _per_array_fields = {'total_irrad', 'aoi', 'aoi_modifier',\n+ 'spectral_modifier', 'cell_temperature',\n+ 'effective_irradiance', 'dc', 'diode_params'}\n+\n # system-level information\n solar_position: Optional[pd.DataFrame] = field(default=None)\n airmass: Optional[pd.DataFrame] = field(default=None)\n ac: Optional[pd.Series] = field(default=None)\n- # per DC array information\n tracking: Optional[pd.DataFrame] = field(default=None)\n+\n+ # per DC array information\n total_irrad: Optional[PerArray[pd.DataFrame]] = field(default=None)\n aoi: Optional[PerArray[pd.Series]] = field(default=None)\n- aoi_modifier: Optional[PerArray[pd.Series]] = field(default=None)\n- spectral_modifier: Optional[PerArray[pd.Series]] = field(default=None)\n+ aoi_modifier: Optional[PerArray[Union[pd.Series, float]]] = \\\n+ field(default=None)\n+ spectral_modifier: Optional[PerArray[Union[pd.Series, float]]] = \\\n+ field(default=None)\n cell_temperature: Optional[PerArray[pd.Series]] = field(default=None)\n effective_irradiance: Optional[PerArray[pd.Series]] = field(default=None)\n dc: Optional[PerArray[Union[pd.Series, pd.DataFrame]]] = \\\n field(default=None)\n diode_params: Optional[PerArray[pd.DataFrame]] = field(default=None)\n \n+ def _result_type(self, value):\n+ \"\"\"Coerce `value` to the correct type according to\n+ ``self._singleton_tuples``.\"\"\"\n+ # Allow None to pass through without being wrapped in a tuple\n+ if (self._singleton_tuples\n+ and not isinstance(value, tuple)\n+ and value is not None):\n+ return (value,)\n+ return value\n+\n+ def __setattr__(self, key, value):\n+ if key in ModelChainResult._per_array_fields:\n+ value = self._result_type(value)\n+ super().__setattr__(key, value)\n+\n \n class ModelChain:\n \"\"\"\n@@ -684,12 +709,9 @@ def infer_dc_model(self):\n 'set the model with the dc_model kwarg.')\n \n def sapm(self):\n- self.results.dc = self.system.sapm(self.results.effective_irradiance,\n- self.results.cell_temperature)\n-\n- self.results.dc = self.system.scale_voltage_current_power(\n- self.results.dc)\n-\n+ dc = self.system.sapm(self.results.effective_irradiance,\n+ self.results.cell_temperature)\n+ self.results.dc = self.system.scale_voltage_current_power(dc)\n return self\n \n def _singlediode(self, calcparams_model_function):\n@@ -745,18 +767,14 @@ def pvwatts_dc(self):\n pvlib.pvsystem.PVSystem.pvwatts_dc\n pvlib.pvsystem.PVSystem.scale_voltage_current_power\n \"\"\"\n- self.results.dc = self.system.pvwatts_dc(\n- self.results.effective_irradiance, self.results.cell_temperature)\n- if isinstance(self.results.dc, tuple):\n- temp = tuple(\n- pd.DataFrame(s, columns=['p_mp']) for s in self.results.dc)\n- else:\n- temp = pd.DataFrame(self.results.dc, columns=['p_mp'])\n- scaled = self.system.scale_voltage_current_power(temp)\n- if isinstance(scaled, tuple):\n- self.results.dc = tuple(s['p_mp'] for s in scaled)\n- else:\n- self.results.dc = scaled['p_mp']\n+ dc = self.system.pvwatts_dc(\n+ self.results.effective_irradiance,\n+ self.results.cell_temperature,\n+ unwrap=False\n+ )\n+ p_mp = tuple(pd.DataFrame(s, columns=['p_mp']) for s in dc)\n+ scaled = self.system.scale_voltage_current_power(p_mp)\n+ self.results.dc = _tuple_from_dfs(scaled, \"p_mp\")\n return self\n \n @property\n@@ -866,23 +884,29 @@ def infer_aoi_model(self):\n \n def ashrae_aoi_loss(self):\n self.results.aoi_modifier = self.system.get_iam(\n- self.results.aoi, iam_model='ashrae')\n+ self.results.aoi,\n+ iam_model='ashrae'\n+ )\n return self\n \n def physical_aoi_loss(self):\n- self.results.aoi_modifier = self.system.get_iam(self.results.aoi,\n- iam_model='physical')\n+ self.results.aoi_modifier = self.system.get_iam(\n+ self.results.aoi,\n+ iam_model='physical'\n+ )\n return self\n \n def sapm_aoi_loss(self):\n- self.results.aoi_modifier = self.system.get_iam(self.results.aoi,\n- iam_model='sapm')\n+ self.results.aoi_modifier = self.system.get_iam(\n+ self.results.aoi,\n+ iam_model='sapm'\n+ )\n return self\n \n def martin_ruiz_aoi_loss(self):\n self.results.aoi_modifier = self.system.get_iam(\n- self.results.aoi,\n- iam_model='martin_ruiz')\n+ self.results.aoi, iam_model='martin_ruiz'\n+ )\n return self\n \n def no_aoi_loss(self):\n@@ -934,13 +958,15 @@ def infer_spectral_model(self):\n \n def first_solar_spectral_loss(self):\n self.results.spectral_modifier = self.system.first_solar_spectral_loss(\n- self.weather['precipitable_water'],\n- self.results.airmass['airmass_absolute'])\n+ _tuple_from_dfs(self.weather, 'precipitable_water'),\n+ self.results.airmass['airmass_absolute']\n+ )\n return self\n \n def sapm_spectral_loss(self):\n self.results.spectral_modifier = self.system.sapm_spectral_loss(\n- self.results.airmass['airmass_absolute'])\n+ self.results.airmass['airmass_absolute']\n+ )\n return self\n \n def no_spectral_loss(self):\n@@ -1066,7 +1092,7 @@ def infer_losses_model(self):\n \n def pvwatts_losses(self):\n self.losses = (100 - self.system.pvwatts_losses()) / 100.\n- if self.system.num_arrays > 1:\n+ if isinstance(self.results.dc, tuple):\n for dc in self.results.dc:\n dc *= self.losses\n else:\n@@ -1271,6 +1297,17 @@ def _verify(data, index=None):\n for (i, array_data) in enumerate(data):\n _verify(array_data, i)\n \n+ def _configure_results(self):\n+ \"\"\"Configure the type used for per-array fields in ModelChainResult.\n+\n+ Must be called after ``self.weather`` has been assigned. If\n+ ``self.weather`` is a tuple and the number of arrays in the system\n+ is 1, then per-array results are stored as length-1 tuples.\n+ \"\"\"\n+ self.results._singleton_tuples = (\n+ self.system.num_arrays == 1 and isinstance(self.weather, tuple)\n+ )\n+\n def _assign_weather(self, data):\n def _build_weather(data):\n key_list = [k for k in WEATHER_KEYS if k in data]\n@@ -1286,6 +1323,7 @@ def _build_weather(data):\n self.weather = tuple(\n _build_weather(weather) for weather in data\n )\n+ self._configure_results()\n return self\n \n def _assign_total_irrad(self, data):\n@@ -1383,7 +1421,8 @@ def prepare_inputs(self, weather):\n _tuple_from_dfs(self.weather, 'ghi'),\n _tuple_from_dfs(self.weather, 'dhi'),\n airmass=self.results.airmass['airmass_relative'],\n- model=self.transposition_model)\n+ model=self.transposition_model\n+ )\n \n return self\n \ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -6,6 +6,7 @@\n from collections import OrderedDict\n import functools\n import io\n+import itertools\n import os\n from urllib.request import urlopen\n import numpy as np\n@@ -811,8 +812,9 @@ def first_solar_spectral_loss(self, pw, airmass_absolute):\n effective irradiance, i.e., the irradiance that is converted to\n electrical current.\n \"\"\"\n+ pw = self._validate_per_array(pw, system_wide=True)\n \n- def _spectral_correction(array):\n+ def _spectral_correction(array, pw):\n if 'first_solar_spectral_coefficients' in \\\n array.module_parameters.keys():\n coefficients = \\\n@@ -828,7 +830,9 @@ def _spectral_correction(array):\n pw, airmass_absolute,\n module_type, coefficients\n )\n- return tuple(_spectral_correction(array) for array in self.arrays)\n+ return tuple(\n+ itertools.starmap(_spectral_correction, zip(self.arrays, pw))\n+ )\n \n def singlediode(self, photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth,\n@@ -891,29 +895,31 @@ def get_ac(self, model, p_dc, v_dc=None):\n model = model.lower()\n multiple_arrays = self.num_arrays > 1\n if model == 'sandia':\n+ p_dc = self._validate_per_array(p_dc)\n+ v_dc = self._validate_per_array(v_dc)\n if multiple_arrays:\n- p_dc = self._validate_per_array(p_dc)\n- v_dc = self._validate_per_array(v_dc)\n- inv_fun = inverter.sandia_multi\n- else:\n- inv_fun = inverter.sandia\n- return inv_fun(v_dc, p_dc, self.inverter_parameters)\n+ return inverter.sandia_multi(\n+ v_dc, p_dc, self.inverter_parameters)\n+ return inverter.sandia(v_dc[0], p_dc[0], self.inverter_parameters)\n elif model == 'pvwatts':\n kwargs = _build_kwargs(['eta_inv_nom', 'eta_inv_ref'],\n self.inverter_parameters)\n+ p_dc = self._validate_per_array(p_dc)\n if multiple_arrays:\n- p_dc = self._validate_per_array(p_dc)\n- inv_fun = inverter.pvwatts_multi\n- else:\n- inv_fun = inverter.pvwatts\n- return inv_fun(p_dc, self.inverter_parameters['pdc0'], **kwargs)\n+ return inverter.pvwatts_multi(\n+ p_dc, self.inverter_parameters['pdc0'], **kwargs)\n+ return inverter.pvwatts(\n+ p_dc[0], self.inverter_parameters['pdc0'], **kwargs)\n elif model == 'adr':\n if multiple_arrays:\n raise ValueError(\n 'The adr inverter function cannot be used for an inverter',\n ' with multiple MPPT inputs')\n- else:\n- return inverter.adr(v_dc, p_dc, self.inverter_parameters)\n+ # While this is only used for single-array systems, calling\n+ # _validate_per_arry lets us pass in singleton tuples.\n+ p_dc = self._validate_per_array(p_dc)\n+ v_dc = self._validate_per_array(v_dc)\n+ return inverter.adr(v_dc[0], p_dc[0], self.inverter_parameters)\n else:\n raise ValueError(\n model + ' is not a valid AC power model.',\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -1080,6 +1080,54 @@ def test_run_model_from_effective_irradiance_missing_poa(\n (data_complete, data_incomplete))\n \n \n+def test_run_model_singleton_weather_single_array(cec_dc_snl_ac_system,\n+ location, weather):\n+ mc = ModelChain(cec_dc_snl_ac_system, location,\n+ aoi_model=\"no_loss\", spectral_model=\"no_loss\")\n+ mc.run_model([weather])\n+ assert isinstance(mc.results.total_irrad, tuple)\n+ assert isinstance(mc.results.aoi, tuple)\n+ assert isinstance(mc.results.aoi_modifier, tuple)\n+ assert isinstance(mc.results.spectral_modifier, tuple)\n+ assert isinstance(mc.results.effective_irradiance, tuple)\n+ assert isinstance(mc.results.dc, tuple)\n+ assert isinstance(mc.results.cell_temperature, tuple)\n+ assert len(mc.results.cell_temperature) == 1\n+ assert isinstance(mc.results.cell_temperature[0], pd.Series)\n+\n+\n+def test_run_model_from_poa_singleton_weather_single_array(\n+ sapm_dc_snl_ac_system, location, total_irrad):\n+ mc = ModelChain(sapm_dc_snl_ac_system, location,\n+ aoi_model='no_loss', spectral_model='no_loss')\n+ ac = mc.run_model_from_poa([total_irrad]).results.ac\n+ expected = pd.Series(np.array([149.280238, 96.678385]),\n+ index=total_irrad.index)\n+ assert isinstance(mc.results.cell_temperature, tuple)\n+ assert len(mc.results.cell_temperature) == 1\n+ assert isinstance(mc.results.cell_temperature[0], pd.Series)\n+ assert_series_equal(ac, expected)\n+\n+\n+def test_run_model_from_effective_irradiance_weather_single_array(\n+ sapm_dc_snl_ac_system, location, weather, total_irrad):\n+ data = weather.copy()\n+ data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad\n+ data['effective_irradiance'] = data['poa_global']\n+ mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss',\n+ spectral_model='no_loss')\n+ ac = mc.run_model_from_effective_irradiance([data]).results.ac\n+ expected = pd.Series(np.array([149.280238, 96.678385]),\n+ index=data.index)\n+ assert isinstance(mc.results.cell_temperature, tuple)\n+ assert len(mc.results.cell_temperature) == 1\n+ assert isinstance(mc.results.cell_temperature[0], pd.Series)\n+ assert isinstance(mc.results.dc, tuple)\n+ assert len(mc.results.dc) == 1\n+ assert isinstance(mc.results.dc[0], pd.DataFrame)\n+ assert_series_equal(ac, expected)\n+\n+\n def poadc(mc):\n mc.results.dc = mc.results.total_irrad['poa_global'] * 0.2\n mc.results.dc.name = None # assert_series_equal will fail without this\n@@ -1324,6 +1372,22 @@ def test_aoi_models(sapm_dc_snl_ac_system, location, aoi_model,\n assert mc.results.ac[1] < 1\n \n \[email protected]('aoi_model', [\n+ 'sapm', 'ashrae', 'physical', 'martin_ruiz'\n+])\n+def test_aoi_models_singleon_weather_single_array(\n+ sapm_dc_snl_ac_system, location, aoi_model, weather):\n+ mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm',\n+ aoi_model=aoi_model, spectral_model='no_loss')\n+ mc.run_model(weather=[weather])\n+ assert isinstance(mc.results.aoi_modifier, tuple)\n+ assert len(mc.results.aoi_modifier) == 1\n+ assert isinstance(mc.results.ac, pd.Series)\n+ assert not mc.results.ac.empty\n+ assert mc.results.ac[0] > 150 and mc.results.ac[0] < 200\n+ assert mc.results.ac[1] < 1\n+\n+\n def test_aoi_model_no_loss(sapm_dc_snl_ac_system, location, weather):\n mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm',\n aoi_model='no_loss', spectral_model='no_loss')\n@@ -1382,6 +1446,21 @@ def test_spectral_models(sapm_dc_snl_ac_system, location, spectral_model,\n assert isinstance(spectral_modifier, (pd.Series, float, int))\n \n \[email protected]('spectral_model', [\n+ 'sapm', 'first_solar', 'no_loss', constant_spectral_loss\n+])\n+def test_spectral_models_singleton_weather_single_array(\n+ sapm_dc_snl_ac_system, location, spectral_model, weather):\n+ # add pw to weather dataframe\n+ weather['precipitable_water'] = [0.3, 0.5]\n+ mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm',\n+ aoi_model='no_loss', spectral_model=spectral_model)\n+ spectral_modifier = mc.run_model([weather]).results.spectral_modifier\n+ assert isinstance(spectral_modifier, tuple)\n+ assert len(spectral_modifier) == 1\n+ assert isinstance(spectral_modifier[0], (pd.Series, float, int))\n+\n+\n def constant_losses(mc):\n mc.losses = 0.9\n mc.results.dc *= mc.losses\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -1472,6 +1472,40 @@ def test_PVSystem_get_ac_pvwatts_multi(\n system.get_ac('pvwatts', (pdcs, pdcs, pdcs))\n \n \[email protected]('model', ['sandia', 'adr', 'pvwatts'])\n+def test_PVSystem_get_ac_single_array_tuple_input(\n+ model,\n+ pvwatts_system_defaults,\n+ cec_inverter_parameters,\n+ adr_inverter_parameters):\n+ vdcs = {\n+ 'sandia': pd.Series(np.linspace(0, 50, 3)),\n+ 'pvwatts': None,\n+ 'adr': pd.Series([135, 154, 390, 420, 551])\n+ }\n+ pdcs = {'adr': pd.Series([135, 1232, 1170, 420, 551]),\n+ 'sandia': pd.Series(np.linspace(0, 11, 3)) * vdcs['sandia'],\n+ 'pvwatts': 50}\n+ inverter_parameters = {\n+ 'sandia': cec_inverter_parameters,\n+ 'adr': adr_inverter_parameters,\n+ 'pvwatts': pvwatts_system_defaults.inverter_parameters\n+ }\n+ expected = {\n+ 'adr': pd.Series([np.nan, 1161.5745, 1116.4459, 382.6679, np.nan]),\n+ 'sandia': pd.Series([-0.020000, 132.004308, 250.000000])\n+ }\n+ system = pvsystem.PVSystem(\n+ arrays=[pvsystem.Array()],\n+ inverter_parameters=inverter_parameters[model]\n+ )\n+ ac = system.get_ac(p_dc=(pdcs[model],), v_dc=(vdcs[model],), model=model)\n+ if model == 'pvwatts':\n+ assert ac < pdcs['pvwatts']\n+ else:\n+ assert_series_equal(ac, expected[model])\n+\n+\n def test_PVSystem_get_ac_adr(adr_inverter_parameters, mocker):\n mocker.spy(inverter, 'adr')\n system = pvsystem.PVSystem(\n", "problem_statement": "ModelChainResult.cell_temperature is not always a pandas.Series \nFor a `ModelChain` configured as below, the `cell_temperature` when running the model chain with a list of data like `ModelChain.run_model([data])` is a tuple with a single number instead of the expected Series\r\n\r\n**To Reproduce**\r\n```python\r\nimport pandas as pd \r\nfrom pvlib.location import Location \r\nfrom pvlib.pvsystem import PVSystem, Array \r\nfrom pvlib.modelchain import ModelChain \r\n \r\ndata = pd.DataFrame( \r\n { \r\n \"ghi\": [1100.0, 1101.0], \r\n \"dni\": [1000.0, 1001], \r\n \"dhi\": [100.0, 100], \r\n \"temp_air\": [25.0, 25], \r\n \"wind_speed\": [10.0, 10], \r\n }, \r\n index=pd.DatetimeIndex( \r\n [pd.Timestamp(\"2021-01-20T12:00-05:00\"), pd.Timestamp(\"2021-01-20T12:05-05:00\")] \r\n ), \r\n) \r\n \r\narray_params = { \r\n \"name\": None, \r\n \"surface_tilt\": 20.0, \r\n \"surface_azimuth\": 180.0, \r\n \"module\": \"Canadian_Solar_Inc__CS5P_220M\", \r\n \"albedo\": 0.2, \r\n \"temperature_model_parameters\": { \r\n \"u_c\": 29.0, \r\n \"u_v\": 0.0, \r\n \"eta_m\": 0.1, \r\n \"alpha_absorption\": 0.9, \r\n }, \r\n \"strings\": 5, \r\n \"modules_per_string\": 7, \r\n \"module_parameters\": { \r\n \"alpha_sc\": 0.004539, \r\n \"gamma_ref\": 1.2, \r\n \"mu_gamma\": -0.003, \r\n \"I_L_ref\": 5.11426, \r\n \"I_o_ref\": 8.10251e-10, \r\n \"R_sh_ref\": 381.254, \r\n \"R_sh_0\": 400.0, \r\n \"R_s\": 1.06602, \r\n \"cells_in_series\": 96, \r\n \"R_sh_exp\": 5.5, \r\n \"EgRef\": 1.121, \r\n }, \r\n}\r\ninverter_parameters = { \r\n \"Paco\": 250.0, \r\n \"Pdco\": 259.589, \r\n \"Vdco\": 40.0, \r\n \"Pso\": 2.08961, \r\n \"C0\": -4.1e-05, \r\n \"C1\": -9.1e-05, \r\n \"C2\": 0.000494, \r\n \"C3\": -0.013171, \r\n \"Pnt\": 0.075, \r\n} \r\n \r\n \r\nlocation = Location(latitude=33.98, longitude=-115.323, altitude=2300) \r\n \r\n \r\narray_sys = PVSystem( \r\n arrays=[Array(**array_params)], inverter_parameters=inverter_parameters \r\n) \r\nassert isinstance( \r\n ModelChain(array_sys, location, aoi_model=\"no_loss\", spectral_model=\"no_loss\") \r\n .run_model(data) \r\n .results.cell_temperature, \r\n pd.Series, \r\n) \r\n \r\narray_run = ModelChain( \r\n array_sys, location, aoi_model=\"no_loss\", spectral_model=\"no_loss\" \r\n).run_model([data]) \r\nassert array_run.results.cell_temperature == array_run.cell_temperature \r\nprint(array_run.results.cell_temperature) # (45.329789874660285,) \r\n \r\n \r\narray_params[\"strings_per_inverter\"] = array_params.pop(\"strings\") \r\nstandard_sys = PVSystem(**array_params, inverter_parameters=inverter_parameters) \r\nassert isinstance( \r\n ModelChain(standard_sys, location, aoi_model=\"no_loss\", spectral_model=\"no_loss\") \r\n .run_model(data) \r\n .results.cell_temperature, \r\n pd.Series, \r\n) \r\n \r\nstandard_run = ModelChain( \r\n standard_sys, location, aoi_model=\"no_loss\", spectral_model=\"no_loss\" \r\n).run_model([data]) \r\nassert standard_run.results.cell_temperature == standard_run.cell_temperature \r\nprint(standard_run.results.cell_temperature) # (45.329789874660285,) \r\nassert not isinstance(standard_run.results.cell_temperature, pd.Series) \r\n \r\n```\r\n\r\n**Expected behavior**\r\n`type(ModelChain.run_model([data]).results.cell_temperature) == pd.Series`\r\n__\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.8.1+4.gba4a199\r\n - ``pandas.__version__``: 1.1.4\r\n - python: 3.8.5\r\n\n", "hints_text": "Confirmed. This is a bug in `pvlib.modelchain.ModelChain._prepare_temperature` not all inputs are tuples and aren't being converted. @wfvining fyi and lmk if you want to fix it.\nDefinitely a bug, but I think the correct behavior is slightly different than you expect. Because you pass a list to `ModelChain.run_model()` the output should be a tuple with a single `pd.Series` element.\nI agree that passing data as a tuple/list should result in all results being tuples of Series/DataFrames. So perhaps this is a separate bug, but ``array_run.results.total_irrad`` (and other results properties) is a singular `pd.DataFrame` instead of `Tuple[pd.DataFrame]`. \nYes, that's the problem. We should make those match the type of `ModelChain.weather`. Not sure about this, but we might be able to pass ~`unwrap=isinstance(self.weather, tuple)`~ `unwrap=not isinstance(self.weather, tuple)` to the `PVSystem` methods to accomplish this. Probably won't be that easy though, since `ModelChain` interacts heavily with `PVSystem` attributes like `temperature_model_params` which can't accept that kwarg.\nPerhaps a related error is raised when running \r\n```python\r\npoa_data = pd.DataFrame(\r\n {\r\n \"poa_global\": [1100.0, 1101.0],\r\n \"poa_direct\": [1000.0, 1001],\r\n \"poa_diffuse\": [100.0, 100],\r\n \"module_temperature\": [25.0, 25],\r\n },\r\n index=pd.DatetimeIndex(\r\n [pd.Timestamp(\"2021-01-20T12:00-05:00\"), pd.Timestamp(\"2021-01-20T12:05-05:00\")]\r\n ),\r\n)\r\n\r\nModelChain(\r\n array_sys, location, aoi_model=\"no_loss\", spectral_model=\"no_loss\",\r\n).run_model_from_poa([poa_data]) \r\n```\r\nraises a TypeError here https://github.com/pvlib/pvlib-python/blob/6b92d218653633e366241c31e8836c0072739ece/pvlib/modelchain.py#L1102-L1106\r\nbecause `self.results.aoi_modifier = 1.0` and `self.results.spectral_modifier = 1.0` \r\nhttps://github.com/pvlib/pvlib-python/blob/6b92d218653633e366241c31e8836c0072739ece/pvlib/modelchain.py#L904-L909\nYup, that's the *first* place this error creeps in. That needs to change, as well as the methods that apply loss models from `PVSystem`. `ModelChain._prep_inputs_fixed()` also needs updating, as well as `_prepate_temperature` itself. I suspect there are one or two other places as well.\r\n\r\nI'm kicking myself a bit for not considering this corner case initially. Very glad you found it early on.\nOne simple solution might be to add some indirection when assigning to `ModelChain.results`. Instead of assigning directly, assignments go through an `_assign_result(field, value)` method that ensures the type of `value` matches `ModelChain.weather`. This might not be the *best* option, but it would not be too difficult to implement.", "created_at": "2021-02-02T17:17:56Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_missing_poa", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp_override", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_change_surface_azimuth", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_modules_per_string", "pvlib/tests/test_pvsystem.py::test_PVSystem_strings_per_inverter", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1737", "base_commit": "5119b4281fa9de8a4dc97002b5c10a6d73c25a4f", "patch": "diff --git a/pvlib/iotools/tmy.py b/pvlib/iotools/tmy.py\n--- a/pvlib/iotools/tmy.py\n+++ b/pvlib/iotools/tmy.py\n@@ -24,7 +24,8 @@\n }\n \n \n-def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n+def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None,\n+ encoding=None):\n \"\"\"Read a TMY3 file into a pandas dataframe.\n \n Note that values contained in the metadata dictionary are unchanged\n@@ -50,6 +51,11 @@ def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n If ``True``, apply standard names to TMY3 columns. Typically this\n results in stripping the units from the column name.\n Cannot be used in combination with ``map_variables``.\n+ encoding : str, optional\n+ Encoding of the file. For files that contain non-UTF8 characters it may\n+ be necessary to specify an alternative encoding, e.g., for\n+ SolarAnywhere TMY3 files the encoding should be 'iso-8859-1'. Users\n+ may also consider using the 'utf-8-sig' encoding.\n \n Returns\n -------\n@@ -58,7 +64,7 @@ def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n data : DataFrame\n A pandas dataframe with the columns described in the table\n below. For more detailed descriptions of each component, please\n- consult the TMY3 User's Manual ([1]_), especially tables 1-1\n+ consult the TMY3 User's Manual [1]_, especially tables 1-1\n through 1-6.\n \n metadata : dict\n@@ -187,14 +193,12 @@ def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n \"\"\" # noqa: E501\n head = ['USAF', 'Name', 'State', 'TZ', 'latitude', 'longitude', 'altitude']\n \n- try:\n- with open(str(filename), 'r') as fbuf:\n- firstline, data = _parse_tmy3(fbuf)\n- # SolarAnywhere files contain non-UTF8 characters and may require\n- # encoding='iso-8859-1' in order to be parsed\n- except UnicodeDecodeError:\n- with open(str(filename), 'r', encoding='iso-8859-1') as fbuf:\n- firstline, data = _parse_tmy3(fbuf)\n+ with open(str(filename), 'r', encoding=encoding) as fbuf:\n+ # header information on the 1st line (0 indexing)\n+ firstline = fbuf.readline()\n+ # use pandas to read the csv file buffer\n+ # header is actually the second line, but tell pandas to look for\n+ data = pd.read_csv(fbuf, header=0)\n \n meta = dict(zip(head, firstline.rstrip('\\n').split(\",\")))\n # convert metadata strings to numeric types\n@@ -206,8 +210,10 @@ def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n \n # get the date column as a pd.Series of numpy datetime64\n data_ymd = pd.to_datetime(data['Date (MM/DD/YYYY)'], format='%m/%d/%Y')\n+ # extract minutes\n+ minutes = data['Time (HH:MM)'].str.split(':').str[1].astype(int)\n # shift the time column so that midnite is 00:00 instead of 24:00\n- shifted_hour = data['Time (HH:MM)'].str[:2].astype(int) % 24\n+ shifted_hour = data['Time (HH:MM)'].str.split(':').str[0].astype(int) % 24\n # shift the dates at midnight (24:00) so they correspond to the next day.\n # If midnight is specified as 00:00 do not shift date.\n data_ymd[data['Time (HH:MM)'].str[:2] == '24'] += datetime.timedelta(days=1) # noqa: E501\n@@ -225,7 +231,8 @@ def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n data_ymd.iloc[-1] = data_ymd.iloc[-1].replace(year=coerce_year+1)\n # NOTE: as of pvlib-0.6.3, min req is pandas-0.18.1, so pd.to_timedelta\n # unit must be in (D,h,m,s,ms,us,ns), but pandas>=0.24 allows unit='hour'\n- data.index = data_ymd + pd.to_timedelta(shifted_hour, unit='h')\n+ data.index = data_ymd + pd.to_timedelta(shifted_hour, unit='h') \\\n+ + pd.to_timedelta(minutes, unit='min')\n # shouldnt' specify both recolumn and map_variables\n if recolumn is not None and map_variables is not None:\n msg = \"`map_variables` and `recolumn` cannot both be specified\"\n@@ -252,15 +259,6 @@ def read_tmy3(filename, coerce_year=None, map_variables=None, recolumn=None):\n return data, meta\n \n \n-def _parse_tmy3(fbuf):\n- # header information on the 1st line (0 indexing)\n- firstline = fbuf.readline()\n- # use pandas to read the csv file buffer\n- # header is actually the second line, but tell pandas to look for\n- data = pd.read_csv(fbuf, header=0)\n- return firstline, data\n-\n-\n def _recolumn(tmy3_dataframe):\n \"\"\"\n Rename the columns of the TMY3 DataFrame.\n@@ -328,7 +326,7 @@ def read_tmy2(filename):\n data : DataFrame\n A dataframe with the columns described in the table below. For a\n more detailed descriptions of each component, please consult the\n- TMY2 User's Manual ([1]_), especially tables 3-1 through 3-6, and\n+ TMY2 User's Manual [1]_, especially tables 3-1 through 3-6, and\n Appendix B.\n \n metadata : dict\n@@ -430,6 +428,7 @@ def read_tmy2(filename):\n ----------\n .. [1] Marion, W and Urban, K. \"Wilcox, S and Marion, W. \"User's Manual\n for TMY2s\". NREL 1995.\n+ :doi:`10.2172/87130`\n \"\"\" # noqa: E501\n # paste in the column info as one long line\n string = '%2d%2d%2d%2d%4d%4d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%2d%1s%1d%2d%1s%1d%4d%1s%1d%4d%1s%1d%3d%1s%1d%4d%1s%1d%3d%1s%1d%3d%1s%1d%4d%1s%1d%5d%1s%1d%10d%3d%1s%1d%3d%1s%1d%3d%1s%1d%2d%1s%1d' # noqa: E501\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_tmy.py b/pvlib/tests/iotools/test_tmy.py\n--- a/pvlib/tests/iotools/test_tmy.py\n+++ b/pvlib/tests/iotools/test_tmy.py\n@@ -121,7 +121,8 @@ def test_solaranywhere_tmy3(solaranywhere_index):\n # The SolarAnywhere TMY3 format specifies midnight as 00:00 whereas the\n # NREL TMY3 format utilizes 24:00. The SolarAnywhere file is therefore\n # included to test files with 00:00 timestamps are parsed correctly\n- data, meta = tmy.read_tmy3(TMY3_SOLARANYWHERE, map_variables=False)\n+ data, meta = tmy.read_tmy3(TMY3_SOLARANYWHERE, encoding='iso-8859-1',\n+ map_variables=False)\n pd.testing.assert_index_equal(data.index, solaranywhere_index)\n assert meta['USAF'] == 0\n assert meta['Name'] == 'Burlington United States'\n", "problem_statement": "SolarAnywhere File -- pvlib.iotools.read_tmy3 Bug\n@AdamRJensen \r\n\r\nThere's a bug report for reading SolarAnywhere Files with using the pvlib.iotools.read_tmy3 function. This bug is in the TMY3 file (I think?)\r\n\r\n\r\n\r\n\n", "hints_text": "Interesting, did this come up during the 2023 PVPMC workshop? These functions are meant to read the legacy TMY files from the [NSRDB archives](https://nsrdb.nrel.gov/data-sets/archives), but because SolarAnywhere TGY files are similar, you may also be able to read them with `pvlib.iotools.read_tmy3()` but you might need to edit the SolarAnywhere file to match the NSRDB TMY3 file format more closely. Can you paste the exact error message you got when trying to read the SolarAnywhere file?\nThe error appeared when one of the hackathon participants tried to read [this SolarAnywhere](https://raw.githubusercontent.com/PVSC-Python-Tutorials/PVPMC_2023/main/data/SolarAnywhere%20Typical%20DNI%20Year%20Lat_40_75%20Lon_-111_85%20TMY3%20format.csv) file.\r\n\r\nThere was an unknown character in the `meta['USAF']` value that couldn't be converted to an int.\r\n\r\nHowever, I cannot reproduce the error. I wonder if it was caused by the way the participant saved that file locally.\r\n\nI can't reproduce the error either.\r\n\r\n@PGRenewables what version of pvlib were you using? You can check that by writing ``pvlib.__version__``.\r\nAlso, if you could upload the file you saved locally, that would be great.\nRegardless, encoding problems are nightmarish at times, I wonder if we should dedicate a short troubleshooting section to it as perhaps we've already done for time zones?\n@AdamRJensen \r\n\r\nPVLib Version 0.9.2\r\n\r\n[PVLib Tutorial.zip](https://github.com/pvlib/pvlib-python/files/11456496/PVLib.Tutorial.zip)\r\n\r\nI included the files that I was working with in this zip file.\n@PGRenewables Thanks! Can you upload the data file itself as well? Since they can't reproduce the error with the original file, a next step is to check whether there is some difference between the original data file and the one you're using. \nHi @kandersolar , this is the file that I was using. Thank you so much! \r\n\r\n\r\n[SolarAnywhere Typical DNI Year Lat_40_75 Lon_-111_85_TMY3_format.csv](https://github.com/pvlib/pvlib-python/files/11466930/SolarAnywhere.Typical.DNI.Year.Lat_40_75.Lon_-111_85_TMY3_format.csv)\r\n\n`print(open(filename, 'r').read(5))` shows that the file @PGRenewables just uploaded differs from the original in that it starts with `\u00ef\u00bb\u00bf`, which google says is a [Byte Order Mark](https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding) for UTF-8. I also notice that the date format inside the CSV data is different in this file (`01/01/2004` versus `1/1/2004`). I speculate that the data got read into some tool that understands CSV (Excel?) and then re-exported before getting used with pvlib?\r\n\r\nThe internet suggests using `encoding='utf-8-sig'` for files with this BOM. We could try to handle this case, but I'm nervous that `read_tmy3` will turn into a rat's nest if it keeps trying to handle encoding issues itself. I still think exposing `encoding` as an optional parameter is worth considering (https://github.com/pvlib/pvlib-python/pull/1494#issuecomment-1194011363).", "created_at": "2023-05-16T18:00:13Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_tmy.py::test_solaranywhere_tmy3"], "PASS_TO_PASS": ["pvlib/tests/iotools/test_tmy.py::test_read_tmy3", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_recolumn", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_norecolumn", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_raise_valueerror", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_map_variables", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_map_variables_deprecating_warning", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_coerce_year", "pvlib/tests/iotools/test_tmy.py::test_read_tmy3_no_coerce_year", "pvlib/tests/iotools/test_tmy.py::test_read_tmy2", "pvlib/tests/iotools/test_tmy.py::test_gh865_read_tmy3_feb_leapyear_hr24"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1852", "base_commit": "f8b129418025b47ad669ba4802d03348a275e329", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -15,7 +15,7 @@\n import pandas as pd\n from dataclasses import dataclass\n from abc import ABC, abstractmethod\n-from typing import Optional\n+from typing import Optional, Union\n \n from pvlib._deprecation import deprecated, warn_deprecated\n \n@@ -1411,12 +1411,21 @@ class SingleAxisTrackerMount(AbstractMount):\n A value denoting the compass direction along which the axis of\n rotation lies, measured east of north. [degrees]\n \n- max_angle : float, default 90\n- A value denoting the maximum rotation angle\n+ max_angle : float or tuple, default 90\n+ A value denoting the maximum rotation angle, in decimal degrees,\n of the one-axis tracker from its horizontal position (horizontal\n- if axis_tilt = 0). A max_angle of 90 degrees allows the tracker\n- to rotate to a vertical position to point the panel towards a\n- horizon. max_angle of 180 degrees allows for full rotation. [degrees]\n+ if axis_tilt = 0). If a float is provided, it represents the maximum\n+ rotation angle, and the minimum rotation angle is assumed to be the\n+ opposite of the maximum angle. If a tuple of (min_angle, max_angle) is\n+ provided, it represents both the minimum and maximum rotation angles.\n+\n+ A rotation to 'max_angle' is a counter-clockwise rotation about the\n+ y-axis of the tracker coordinate system. For example, for a tracker\n+ with 'axis_azimuth' oriented to the south, a rotation to 'max_angle'\n+ is towards the west, and a rotation toward 'min_angle' is in the\n+ opposite direction, toward the east. Hence a max_angle of 180 degrees\n+ (equivalent to max_angle = (-180, 180)) allows the tracker to achieve\n+ its full rotation capability.\n \n backtrack : bool, default True\n Controls whether the tracker has the capability to \"backtrack\"\n@@ -1452,7 +1461,7 @@ class SingleAxisTrackerMount(AbstractMount):\n \"\"\"\n axis_tilt: float = 0.0\n axis_azimuth: float = 0.0\n- max_angle: float = 90.0\n+ max_angle: Union[float, tuple] = 90.0\n backtrack: bool = True\n gcr: float = 2.0/7.0\n cross_axis_tilt: float = 0.0\ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -44,12 +44,21 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n A value denoting the compass direction along which the axis of\n rotation lies. Measured in decimal degrees east of north.\n \n- max_angle : float, default 90\n+ max_angle : float or tuple, default 90\n A value denoting the maximum rotation angle, in decimal degrees,\n of the one-axis tracker from its horizontal position (horizontal\n- if axis_tilt = 0). A max_angle of 90 degrees allows the tracker\n- to rotate to a vertical position to point the panel towards a\n- horizon. max_angle of 180 degrees allows for full rotation.\n+ if axis_tilt = 0). If a float is provided, it represents the maximum\n+ rotation angle, and the minimum rotation angle is assumed to be the\n+ opposite of the maximum angle. If a tuple of (min_angle, max_angle) is\n+ provided, it represents both the minimum and maximum rotation angles.\n+\n+ A rotation to 'max_angle' is a counter-clockwise rotation about the\n+ y-axis of the tracker coordinate system. For example, for a tracker\n+ with 'axis_azimuth' oriented to the south, a rotation to 'max_angle'\n+ is towards the west, and a rotation toward 'min_angle' is in the\n+ opposite direction, toward the east. Hence a max_angle of 180 degrees\n+ (equivalent to max_angle = (-180, 180)) allows the tracker to achieve\n+ its full rotation capability.\n \n backtrack : bool, default True\n Controls whether the tracker has the capability to \"backtrack\"\n@@ -190,7 +199,16 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n \n # NOTE: max_angle defined relative to zero-point rotation, not the\n # system-plane normal\n- tracker_theta = np.clip(tracker_theta, -max_angle, max_angle)\n+\n+ # Determine minimum and maximum rotation angles based on max_angle.\n+ # If max_angle is a single value, assume min_angle is the negative.\n+ if np.isscalar(max_angle):\n+ min_angle = -max_angle\n+ else:\n+ min_angle, max_angle = max_angle\n+\n+ # Clip tracker_theta between the minimum and maximum angles.\n+ tracker_theta = np.clip(tracker_theta, min_angle, max_angle)\n \n # Calculate auxiliary angles\n surface = calc_surface_orientation(tracker_theta, axis_tilt, axis_azimuth)\n", "test_patch": "diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -2422,6 +2422,15 @@ def test_SingleAxisTrackerMount_get_orientation(single_axis_tracker_mount):\n assert actual[key] == pytest.approx(expected_value), err_msg\n \n \n+def test_SingleAxisTrackerMount_get_orientation_asymmetric_max():\n+ mount = pvsystem.SingleAxisTrackerMount(max_angle=(-30, 45))\n+ expected = {'surface_tilt': [45, 30], 'surface_azimuth': [90, 270]}\n+ actual = mount.get_orientation([60, 60], [90, 270])\n+ for key, expected_value in expected.items():\n+ err_msg = f\"{key} value incorrect\"\n+ assert actual[key] == pytest.approx(expected_value), err_msg\n+\n+\n def test_dc_ohms_from_percent():\n expected = .1425\n out = pvsystem.dc_ohms_from_percent(38, 8, 3, 1, 1)\ndiff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -151,6 +151,22 @@ def test_max_angle():\n assert_frame_equal(expect, tracker_data)\n \n \n+def test_min_angle():\n+ apparent_zenith = pd.Series([60])\n+ apparent_azimuth = pd.Series([270])\n+ tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth,\n+ axis_tilt=0, axis_azimuth=0,\n+ max_angle=(-45, 50), backtrack=True,\n+ gcr=2.0/7.0)\n+\n+ expect = pd.DataFrame({'aoi': 15, 'surface_azimuth': 270,\n+ 'surface_tilt': 45, 'tracker_theta': -45},\n+ index=[0], dtype=np.float64)\n+ expect = expect[SINGLEAXIS_COL_ORDER]\n+\n+ assert_frame_equal(expect, tracker_data)\n+\n+\n def test_backtrack():\n apparent_zenith = pd.Series([80])\n apparent_azimuth = pd.Series([90])\n", "problem_statement": "Add `min_angle` argument to `tracking.singleaxis`\nIn `tracking.singleaxis` the minimum angle of the tracker is assumed to be opposite of the maximum angle, although in some cases the minimum angle could be different. NREL SAM doesn't support that but PVsyst does.\r\n\r\nIn order to support non symmetrical limiting angles, `tracking.singleaxis` should have another, optional, input, `min_angle`. By default, if not supplied (i.e. value is `None`), the current behavior (`min_angle = -max_angle`) would apply.\r\n\r\nCan I propose a PR for this, with modifications to `tracking.singleaxis`, `tracking.SingleAxisTracker` and to `pvsystem.SingleAxisTrackerMount` + corresponding tests?\n", "hints_text": "I'm in favor of pvlib being able to handle asymmetrical rotation limits in principle, but I'm curious what situation has that asymmetry in practice. @MichalArieli do you have a particular real-world application in mind?\r\n\r\nRather than separate `min_` and `max_` parameters, I think I'd favor a single parameter that accepts a tuple as @cwhanse suggested here: https://github.com/pvlib/pvlib-python/pull/823#issuecomment-561399605. I'm not sure about renaming `max_angle` to something else though. `singleaxis(..., max_angle=(-40, 45))` seems okay to me. And since symmetrical limits is by far the more common case, I think the parameter should continue accepting a single value (in which case symmetry is assumed) in addition to a tuple.\r\n\r\n`tracking.SingleAxisTracker` is being removed anyway (#1771), so no point in making any additions there. Whatever changes we decide on here should only be made to `tracking.singleaxis` and `pvsystem.SingleAxisTrackerMount` (and tests, of course).\n@kandersolar Thanks for the quick response! \r\n\r\nRegarding handling asymmetry in rotation limits, let's take the example of a tracker placed at a 90-degree axis azimuth, tracking south-north. If the sun is at azimuth 80 degrees during sunrise, the algorithm will guide the tracker to briefly turn north. To prevent that we can implement a maximum angle limit for northward movement to ensure smooth and continuous motion and taking into account the time needed for such a large angular change.\r\n\r\nI agree its better to have a single parameter that accepts a tuple/ single value. Would you like me to apply these changes and send for a PR? \r\n\n> Would you like me to apply these changes and send for a PR?\r\n\r\nPlease do!", "created_at": "2023-09-12T16:46:37Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation_asymmetric_max", "pvlib/tests/test_tracking.py::test_min_angle"], "PASS_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss_deprecated", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_recombination", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[lambertw]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[brentq]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[newton]", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_Array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]", "pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_calc_axis_tilt", "pvlib/tests/test_tracking.py::test_slope_aware_backtracking", "pvlib/tests/test_tracking.py::test_singleaxis_aoi_gh1221", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_types", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_kwargs", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_special"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1469", "base_commit": "04e3ffd5ed2b8504e45ee0dc6bc7194d2440012d", "patch": "diff --git a/pvlib/clearsky.py b/pvlib/clearsky.py\n--- a/pvlib/clearsky.py\n+++ b/pvlib/clearsky.py\n@@ -960,8 +960,8 @@ def bird(zenith, airmass_relative, aod380, aod500, precipitable_water,\n Extraterrestrial radiation [W/m^2], defaults to 1364[W/m^2]\n asymmetry : numeric\n Asymmetry factor, defaults to 0.85\n- albedo : numeric\n- Albedo, defaults to 0.2\n+ albedo : numeric, default 0.2\n+ Ground surface albedo. [unitless]\n \n Returns\n -------\ndiff --git a/pvlib/irradiance.py b/pvlib/irradiance.py\n--- a/pvlib/irradiance.py\n+++ b/pvlib/irradiance.py\n@@ -304,7 +304,7 @@ def beam_component(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n def get_total_irradiance(surface_tilt, surface_azimuth,\n solar_zenith, solar_azimuth,\n dni, ghi, dhi, dni_extra=None, airmass=None,\n- albedo=.25, surface_type=None,\n+ albedo=0.25, surface_type=None,\n model='isotropic',\n model_perez='allsitescomposite1990'):\n r\"\"\"\n@@ -344,7 +344,7 @@ def get_total_irradiance(surface_tilt, surface_azimuth,\n airmass : None or numeric, default None\n Relative airmass (not adjusted for pressure). [unitless]\n albedo : numeric, default 0.25\n- Surface albedo. [unitless]\n+ Ground surface albedo. [unitless]\n surface_type : None or str, default None\n Surface type. See :py:func:`~pvlib.irradiance.get_ground_diffuse` for\n the list of accepted values.\n@@ -1872,7 +1872,7 @@ def gti_dirint(poa_global, aoi, solar_zenith, solar_azimuth, times,\n applied.\n \n albedo : numeric, default 0.25\n- Surface albedo\n+ Ground surface albedo. [unitless]\n \n model : String, default 'perez'\n Irradiance model. See :py:func:`get_sky_diffuse` for allowed values.\ndiff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -1339,6 +1339,16 @@ def _prep_inputs_solar_pos(self, weather):\n **kwargs)\n return self\n \n+ def _prep_inputs_albedo(self, weather):\n+ \"\"\"\n+ Get albedo from weather\n+ \"\"\"\n+ try:\n+ self.results.albedo = _tuple_from_dfs(weather, 'albedo')\n+ except KeyError:\n+ self.results.albedo = None\n+ return self\n+\n def _prep_inputs_airmass(self):\n \"\"\"\n Assign airmass\n@@ -1471,11 +1481,17 @@ def prepare_inputs(self, weather):\n \n Parameters\n ----------\n- weather : DataFrame, or tuple or list of DataFrame\n+ weather : DataFrame, or tuple or list of DataFrames\n Required column names include ``'dni'``, ``'ghi'``, ``'dhi'``.\n- Optional column names are ``'wind_speed'``, ``'temp_air'``; if not\n+ Optional column names are ``'wind_speed'``, ``'temp_air'``,\n+ ``'albedo'``.\n+\n+ If optional columns ``'wind_speed'``, ``'temp_air'`` are not\n provided, air temperature of 20 C and wind speed\n- of 0 m/s will be added to the DataFrame.\n+ of 0 m/s will be added to the `weather` DataFrame.\n+\n+ If optional column ``'albedo'`` is provided, albedo values in the\n+ ModelChain's PVSystem.arrays are ignored.\n \n If `weather` is a tuple or list, it must be of the same length and\n order as the Arrays of the ModelChain's PVSystem.\n@@ -1494,7 +1510,7 @@ def prepare_inputs(self, weather):\n Notes\n -----\n Assigns attributes to ``results``: ``times``, ``weather``,\n- ``solar_position``, ``airmass``, ``total_irrad``, ``aoi``\n+ ``solar_position``, ``airmass``, ``total_irrad``, ``aoi``, ``albedo``.\n \n See also\n --------\n@@ -1507,6 +1523,7 @@ def prepare_inputs(self, weather):\n \n self._prep_inputs_solar_pos(weather)\n self._prep_inputs_airmass()\n+ self._prep_inputs_albedo(weather)\n \n # PVSystem.get_irradiance and SingleAxisTracker.get_irradiance\n # and PVSystem.get_aoi and SingleAxisTracker.get_aoi\n@@ -1531,6 +1548,7 @@ def prepare_inputs(self, weather):\n _tuple_from_dfs(self.results.weather, 'dni'),\n _tuple_from_dfs(self.results.weather, 'ghi'),\n _tuple_from_dfs(self.results.weather, 'dhi'),\n+ albedo=self.results.albedo,\n airmass=self.results.airmass['airmass_relative'],\n model=self.transposition_model\n )\n@@ -1724,16 +1742,32 @@ def run_model(self, weather):\n Parameters\n ----------\n weather : DataFrame, or tuple or list of DataFrame\n- Irradiance column names must include ``'dni'``, ``'ghi'``, and\n- ``'dhi'``. If optional columns ``'temp_air'`` and ``'wind_speed'``\n+ Column names must include:\n+\n+ - ``'dni'``\n+ - ``'ghi'``\n+ - ``'dhi'``\n+\n+ Optional columns are:\n+\n+ - ``'temp_air'``\n+ - ``'cell_temperature'``\n+ - ``'module_temperature'``\n+ - ``'wind_speed'``\n+ - ``'albedo'``\n+\n+ If optional columns ``'temp_air'`` and ``'wind_speed'``\n are not provided, air temperature of 20 C and wind speed of 0 m/s\n are added to the DataFrame. If optional column\n ``'cell_temperature'`` is provided, these values are used instead\n- of `temperature_model`. If optional column `module_temperature`\n+ of `temperature_model`. If optional column ``'module_temperature'``\n is provided, `temperature_model` must be ``'sapm'``.\n \n- If list or tuple, must be of the same length and order as the\n- Arrays of the ModelChain's PVSystem.\n+ If optional column ``'albedo'`` is provided, ``'albedo'`` may not\n+ be present on the ModelChain's PVSystem.Arrays.\n+\n+ If weather is a list or tuple, it must be of the same length and\n+ order as the Arrays of the ModelChain's PVSystem.\n \n Returns\n -------\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -134,7 +134,7 @@ class PVSystem:\n a single array is created from the other parameters (e.g.\n `surface_tilt`, `surface_azimuth`). Must contain at least one Array,\n if length of arrays is 0 a ValueError is raised. If `arrays` is\n- specified the following parameters are ignored:\n+ specified the following PVSystem parameters are ignored:\n \n - `surface_tilt`\n - `surface_azimuth`\n@@ -157,13 +157,16 @@ class PVSystem:\n North=0, East=90, South=180, West=270.\n \n albedo : None or float, default None\n- The ground albedo. If ``None``, will attempt to use\n- ``surface_type`` and ``irradiance.SURFACE_ALBEDOS``\n- to lookup albedo.\n+ Ground surface albedo. If ``None``, then ``surface_type`` is used\n+ to look up a value in ``irradiance.SURFACE_ALBEDOS``.\n+ If ``surface_type`` is also None then a ground surface albedo\n+ of 0.25 is used. For time-dependent albedos, add ``'albedo'`` to\n+ the input ``'weather'`` DataFrame for\n+ :py:class:`pvlib.modelchain.ModelChain` methods.\n \n surface_type : None or string, default None\n- The ground surface type. See ``irradiance.SURFACE_ALBEDOS``\n- for valid values.\n+ The ground surface type. See ``irradiance.SURFACE_ALBEDOS`` for\n+ valid values.\n \n module : None or string, default None\n The model name of the modules.\n@@ -333,30 +336,32 @@ def get_aoi(self, solar_zenith, solar_azimuth):\n \n @_unwrap_single_value\n def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n- dni_extra=None, airmass=None, model='haydavies',\n- **kwargs):\n+ albedo=None, dni_extra=None, airmass=None,\n+ model='haydavies', **kwargs):\n \"\"\"\n Uses the :py:func:`irradiance.get_total_irradiance` function to\n calculate the plane of array irradiance components on a tilted\n- surface defined by ``self.surface_tilt``,\n- ``self.surface_azimuth``, and ``self.albedo``.\n+ surface defined by ``self.surface_tilt`` and ``self.surface_azimuth```.\n \n Parameters\n ----------\n- solar_zenith : float or Series.\n+ solar_zenith : float or Series\n Solar zenith angle.\n- solar_azimuth : float or Series.\n+ solar_azimuth : float or Series\n Solar azimuth angle.\n dni : float or Series or tuple of float or Series\n- Direct Normal Irradiance\n+ Direct Normal Irradiance. [W/m2]\n ghi : float or Series or tuple of float or Series\n- Global horizontal irradiance\n+ Global horizontal irradiance. [W/m2]\n dhi : float or Series or tuple of float or Series\n- Diffuse horizontal irradiance\n- dni_extra : None, float or Series, default None\n- Extraterrestrial direct normal irradiance\n+ Diffuse horizontal irradiance. [W/m2]\n+ albedo : None, float or Series, default None\n+ Ground surface albedo. [unitless]\n+ dni_extra : None, float, Series or tuple of float or Series,\n+ default None\n+ Extraterrestrial direct normal irradiance. [W/m2]\n airmass : None, float or Series, default None\n- Airmass\n+ Airmass. [unitless]\n model : String, default 'haydavies'\n Irradiance model.\n \n@@ -376,17 +381,26 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n poa_irradiance : DataFrame or tuple of DataFrame\n Column names are: ``'poa_global', 'poa_direct', 'poa_diffuse',\n 'poa_sky_diffuse', 'poa_ground_diffuse'``.\n+\n+ See also\n+ --------\n+ :py:func:`pvlib.irradiance.get_total_irradiance`\n \"\"\"\n dni = self._validate_per_array(dni, system_wide=True)\n ghi = self._validate_per_array(ghi, system_wide=True)\n dhi = self._validate_per_array(dhi, system_wide=True)\n+\n+ albedo = self._validate_per_array(albedo, system_wide=True)\n+\n return tuple(\n array.get_irradiance(solar_zenith, solar_azimuth,\n dni, ghi, dhi,\n- dni_extra, airmass, model,\n+ albedo=albedo,\n+ dni_extra=dni_extra, airmass=airmass,\n+ model=model,\n **kwargs)\n- for array, dni, ghi, dhi in zip(\n- self.arrays, dni, ghi, dhi\n+ for array, dni, ghi, dhi, albedo in zip(\n+ self.arrays, dni, ghi, dhi, albedo\n )\n )\n \n@@ -1258,14 +1272,14 @@ class Array:\n If not provided, a FixedMount with zero tilt is used.\n \n albedo : None or float, default None\n- The ground albedo. If ``None``, will attempt to use\n- ``surface_type`` to look up an albedo value in\n- ``irradiance.SURFACE_ALBEDOS``. If a surface albedo\n- cannot be found then 0.25 is used.\n+ Ground surface albedo. If ``None``, then ``surface_type`` is used\n+ to look up a value in ``irradiance.SURFACE_ALBEDOS``.\n+ If ``surface_type`` is also None then a ground surface albedo\n+ of 0.25 is used.\n \n surface_type : None or string, default None\n- The ground surface type. See ``irradiance.SURFACE_ALBEDOS``\n- for valid values.\n+ The ground surface type. See ``irradiance.SURFACE_ALBEDOS`` for valid\n+ values.\n \n module : None or string, default None\n The model name of the modules.\n@@ -1425,15 +1439,14 @@ def get_aoi(self, solar_zenith, solar_azimuth):\n solar_zenith, solar_azimuth)\n \n def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n- dni_extra=None, airmass=None, model='haydavies',\n- **kwargs):\n+ albedo=None, dni_extra=None, airmass=None,\n+ model='haydavies', **kwargs):\n \"\"\"\n Get plane of array irradiance components.\n \n Uses the :py:func:`pvlib.irradiance.get_total_irradiance` function to\n calculate the plane of array irradiance components for a surface\n- defined by ``self.surface_tilt`` and ``self.surface_azimuth`` with\n- albedo ``self.albedo``.\n+ defined by ``self.surface_tilt`` and ``self.surface_azimuth``.\n \n Parameters\n ----------\n@@ -1442,15 +1455,17 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n solar_azimuth : float or Series.\n Solar azimuth angle.\n dni : float or Series\n- Direct Normal Irradiance\n- ghi : float or Series\n+ Direct normal irradiance. [W/m2]\n+ ghi : float or Series. [W/m2]\n Global horizontal irradiance\n dhi : float or Series\n- Diffuse horizontal irradiance\n+ Diffuse horizontal irradiance. [W/m2]\n+ albedo : None, float or Series, default None\n+ Ground surface albedo. [unitless]\n dni_extra : None, float or Series, default None\n- Extraterrestrial direct normal irradiance\n+ Extraterrestrial direct normal irradiance. [W/m2]\n airmass : None, float or Series, default None\n- Airmass\n+ Airmass. [unitless]\n model : String, default 'haydavies'\n Irradiance model.\n \n@@ -1463,7 +1478,14 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n poa_irradiance : DataFrame\n Column names are: ``'poa_global', 'poa_direct', 'poa_diffuse',\n 'poa_sky_diffuse', 'poa_ground_diffuse'``.\n+\n+ See also\n+ --------\n+ :py:func:`pvlib.irradiance.get_total_irradiance`\n \"\"\"\n+ if albedo is None:\n+ albedo = self.albedo\n+\n # not needed for all models, but this is easier\n if dni_extra is None:\n dni_extra = irradiance.get_extra_radiation(solar_zenith.index)\n@@ -1476,10 +1498,10 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n orientation['surface_azimuth'],\n solar_zenith, solar_azimuth,\n dni, ghi, dhi,\n+ albedo=albedo,\n dni_extra=dni_extra,\n airmass=airmass,\n model=model,\n- albedo=self.albedo,\n **kwargs)\n \n def get_iam(self, aoi, iam_model='physical'):\ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -187,7 +187,8 @@ def get_aoi(self, surface_tilt, surface_azimuth, solar_zenith,\n @_unwrap_single_value\n def get_irradiance(self, surface_tilt, surface_azimuth,\n solar_zenith, solar_azimuth, dni, ghi, dhi,\n- dni_extra=None, airmass=None, model='haydavies',\n+ albedo=None, dni_extra=None, airmass=None,\n+ model='haydavies',\n **kwargs):\n \"\"\"\n Uses the :func:`irradiance.get_total_irradiance` function to\n@@ -214,6 +215,8 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n Global horizontal irradiance\n dhi : float or Series\n Diffuse horizontal irradiance\n+ albedo : None, float or Series, default None\n+ Ground surface albedo. [unitless]\n dni_extra : float or Series, default None\n Extraterrestrial direct normal irradiance\n airmass : float or Series, default None\n@@ -244,6 +247,13 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n ghi = self._validate_per_array(ghi, system_wide=True)\n dhi = self._validate_per_array(dhi, system_wide=True)\n \n+ if albedo is None:\n+ # assign default albedo here because SingleAxisTracker\n+ # initializes albedo to None\n+ albedo = 0.25\n+\n+ albedo = self._validate_per_array(albedo, system_wide=True)\n+\n return tuple(\n irradiance.get_total_irradiance(\n surface_tilt,\n@@ -254,10 +264,10 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n dni_extra=dni_extra,\n airmass=airmass,\n model=model,\n- albedo=self.arrays[0].albedo,\n+ albedo=albedo,\n **kwargs)\n- for array, dni, ghi, dhi in zip(\n- self.arrays, dni, ghi, dhi\n+ for array, dni, ghi, dhi, albedo in zip(\n+ self.arrays, dni, ghi, dhi, albedo\n )\n )\n \n", "test_patch": "diff --git a/pvlib/tests/test_clearsky.py b/pvlib/tests/test_clearsky.py\n--- a/pvlib/tests/test_clearsky.py\n+++ b/pvlib/tests/test_clearsky.py\n@@ -756,6 +756,30 @@ def test_bird():\n assert np.allclose(\n testdata['Dif Hz'].where(dusk, 0.), diffuse_horz[1:48], rtol=1e-3\n )\n+ # repeat test with albedo as a Series\n+ alb_series = pd.Series(0.2, index=times)\n+ irrads = clearsky.bird(\n+ zenith, airmass, aod_380nm, aod_500nm, h2o_cm, o3_cm, press_mB * 100.,\n+ etr, b_a, alb_series\n+ )\n+ Eb, Ebh, Gh, Dh = (irrads[_] for _ in field_names)\n+ direct_beam = pd.Series(np.where(dawn, Eb, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Direct Beam'].where(dusk, 0.), direct_beam[1:48], rtol=1e-3\n+ )\n+ direct_horz = pd.Series(np.where(dawn, Ebh, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Direct Hz'].where(dusk, 0.), direct_horz[1:48], rtol=1e-3\n+ )\n+ global_horz = pd.Series(np.where(dawn, Gh, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Global Hz'].where(dusk, 0.), global_horz[1:48], rtol=1e-3\n+ )\n+ diffuse_horz = pd.Series(np.where(dawn, Dh, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Dif Hz'].where(dusk, 0.), diffuse_horz[1:48], rtol=1e-3\n+ )\n+\n # test keyword parameters\n irrads2 = clearsky.bird(\n zenith, airmass, aod_380nm, aod_500nm, h2o_cm, dni_extra=etr\ndiff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py\n--- a/pvlib/tests/test_irradiance.py\n+++ b/pvlib/tests/test_irradiance.py\n@@ -120,29 +120,38 @@ def test_get_extra_radiation_invalid():\n irradiance.get_extra_radiation(300, method='invalid')\n \n \n-def test_grounddiffuse_simple_float():\n+def test_get_ground_diffuse_simple_float():\n result = irradiance.get_ground_diffuse(40, 900)\n assert_allclose(result, 26.32000014911496)\n \n \n-def test_grounddiffuse_simple_series(irrad_data):\n+def test_get_ground_diffuse_simple_series(irrad_data):\n ground_irrad = irradiance.get_ground_diffuse(40, irrad_data['ghi'])\n assert ground_irrad.name == 'diffuse_ground'\n \n \n-def test_grounddiffuse_albedo_0(irrad_data):\n+def test_get_ground_diffuse_albedo_0(irrad_data):\n ground_irrad = irradiance.get_ground_diffuse(\n 40, irrad_data['ghi'], albedo=0)\n assert 0 == ground_irrad.all()\n \n \n+def test_get_ground_diffuse_albedo_series(times):\n+ albedo = pd.Series(0.2, index=times)\n+ ground_irrad = irradiance.get_ground_diffuse(\n+ 45, pd.Series(1000, index=times), albedo)\n+ expected = albedo * 0.5 * (1 - np.sqrt(2) / 2.) * 1000\n+ expected.name = 'diffuse_ground'\n+ assert_series_equal(ground_irrad, expected)\n+\n+\n def test_grounddiffuse_albedo_invalid_surface(irrad_data):\n with pytest.raises(KeyError):\n irradiance.get_ground_diffuse(\n 40, irrad_data['ghi'], surface_type='invalid')\n \n \n-def test_grounddiffuse_albedo_surface(irrad_data):\n+def test_get_ground_diffuse_albedo_surface(irrad_data):\n result = irradiance.get_ground_diffuse(40, irrad_data['ghi'],\n surface_type='sand')\n assert_allclose(result, [0, 3.731058, 48.778813, 12.035025], atol=1e-4)\n@@ -387,6 +396,26 @@ def test_get_total_irradiance(irrad_data, ephem_data, dni_et,\n 'poa_ground_diffuse']\n \n \n+def test_get_total_irradiance_albedo(\n+ irrad_data, ephem_data, dni_et, relative_airmass):\n+ models = ['isotropic', 'klucher',\n+ 'haydavies', 'reindl', 'king', 'perez']\n+ albedo = pd.Series(0.2, index=ephem_data.index)\n+ for model in models:\n+ total = irradiance.get_total_irradiance(\n+ 32, 180,\n+ ephem_data['apparent_zenith'], ephem_data['azimuth'],\n+ dni=irrad_data['dni'], ghi=irrad_data['ghi'],\n+ dhi=irrad_data['dhi'],\n+ dni_extra=dni_et, airmass=relative_airmass,\n+ model=model,\n+ albedo=albedo)\n+\n+ assert total.columns.tolist() == ['poa_global', 'poa_direct',\n+ 'poa_diffuse', 'poa_sky_diffuse',\n+ 'poa_ground_diffuse']\n+\n+\n @pytest.mark.parametrize('model', ['isotropic', 'klucher',\n 'haydavies', 'reindl', 'king', 'perez'])\n def test_get_total_irradiance_scalars(model):\n@@ -698,6 +727,14 @@ def test_gti_dirint():\n \n assert_frame_equal(output, expected)\n \n+ # test with albedo as a Series\n+ albedo = pd.Series(0.05, index=times)\n+ output = irradiance.gti_dirint(\n+ poa_global, aoi, zenith, azimuth, times, surface_tilt, surface_azimuth,\n+ albedo=albedo)\n+\n+ assert_frame_equal(output, expected)\n+\n # test temp_dew input\n temp_dew = np.array([70, 80, 20])\n output = irradiance.gti_dirint(\ndiff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -497,6 +497,24 @@ def test_prepare_inputs_multi_weather(\n assert len(mc.results.total_irrad) == num_arrays\n \n \[email protected](\"input_type\", [tuple, list])\n+def test_prepare_inputs_albedo_in_weather(\n+ sapm_dc_snl_ac_system_Array, location, input_type):\n+ times = pd.date_range(start='20160101 1200-0700',\n+ end='20160101 1800-0700', freq='6H')\n+ mc = ModelChain(sapm_dc_snl_ac_system_Array, location)\n+ weather = pd.DataFrame({'ghi': 1, 'dhi': 1, 'dni': 1, 'albedo': 0.5},\n+ index=times)\n+ # weather as a single DataFrame\n+ mc.prepare_inputs(weather)\n+ num_arrays = sapm_dc_snl_ac_system_Array.num_arrays\n+ assert len(mc.results.total_irrad) == num_arrays\n+ # repeat with tuple of weather\n+ mc.prepare_inputs(input_type((weather, weather)))\n+ num_arrays = sapm_dc_snl_ac_system_Array.num_arrays\n+ assert len(mc.results.total_irrad) == num_arrays\n+\n+\n def test_prepare_inputs_no_irradiance(sapm_dc_snl_ac_system, location):\n mc = ModelChain(sapm_dc_snl_ac_system, location)\n weather = pd.DataFrame()\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -1689,14 +1689,37 @@ def test_PVSystem_get_irradiance():\n irrads['dhi'])\n \n expected = pd.DataFrame(data=np.array(\n- [[ 883.65494055, 745.86141676, 137.79352379, 126.397131 ,\n- 11.39639279],\n- [ 0. , -0. , 0. , 0. , 0. ]]),\n+ [[883.65494055, 745.86141676, 137.79352379, 126.397131, 11.39639279],\n+ [0., -0., 0., 0., 0.]]),\n columns=['poa_global', 'poa_direct',\n 'poa_diffuse', 'poa_sky_diffuse',\n 'poa_ground_diffuse'],\n index=times)\n+ assert_frame_equal(irradiance, expected, check_less_precise=2)\n+\n \n+def test_PVSystem_get_irradiance_albedo():\n+ system = pvsystem.PVSystem(surface_tilt=32, surface_azimuth=135)\n+ times = pd.date_range(start='20160101 1200-0700',\n+ end='20160101 1800-0700', freq='6H')\n+ location = Location(latitude=32, longitude=-111)\n+ solar_position = location.get_solarposition(times)\n+ irrads = pd.DataFrame({'dni': [900, 0], 'ghi': [600, 0], 'dhi': [100, 0],\n+ 'albedo': [0.5, 0.5]},\n+ index=times)\n+ # albedo as a Series\n+ irradiance = system.get_irradiance(solar_position['apparent_zenith'],\n+ solar_position['azimuth'],\n+ irrads['dni'],\n+ irrads['ghi'],\n+ irrads['dhi'],\n+ albedo=irrads['albedo'])\n+ expected = pd.DataFrame(data=np.array(\n+ [[895.05134334, 745.86141676, 149.18992658, 126.397131, 22.79279558],\n+ [0., -0., 0., 0., 0.]]),\n+ columns=['poa_global', 'poa_direct', 'poa_diffuse', 'poa_sky_diffuse',\n+ 'poa_ground_diffuse'],\n+ index=times)\n assert_frame_equal(irradiance, expected, check_less_precise=2)\n \n \ndiff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -393,6 +393,25 @@ def test_get_irradiance():\n \n assert_frame_equal(irradiance, expected, check_less_precise=2)\n \n+ # test with albedo as a Series\n+ irrads['albedo'] = [0.5, 0.5]\n+ with np.errstate(invalid='ignore'):\n+ irradiance = system.get_irradiance(tracker_data['surface_tilt'],\n+ tracker_data['surface_azimuth'],\n+ solar_zenith,\n+ solar_azimuth,\n+ irrads['dni'],\n+ irrads['ghi'],\n+ irrads['dhi'],\n+ albedo=irrads['albedo'])\n+\n+ expected = pd.Series(data=[21.05514984, nan], index=times,\n+ name='poa_ground_diffuse')\n+\n+ assert_series_equal(irradiance['poa_ground_diffuse'], expected,\n+ check_less_precise=2)\n+\n+\n \n def test_SingleAxisTracker___repr__():\n with pytest.warns(pvlibDeprecationWarning):\n", "problem_statement": "ModelChain should accept albedo in weather dataframe\n**Is your feature request related to a problem? Please describe.**\r\nAlbedo is treated as a scalar constant in pvlib, but it is of course a function of the weather and changes throughout the year. Albedo is currently set in the PVSystem or Array and cannot be altered using the ModelChain. Albedo is provided as a timeseries from many weather data services as well as through NREL's NSRBD and it would be useful to provide this data to the ModelChain.\r\n\r\nAdditionally, treating albedo as property of the Array seems to conflict with the [PVSystem Design Philosophy](https://pvlib-python.readthedocs.io/en/stable/pvsystem.html#design-philosophy), which highlights the separation of the PV system and the exogenous variables, such as the weather.\r\n\r\n**Describe the solution you'd like**\r\nModelChain.run_model() should accept albedo in the weather dataframe, like temperature and ghi.\r\n\r\n**Describe alternatives you've considered**\r\nAn alternative we have implemented is calling ModelChain.run_model() on each row of a dataframe and manually updating the albedo of the array in each tilmestep. This probably has some side effects that we are unaware of.\r\n\n", "hints_text": "I think I agree that it would make more sense to pass around ground albedo with the weather data instead of treating it as a characteristic of the array. \r\n\r\n> Albedo is treated as a scalar constant in pvlib\r\n\r\n> An alternative we have implemented is calling ModelChain.run_model() on each row of a dataframe and manually updating the albedo of the array in each tilmestep. \r\n\r\nIt is true that the docs for `Array` and `PVSystem` say that `albedo` is a float, but I think it also works to set albedo to a time series that matches the weather you pass to `ModelChain.run_model()`. At least that saves you from looping w/ scalar albedo values. \nI agree that albedo can change with e.g., precipitation or season, but it is also a property of the bare ground surface, and it is that perspective that put albedo with the system parameters. One use case for not having albedo in the weather data would be to evaluate the effect of different ground cover on array output.\r\n\r\nI am only away of the NSRDB offering albedo with weather data; are there other sources?\r\n\r\nI'm +1 on allowing `albedo` to be a Series. I'm neutral on bundling albedo with weather data, but I don't see a better option. We only have two data structures that supply `ModelChain`: the `weather` DataFrame, and the `PVSystem` instance. I don't think it is practical to create a third just for `albedo`, and it isn't any more work to add or modify `albedo` to `weather` than it is to extract `albedo` from downloaded weather data and add it to `PVSystem`.\r\n\r\n\nTo clarify my above message, I think it *already* works to set `PVSystem.albedo` or `Array.albedo` to a Series, despite the docs saying it must be float. \r\n\r\n> are there other sources?\r\n\r\nA non-exhaustive list of examples: [SolarAnywhere](https://www.solaranywhere.com/support/data-fields/albedo/), [SolarGIS](https://solargis.com/docs/getting-started/data-parameters), [MERRA2](https://disc.gsfc.nasa.gov/datasets/M2TMNXRAD_5.12.4/summary)\nDoes anyone know if including time-specific albedo this has been shown to be even more important with bifacials?\r\n\r\n(I would think yes.)\n> Does anyone know if including time-specific albedo this has been shown to be even more important with bifacials?\r\n> \r\n> (I would think yes.)\r\n\r\nYes, it is more important than for single-sided modules. There are ground surfaces where the albedo depends on the solar elevation and hence time of day.\r\n\r\nOne caution about albedo from satellite-derived irradiance: those values are at least km^2 scale, and are observed from space, whereas a PV model is assuming that the albedo is localized (m^2) and has been determined from the irradiance reaching the ground. [SolarAnywhere ](https://www.solaranywhere.com/support/data-fields/albedo/)provides an informative list of caveats.\r\n\r\nThe good news is that the uncertainty in albedo is typically secondary to uncertainty in other data such as GHI, when considering uncertainty in energy production.\r\n\nWhich is the better course of action?\r\n\r\n1. Leave `albedo` on `PVsystem` or `Array`. Edit the docstrings and add tests to make it explicit that `PVSystem.albedo` or `Array.albedo` can be a Series. Advantages: avoids deprecating and removing `PVSystem.albedo`. Downside: users obtaining albedo from weather data sources have an extra step to perform when using `ModelChain` methods.\r\n2. Add `albedo` as an optional column in `weather`, and have `ModelChain` methods use `weather['albedo']` instead of `PVSystem.albedo` when `weather['albedo']` is present. Advantages: convenient for ModelChain users, and avoids deprecating `PVsystem.albedo`. Disadvatanges: potential for confusion when a user also assigns `PVSystem.albedo`. \r\n3. Move `albedo` from `PVSystem` to `weather`. Same advantages as 2, but requires deprecation, and adds an extra step for users who aren't getting albedo with weather data, and would probably lead to adding code to `ModelChain` similar to the code that infers albedo from `PVSystem.surface_type`.\n@cwhanse I lean toward option 1. However, it seems that for option 1, a user might have to duplicate computations already done in the `ModelChain` in the preliminary step of using the weather to compute the existing `PVSystem.albedo` (as some formulaic combination of ground conditions and weather). Do you know if this is really an issue?\nThanks for the discussion around this feature. I favor Option 2, noting that PVSystem.albedo is already an optional argument. Option 1 is prone to bugs and cases need to be handled checking for mismatches in series/dataframe lengths or perhaps same series lengths but different indices. I would discourage Option 3, as it seems there is both a basis for and utility in retaining albedo as a property of PVSystem.\nFor option 2, I would say raise an exception (or at very least a warning) if two albedos are specified. This could definitely be the source of a subtle computational bug when users don't realize a weather file they pulled is doing something they didn't intend.\n+1 for option 2, and I agree with @campanelli-sunpower that an exception should be raised if two albedos are specified\n+1 for option 2, but I like keeping the old method for the case where you just want to set either a single annual albedo or monthly albedos (tho not sure if this option currently exists). I agree also raise exception if both are specified - we can always change it later.", "created_at": "2022-06-09T01:46:04Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_albedo", "pvlib/tests/test_tracking.py::test_get_irradiance"], "PASS_TO_PASS": ["pvlib/tests/test_clearsky.py::test_ineichen_series", "pvlib/tests/test_clearsky.py::test_ineichen_series_perez_enhancement", "pvlib/tests/test_clearsky.py::test_ineichen_scalar_input", "pvlib/tests/test_clearsky.py::test_ineichen_nans", "pvlib/tests/test_clearsky.py::test_ineichen_arrays", "pvlib/tests/test_clearsky.py::test_ineichen_dni_extra", "pvlib/tests/test_clearsky.py::test_ineichen_altitude", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_leapyear", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_nointerp", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_months", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_months_leapyear", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_nointerp_months", "pvlib/tests/test_clearsky.py::test_haurwitz", "pvlib/tests/test_clearsky.py::test_simplified_solis_scalar_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_scalar_neg_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_series_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_dni_extra", "pvlib/tests/test_clearsky.py::test_simplified_solis_pressure", "pvlib/tests/test_clearsky.py::test_simplified_solis_aod700", "pvlib/tests/test_clearsky.py::test_simplified_solis_precipitable_water", "pvlib/tests/test_clearsky.py::test_simplified_solis_small_scalar_pw", "pvlib/tests/test_clearsky.py::test_simplified_solis_return_arrays", "pvlib/tests/test_clearsky.py::test_simplified_solis_nans_arrays", "pvlib/tests/test_clearsky.py::test_simplified_solis_nans_series", "pvlib/tests/test_clearsky.py::test_linke_turbidity_corners", "pvlib/tests/test_clearsky.py::test_degrees_to_index_1", "pvlib/tests/test_clearsky.py::test_detect_clearsky", "pvlib/tests/test_clearsky.py::test_detect_clearsky_defaults", "pvlib/tests/test_clearsky.py::test_detect_clearsky_components", "pvlib/tests/test_clearsky.py::test_detect_clearsky_iterations", "pvlib/tests/test_clearsky.py::test_detect_clearsky_kwargs", "pvlib/tests/test_clearsky.py::test_detect_clearsky_window", "pvlib/tests/test_clearsky.py::test_detect_clearsky_time_interval", "pvlib/tests/test_clearsky.py::test_detect_clearsky_arrays", "pvlib/tests/test_clearsky.py::test_detect_clearsky_irregular_times", "pvlib/tests/test_clearsky.py::test_detect_clearsky_missing_index", "pvlib/tests/test_clearsky.py::test__line_length_windowed", "pvlib/tests/test_clearsky.py::test__max_diff_windowed", "pvlib/tests/test_clearsky.py::test__calc_stats", "pvlib/tests/test_clearsky.py::test_bird", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_float", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_series", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_reindl", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_negative_horizon", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_model_invalid", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_airmass", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_airmass", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_aoi_projection_precision", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent", "pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_albedo_in_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_albedo_in_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_noct_sam_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_run_model_tracker_list", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_len1_weather_tuple", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params4-noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_dc_model_incomplete", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_ohms_from_percent", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_no_dc_ohmic_loss", "pvlib/tests/test_modelchain.py::test_dc_ohmic_ext_def", "pvlib/tests/test_modelchain.py::test_dc_ohmic_not_a_model", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_type]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[temperature_model_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[albedo]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_tilt]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_azimuth]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[racking_model]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[modules_per_string]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[strings_per_inverter]", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]", "pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_calc_axis_tilt", "pvlib/tests/test_tracking.py::test_slope_aware_backtracking", "pvlib/tests/test_tracking.py::test_singleaxis_aoi_gh1221"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1666", "base_commit": "209376e288fe7c928fa2e0a1178ffa44612112f7", "patch": "diff --git a/pvlib/bifacial/infinite_sheds.py b/pvlib/bifacial/infinite_sheds.py\n--- a/pvlib/bifacial/infinite_sheds.py\n+++ b/pvlib/bifacial/infinite_sheds.py\n@@ -6,66 +6,9 @@\n import pandas as pd\n from pvlib.tools import cosd, sind, tand\n from pvlib.bifacial import utils\n-from pvlib.shading import masking_angle\n from pvlib.irradiance import beam_component, aoi, haydavies\n \n \n-def _vf_ground_sky_integ(surface_tilt, surface_azimuth, gcr, height,\n- pitch, max_rows=10, npoints=100, vectorize=False):\n- \"\"\"\n- Integrated view factor to the sky from the ground underneath\n- interior rows of the array.\n-\n- Parameters\n- ----------\n- surface_tilt : numeric\n- Surface tilt angle in degrees from horizontal, e.g., surface facing up\n- = 0, surface facing horizon = 90. [degree]\n- surface_azimuth : numeric\n- Surface azimuth angles in decimal degrees east of north\n- (e.g. North = 0, South = 180, East = 90, West = 270).\n- ``surface_azimuth`` must be >=0 and <=360.\n- gcr : float\n- Ratio of row slant length to row spacing (pitch). [unitless]\n- height : float\n- Height of the center point of the row above the ground; must be in the\n- same units as ``pitch``.\n- pitch : float\n- Distance between two rows. Must be in the same units as ``height``.\n- max_rows : int, default 10\n- Maximum number of rows to consider in front and behind the current row.\n- npoints : int, default 100\n- Number of points used to discretize distance along the ground.\n- vectorize : bool, default False\n- If True, vectorize the view factor calculation across ``surface_tilt``.\n- This increases speed with the cost of increased memory usage.\n-\n- Returns\n- -------\n- fgnd_sky : numeric\n- Integration of view factor over the length between adjacent, interior\n- rows. Shape matches that of ``surface_tilt``. [unitless]\n- \"\"\"\n- # Abuse utils._vf_ground_sky_2d by supplying surface_tilt in place\n- # of a signed rotation. This is OK because\n- # 1) z span the full distance between 2 rows, and\n- # 2) max_rows is set to be large upstream, and\n- # 3) _vf_ground_sky_2d considers [-max_rows, +max_rows]\n- # The VFs to the sky will thus be symmetric around z=0.5\n- z = np.linspace(0, 1, npoints)\n- rotation = np.atleast_1d(surface_tilt)\n- if vectorize:\n- fz_sky = utils._vf_ground_sky_2d(z, rotation, gcr, pitch, height,\n- max_rows)\n- else:\n- fz_sky = np.zeros((npoints, len(rotation)))\n- for k, r in enumerate(rotation):\n- vf = utils._vf_ground_sky_2d(z, r, gcr, pitch, height, max_rows)\n- fz_sky[:, k] = vf[:, 0] # remove spurious rotation dimension\n- # calculate the integrated view factor for all of the ground between rows\n- return np.trapz(fz_sky, z, axis=0)\n-\n-\n def _poa_ground_shadows(poa_ground, f_gnd_beam, df, vf_gnd_sky):\n \"\"\"\n Reduce ground-reflected irradiance to the tilted plane (poa_ground) to\n@@ -95,8 +38,8 @@ def _poa_ground_shadows(poa_ground, f_gnd_beam, df, vf_gnd_sky):\n return poa_ground * (f_gnd_beam*(1 - df) + df*vf_gnd_sky)\n \n \n-def _vf_row_sky_integ(f_x, surface_tilt, gcr, npoints=100):\n- \"\"\"\n+def _poa_sky_diffuse_pv(dhi, gcr, surface_tilt):\n+ r\"\"\"\n Integrated view factors from the shaded and unshaded parts of\n the row slant height to the sky.\n \n@@ -113,53 +56,18 @@ def _vf_row_sky_integ(f_x, surface_tilt, gcr, npoints=100):\n npoints : int, default 100\n Number of points for integration. [unitless]\n \n- Returns\n- -------\n- vf_shade_sky_integ : numeric\n- Integrated view factor from the shaded part of the row to the sky.\n- [unitless]\n- vf_noshade_sky_integ : numeric\n- Integrated view factor from the unshaded part of the row to the sky.\n- [unitless]\n+ A detailed calculation would be\n \n- Notes\n- -----\n- The view factor to the sky at a point x along the row slant height is\n- given by\n+ dhi * (f_x * vf_shade_sky_integ + (1 - f_x) * vf_noshade_sky_integ)\n \n- .. math ::\n- \\\\large{f_{sky} = \\frac{1}{2} \\\\left(\\\\cos\\\\left(\\\\psi_t\\\\right) +\n- \\\\cos \\\\left(\\\\beta\\\\right) \\\\right)\n+ where vf_shade_sky_integ is the average view factor between 0 and f_x\n+ (the shaded portion). But the average view factor is\n \n- where :math:`\\\\psi_t` is the angle from horizontal of the line from point\n- x to the top of the facing row, and :math:`\\\\beta` is the surface tilt.\n+ 1/(f_x - 0) Integral_0^f_x vf(x) dx\n \n- View factors are integrated separately over shaded and unshaded portions\n- of the row slant height.\n+ so the detailed calculation is equivalent to\n \n- \"\"\"\n- # handle Series inputs\n- surface_tilt = np.array(surface_tilt)\n- cst = cosd(surface_tilt)\n- # shaded portion\n- x = np.linspace(0, f_x, num=npoints)\n- psi_t_shaded = masking_angle(surface_tilt, gcr, x)\n- y = 0.5 * (cosd(psi_t_shaded) + cst)\n- # integrate view factors from each point in the discretization. This is an\n- # improvement over the algorithm described in [2]\n- vf_shade_sky_integ = np.trapz(y, x, axis=0)\n- # unshaded portion\n- x = np.linspace(f_x, 1., num=npoints)\n- psi_t_unshaded = masking_angle(surface_tilt, gcr, x)\n- y = 0.5 * (cosd(psi_t_unshaded) + cst)\n- vf_noshade_sky_integ = np.trapz(y, x, axis=0)\n- return vf_shade_sky_integ, vf_noshade_sky_integ\n-\n-\n-def _poa_sky_diffuse_pv(f_x, dhi, vf_shade_sky_integ, vf_noshade_sky_integ):\n- \"\"\"\n- Sky diffuse POA from integrated view factors combined for both shaded and\n- unshaded parts of the surface.\n+ dhi * 1/(1 - 0) Integral_0^1 vf(x) dx\n \n Parameters\n ----------\n@@ -168,179 +76,47 @@ def _poa_sky_diffuse_pv(f_x, dhi, vf_shade_sky_integ, vf_noshade_sky_integ):\n direct irradiance. [unitless]\n dhi : numeric\n Diffuse horizontal irradiance (DHI). [W/m^2]\n- vf_shade_sky_integ : numeric\n- Integrated view factor from the shaded part of the row to the sky.\n- [unitless]\n- vf_noshade_sky_integ : numeric\n- Integrated view factor from the unshaded part of the row to the sky.\n- [unitless]\n-\n- Returns\n- -------\n- poa_sky_diffuse_pv : numeric\n- Total sky diffuse irradiance incident on the PV surface. [W/m^2]\n- \"\"\"\n- return dhi * (f_x * vf_shade_sky_integ + (1 - f_x) * vf_noshade_sky_integ)\n-\n-\n-def _ground_angle(x, surface_tilt, gcr):\n- \"\"\"\n- Angle from horizontal of the line from a point x on the row slant length\n- to the bottom of the facing row.\n-\n- The angles are clockwise from horizontal, rather than the usual\n- counterclockwise direction.\n-\n- Parameters\n- ----------\n- x : numeric\n- fraction of row slant length from bottom, ``x = 0`` is at the row\n- bottom, ``x = 1`` is at the top of the row.\n- surface_tilt : numeric\n- Surface tilt angle in degrees from horizontal, e.g., surface facing up\n- = 0, surface facing horizon = 90. [degree]\n gcr : float\n ground coverage ratio, ratio of row slant length to row spacing.\n [unitless]\n-\n- Returns\n- -------\n- psi : numeric\n- Angle [degree].\n- \"\"\"\n- # : \\\\ \\\n- # : \\\\ \\\n- # : \\\\ \\\n- # : \\\\ \\ facing row\n- # : \\\\.___________\\\n- # : \\ ^*-. psi \\\n- # : \\ x *-. \\\n- # : \\ v *-.\\\n- # : \\<-----P---->\\\n-\n- x1 = gcr * x * sind(surface_tilt)\n- x2 = gcr * x * cosd(surface_tilt) + 1\n- psi = np.arctan2(x1, x2) # do this first because it handles 0 / 0\n- return np.rad2deg(psi)\n-\n-\n-def _vf_row_ground(x, surface_tilt, gcr):\n- \"\"\"\n- View factor from a point x on the row to the ground.\n-\n- Parameters\n- ----------\n- x : numeric\n- Fraction of row slant height from the bottom. [unitless]\n surface_tilt : numeric\n Surface tilt angle in degrees from horizontal, e.g., surface facing up\n = 0, surface facing horizon = 90. [degree]\n- gcr : float\n- Ground coverage ratio, ratio of row slant length to row spacing.\n- [unitless]\n \n Returns\n -------\n- vf : numeric\n- View factor from the point at x to the ground. [unitless]\n-\n- \"\"\"\n- cst = cosd(surface_tilt)\n- # angle from horizontal at the point x on the row slant height to the\n- # bottom of the facing row\n- psi_t_shaded = _ground_angle(x, surface_tilt, gcr)\n- # view factor from the point on the row to the ground\n- return 0.5 * (cosd(psi_t_shaded) - cst)\n-\n-\n-def _vf_row_ground_integ(f_x, surface_tilt, gcr, npoints=100):\n+ poa_sky_diffuse_pv : numeric\n+ Total sky diffuse irradiance incident on the PV surface. [W/m^2]\n \"\"\"\n- View factors to the ground from shaded and unshaded parts of a row.\n-\n- Parameters\n- ----------\n- f_x : numeric\n- Fraction of row slant height from the bottom that is shaded from\n- direct irradiance. [unitless]\n- surface_tilt : numeric\n- Surface tilt angle in degrees from horizontal, e.g., surface facing up\n- = 0, surface facing horizon = 90. [degree]\n- gcr : float\n- Ground coverage ratio, ratio of row slant length to row spacing.\n- [unitless]\n- npoints : int, default 100\n- Number of points for integration. [unitless]\n-\n- Returns\n- -------\n- vf_shade_ground_integ : numeric\n- View factor from the shaded portion of the row to the ground.\n- [unitless]\n- vf_noshade_ground_integ : numeric\n- View factor from the unshaded portion of the row to the ground.\n- [unitless]\n-\n- Notes\n- -----\n- The view factor to the ground at a point x along the row slant height is\n- given by\n-\n- .. math ::\n- \\\\large{f_{gr} = \\frac{1}{2} \\\\left(\\\\cos\\\\left(\\\\psi_t\\\\right) -\n- \\\\cos \\\\left(\\\\beta\\\\right) \\\\right)\n+ vf_integ = utils.vf_row_sky_2d_integ(surface_tilt, gcr, 0., 1.)\n+ return dhi * vf_integ\n \n- where :math:`\\\\psi_t` is the angle from horizontal of the line from point\n- x to the bottom of the facing row, and :math:`\\\\beta` is the surface tilt.\n \n- Each view factor is integrated over the relevant portion of the row\n- slant height.\n- \"\"\"\n- # handle Series inputs\n- surface_tilt = np.array(surface_tilt)\n- # shaded portion of row slant height\n- x = np.linspace(0, f_x, num=npoints)\n- # view factor from the point on the row to the ground\n- y = _vf_row_ground(x, surface_tilt, gcr)\n- # integrate view factors along the shaded portion of the row slant height.\n- # This is an improvement over the algorithm described in [2]\n- vf_shade_ground_integ = np.trapz(y, x, axis=0)\n-\n- # unshaded portion of row slant height\n- x = np.linspace(f_x, 1., num=npoints)\n- # view factor from the point on the row to the ground\n- y = _vf_row_ground(x, surface_tilt, gcr)\n- # integrate view factors along the unshaded portion.\n- # This is an improvement over the algorithm described in [2]\n- vf_noshade_ground_integ = np.trapz(y, x, axis=0)\n-\n- return vf_shade_ground_integ, vf_noshade_ground_integ\n-\n-\n-def _poa_ground_pv(f_x, poa_ground, f_gnd_pv_shade, f_gnd_pv_noshade):\n+def _poa_ground_pv(poa_ground, gcr, surface_tilt):\n \"\"\"\n Reduce ground-reflected irradiance to account for limited view of the\n ground from the row surface.\n \n Parameters\n ----------\n- f_x : numeric\n- Fraction of row slant height from the bottom that is shaded from\n- direct irradiance. [unitless]\n poa_ground : numeric\n Ground-reflected irradiance that would reach the row surface if the\n full ground was visible. poa_gnd_sky accounts for limited view of the\n sky from the ground. [W/m^2]\n- f_gnd_pv_shade : numeric\n- fraction of ground visible from shaded part of PV surface. [unitless]\n- f_gnd_pv_noshade : numeric\n- fraction of ground visible from unshaded part of PV surface. [unitless]\n+ gcr : float\n+ ground coverage ratio, ratio of row slant length to row spacing.\n+ [unitless]\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n \n Returns\n -------\n numeric\n Ground diffuse irradiance on the row plane. [W/m^2]\n \"\"\"\n- return poa_ground * (f_x * f_gnd_pv_shade + (1 - f_x) * f_gnd_pv_noshade)\n+ vf_integ = utils.vf_row_ground_2d_integ(surface_tilt, gcr, 0., 1.)\n+ return poa_ground * vf_integ\n \n \n def _shaded_fraction(solar_zenith, solar_azimuth, surface_tilt,\n@@ -546,32 +322,15 @@ def get_irradiance_poa(surface_tilt, surface_azimuth, solar_zenith,\n # adjacent rows interior to the array\n # method differs from [1], Eq. 7 and Eq. 8; height is defined at row\n # center rather than at row lower edge as in [1].\n- vf_gnd_sky = _vf_ground_sky_integ(\n- surface_tilt, surface_azimuth, gcr, height, pitch, max_rows, npoints,\n+ vf_gnd_sky = utils.vf_ground_sky_2d_integ(\n+ surface_tilt, gcr, height, pitch, max_rows, npoints,\n vectorize)\n # fraction of row slant height that is shaded from direct irradiance\n f_x = _shaded_fraction(solar_zenith, solar_azimuth, surface_tilt,\n surface_azimuth, gcr)\n \n- # Integrated view factors to the sky from the shaded and unshaded parts of\n- # the row slant height\n- # Differs from [1] Eq. 15 and Eq. 16. Here, we integrate over each\n- # interval (shaded or unshaded) rather than averaging values at each\n- # interval's end points.\n- vf_shade_sky, vf_noshade_sky = _vf_row_sky_integ(\n- f_x, surface_tilt, gcr, npoints)\n-\n- # view factors from the ground to shaded and unshaded portions of the row\n- # slant height\n- # Differs from [1] Eq. 17 and Eq. 18. Here, we integrate over each\n- # interval (shaded or unshaded) rather than averaging values at each\n- # interval's end points.\n- f_gnd_pv_shade, f_gnd_pv_noshade = _vf_row_ground_integ(\n- f_x, surface_tilt, gcr, npoints)\n-\n # Total sky diffuse received by both shaded and unshaded portions\n- poa_sky_pv = _poa_sky_diffuse_pv(\n- f_x, dhi, vf_shade_sky, vf_noshade_sky)\n+ poa_sky_pv = _poa_sky_diffuse_pv(dhi, gcr, surface_tilt)\n \n # irradiance reflected from the ground before accounting for shadows\n # and restricted views\n@@ -596,8 +355,7 @@ def get_irradiance_poa(surface_tilt, surface_azimuth, solar_zenith,\n # the usual ground-reflected irradiance includes the single row to ground\n # view factor (1 - cos(tilt))/2, and Eq. 10, 11 and later multiply\n # this quantity by a ratio of view factors.\n- poa_gnd_pv = _poa_ground_pv(\n- f_x, ground_diffuse, f_gnd_pv_shade, f_gnd_pv_noshade)\n+ poa_gnd_pv = _poa_ground_pv(ground_diffuse, gcr, surface_tilt)\n \n # add sky and ground-reflected irradiance on the row by irradiance\n # component\ndiff --git a/pvlib/bifacial/utils.py b/pvlib/bifacial/utils.py\n--- a/pvlib/bifacial/utils.py\n+++ b/pvlib/bifacial/utils.py\n@@ -5,6 +5,7 @@\n import numpy as np\n from pvlib.tools import sind, cosd, tand\n \n+\n def _solar_projection_tangent(solar_zenith, solar_azimuth, surface_azimuth):\n \"\"\"\n Tangent of the angle between the zenith vector and the sun vector\n@@ -89,7 +90,7 @@ def _unshaded_ground_fraction(surface_tilt, surface_azimuth, solar_zenith,\n return f_gnd_beam # 1 - min(1, abs()) < 1 always\n \n \n-def _vf_ground_sky_2d(x, rotation, gcr, pitch, height, max_rows=10):\n+def vf_ground_sky_2d(rotation, gcr, x, pitch, height, max_rows=10):\n r\"\"\"\n Calculate the fraction of the sky dome visible from point x on the ground.\n \n@@ -99,15 +100,15 @@ def _vf_ground_sky_2d(x, rotation, gcr, pitch, height, max_rows=10):\n \n Parameters\n ----------\n- x : numeric\n- Position on the ground between two rows, as a fraction of the pitch.\n- x = 0 corresponds to the point on the ground directly below the\n- center point of a row. Positive x is towards the right. [unitless]\n rotation : numeric\n Rotation angle of the row's right edge relative to row center.\n [degree]\n gcr : float\n Ratio of the row slant length to the row spacing (pitch). [unitless]\n+ x : numeric\n+ Position on the ground between two rows, as a fraction of the pitch.\n+ x = 0 corresponds to the point on the ground directly below the\n+ center point of a row. Positive x is towards the right. [unitless]\n height : float\n Height of the center point of the row above the ground; must be in the\n same units as ``pitch``.\n@@ -169,3 +170,222 @@ def _vf_ground_sky_2d(x, rotation, gcr, pitch, height, max_rows=10):\n np.clip(next_edge, a_min=0., a_max=None, out=next_edge)\n vf = np.sum(next_edge, axis=-1) / 2\n return vf\n+\n+\n+def vf_ground_sky_2d_integ(surface_tilt, gcr, height, pitch, max_rows=10,\n+ npoints=100, vectorize=False):\n+ \"\"\"\n+ Integrated view factor to the sky from the ground underneath\n+ interior rows of the array.\n+\n+ Parameters\n+ ----------\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n+ gcr : float\n+ Ratio of row slant length to row spacing (pitch). [unitless]\n+ height : float\n+ Height of the center point of the row above the ground; must be in the\n+ same units as ``pitch``.\n+ pitch : float\n+ Distance between two rows. Must be in the same units as ``height``.\n+ max_rows : int, default 10\n+ Maximum number of rows to consider in front and behind the current row.\n+ npoints : int, default 100\n+ Number of points used to discretize distance along the ground.\n+ vectorize : bool, default False\n+ If True, vectorize the view factor calculation across ``surface_tilt``.\n+ This increases speed with the cost of increased memory usage.\n+\n+ Returns\n+ -------\n+ fgnd_sky : numeric\n+ Integration of view factor over the length between adjacent, interior\n+ rows. Shape matches that of ``surface_tilt``. [unitless]\n+ \"\"\"\n+ # Abuse vf_ground_sky_2d by supplying surface_tilt in place\n+ # of a signed rotation. This is OK because\n+ # 1) z span the full distance between 2 rows, and\n+ # 2) max_rows is set to be large upstream, and\n+ # 3) _vf_ground_sky_2d considers [-max_rows, +max_rows]\n+ # The VFs to the sky will thus be symmetric around z=0.5\n+ z = np.linspace(0, 1, npoints)\n+ rotation = np.atleast_1d(surface_tilt)\n+ if vectorize:\n+ fz_sky = vf_ground_sky_2d(rotation, gcr, z, pitch, height, max_rows)\n+ else:\n+ fz_sky = np.zeros((npoints, len(rotation)))\n+ for k, r in enumerate(rotation):\n+ vf = vf_ground_sky_2d(r, gcr, z, pitch, height, max_rows)\n+ fz_sky[:, k] = vf[:, 0] # remove spurious rotation dimension\n+ # calculate the integrated view factor for all of the ground between rows\n+ return np.trapz(fz_sky, z, axis=0)\n+\n+\n+def _vf_poly(surface_tilt, gcr, x, delta):\n+ r'''\n+ A term common to many 2D view factor calculations\n+\n+ Parameters\n+ ----------\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n+ gcr : numeric\n+ Ratio of the row slant length to the row spacing (pitch). [unitless]\n+ x : numeric\n+ Position on the row's slant length, as a fraction of the slant length.\n+ x=0 corresponds to the bottom of the row. [unitless]\n+ delta : -1 or +1\n+ A sign indicator for the linear term of the polynomial\n+\n+ Returns\n+ -------\n+ numeric\n+ '''\n+ a = 1 / gcr\n+ c = cosd(surface_tilt)\n+ return np.sqrt(a*a + 2*delta*a*c*x + x*x)\n+\n+\n+def vf_row_sky_2d(surface_tilt, gcr, x):\n+ r'''\n+ Calculate the view factor to the sky from a point x on a row surface.\n+\n+ Assumes a PV system of infinitely long rows with uniform pitch on\n+ horizontal ground. The view to the sky is restricted by the row's surface\n+ tilt and the top of the adjacent row.\n+\n+ Parameters\n+ ----------\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n+ gcr : numeric\n+ Ratio of the row slant length to the row spacing (pitch). [unitless]\n+ x : numeric\n+ Position on the row's slant length, as a fraction of the slant length.\n+ x=0 corresponds to the bottom of the row. [unitless]\n+\n+ Returns\n+ -------\n+ vf : numeric\n+ Fraction of the sky dome visible from the point x. [unitless]\n+\n+ '''\n+ p = _vf_poly(surface_tilt, gcr, 1 - x, -1)\n+ return 0.5*(1 + (1/gcr * cosd(surface_tilt) - (1 - x)) / p)\n+\n+\n+def vf_row_sky_2d_integ(surface_tilt, gcr, x0=0, x1=1):\n+ r'''\n+ Calculate the average view factor to the sky from a segment of the row\n+ surface between x0 and x1.\n+\n+ Assumes a PV system of infinitely long rows with uniform pitch on\n+ horizontal ground. The view to the sky is restricted by the row's surface\n+ tilt and the top of the adjacent row.\n+\n+ Parameters\n+ ----------\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n+ gcr : numeric\n+ Ratio of the row slant length to the row spacing (pitch). [unitless]\n+ x0 : numeric, default 0\n+ Position on the row's slant length, as a fraction of the slant length.\n+ x0=0 corresponds to the bottom of the row. x0 should be less than x1.\n+ [unitless]\n+ x1 : numeric, default 1\n+ Position on the row's slant length, as a fraction of the slant length.\n+ x1 should be greater than x0. [unitless]\n+\n+ Returns\n+ -------\n+ vf : numeric\n+ Average fraction of the sky dome visible from points in the segment\n+ from x0 to x1. [unitless]\n+\n+ '''\n+ u = np.abs(x1 - x0)\n+ p0 = _vf_poly(surface_tilt, gcr, 1 - x0, -1)\n+ p1 = _vf_poly(surface_tilt, gcr, 1 - x1, -1)\n+ with np.errstate(divide='ignore'):\n+ result = np.where(u < 1e-6,\n+ vf_row_sky_2d(surface_tilt, gcr, x0),\n+ 0.5*(1 + 1/u * (p1 - p0))\n+ )\n+ return result\n+\n+\n+def vf_row_ground_2d(surface_tilt, gcr, x):\n+ r'''\n+ Calculate the view factor to the ground from a point x on a row surface.\n+\n+ Assumes a PV system of infinitely long rows with uniform pitch on\n+ horizontal ground. The view to the ground is restricted by the row's\n+ tilt and the bottom of the facing row.\n+\n+ Parameters\n+ ----------\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n+ gcr : numeric\n+ Ratio of the row slant length to the row spacing (pitch). [unitless]\n+ x : numeric\n+ Position on the row's slant length, as a fraction of the slant length.\n+ x=0 corresponds to the bottom of the row. [unitless]\n+\n+ Returns\n+ -------\n+ vf : numeric\n+ View factor to the visible ground from the point x. [unitless]\n+\n+ '''\n+ p = _vf_poly(surface_tilt, gcr, x, 1)\n+ return 0.5 * (1 - (1/gcr * cosd(surface_tilt) + x)/p)\n+\n+\n+def vf_row_ground_2d_integ(surface_tilt, gcr, x0=0, x1=1):\n+ r'''\n+ Calculate the average view factor to the ground from a segment of the row\n+ surface between x0 and x1.\n+\n+ Assumes a PV system of infinitely long rows with uniform pitch on\n+ horizontal ground. The view to the ground is restricted by the row's\n+ tilt and the bottom of the facing row.\n+\n+ Parameters\n+ ----------\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n+ gcr : numeric\n+ Ratio of the row slant length to the row spacing (pitch). [unitless]\n+ x0 : numeric, default 0.\n+ Position on the row's slant length, as a fraction of the slant length.\n+ x0=0 corresponds to the bottom of the row. x0 should be less than x1.\n+ [unitless]\n+ x1 : numeric, default 1.\n+ Position on the row's slant length, as a fraction of the slant length.\n+ x1 should be greater than x0. [unitless]\n+\n+ Returns\n+ -------\n+ vf : numeric\n+ Integrated view factor to the visible ground on the interval (x0, x1).\n+ [unitless]\n+\n+ '''\n+ u = np.abs(x1 - x0)\n+ p0 = _vf_poly(surface_tilt, gcr, x0, 1)\n+ p1 = _vf_poly(surface_tilt, gcr, x1, 1)\n+ with np.errstate(divide='ignore'):\n+ result = np.where(u < 1e-6,\n+ vf_row_ground_2d(surface_tilt, gcr, x0),\n+ 0.5*(1 - 1/u * (p1 - p0))\n+ )\n+ return result\ndiff --git a/pvlib/shading.py b/pvlib/shading.py\n--- a/pvlib/shading.py\n+++ b/pvlib/shading.py\n@@ -8,6 +8,47 @@\n from pvlib.tools import sind, cosd\n \n \n+def ground_angle(surface_tilt, gcr, slant_height):\n+ \"\"\"\n+ Angle from horizontal of the line from a point on the row slant length\n+ to the bottom of the facing row.\n+\n+ The angles are clockwise from horizontal, rather than the usual\n+ counterclockwise direction.\n+\n+ Parameters\n+ ----------\n+ surface_tilt : numeric\n+ Surface tilt angle in degrees from horizontal, e.g., surface facing up\n+ = 0, surface facing horizon = 90. [degree]\n+ gcr : float\n+ ground coverage ratio, ratio of row slant length to row spacing.\n+ [unitless]\n+ slant_height : numeric\n+ The distance up the module's slant height to evaluate the ground\n+ angle, as a fraction [0-1] of the module slant height [unitless].\n+\n+ Returns\n+ -------\n+ psi : numeric\n+ Angle [degree].\n+ \"\"\"\n+ # : \\\\ \\\n+ # : \\\\ \\\n+ # : \\\\ \\\n+ # : \\\\ \\ facing row\n+ # : \\\\.___________\\\n+ # : \\ ^*-. psi \\\n+ # : \\ x *-. \\\n+ # : \\ v *-.\\\n+ # : \\<-----P---->\\\n+\n+ x1 = gcr * slant_height * sind(surface_tilt)\n+ x2 = gcr * slant_height * cosd(surface_tilt) + 1\n+ psi = np.arctan2(x1, x2) # do this before rad2deg because it handles 0 / 0\n+ return np.rad2deg(psi)\n+\n+\n def masking_angle(surface_tilt, gcr, slant_height):\n \"\"\"\n The elevation angle below which diffuse irradiance is blocked.\n", "test_patch": "diff --git a/pvlib/tests/bifacial/test_infinite_sheds.py b/pvlib/tests/bifacial/test_infinite_sheds.py\n--- a/pvlib/tests/bifacial/test_infinite_sheds.py\n+++ b/pvlib/tests/bifacial/test_infinite_sheds.py\n@@ -5,7 +5,6 @@\n import numpy as np\n import pandas as pd\n from pvlib.bifacial import infinite_sheds\n-from pvlib.tools import cosd\n from ..conftest import assert_series_equal\n \n import pytest\n@@ -42,116 +41,6 @@ def test_system():\n return syst, pts, vfs_ground_sky\n \n \[email protected](\"vectorize\", [True, False])\n-def test__vf_ground_sky_integ(test_system, vectorize):\n- ts, pts, vfs_gnd_sky = test_system\n- # pass rotation here since max_rows=1 for the hand-solved case in\n- # the fixture test_system, which means the ground-to-sky view factor\n- # isn't summed over enough rows for symmetry to hold.\n- vf_integ = infinite_sheds._vf_ground_sky_integ(\n- ts['rotation'], ts['surface_azimuth'],\n- ts['gcr'], ts['height'], ts['pitch'],\n- max_rows=1, npoints=3, vectorize=vectorize)\n- expected_vf_integ = np.trapz(vfs_gnd_sky, pts)\n- assert np.isclose(vf_integ, expected_vf_integ, rtol=0.1)\n-\n-\n-def test__vf_row_sky_integ(test_system):\n- ts, _, _ = test_system\n- gcr = ts['gcr']\n- surface_tilt = ts['surface_tilt']\n- f_x = np.array([0., 0.5, 1.])\n- shaded = []\n- noshade = []\n- for x in f_x:\n- s, ns = infinite_sheds._vf_row_sky_integ(\n- x, surface_tilt, gcr, npoints=100)\n- shaded.append(s)\n- noshade.append(ns)\n-\n- def analytic(gcr, surface_tilt, x):\n- c = cosd(surface_tilt)\n- a = 1. / gcr\n- dx = np.sqrt(a**2 - 2 * a * c * x + x**2)\n- return - a * (c**2 - 1) * np.arctanh((x - a * c) / dx) - c * dx\n-\n- expected_shade = 0.5 * (f_x * cosd(surface_tilt)\n- - analytic(gcr, surface_tilt, 1 - f_x)\n- + analytic(gcr, surface_tilt, 1.))\n- expected_noshade = 0.5 * ((1 - f_x) * cosd(surface_tilt)\n- + analytic(gcr, surface_tilt, 1. - f_x)\n- - analytic(gcr, surface_tilt, 0.))\n- shaded = np.array(shaded)\n- noshade = np.array(noshade)\n- assert np.allclose(shaded, expected_shade)\n- assert np.allclose(noshade, expected_noshade)\n-\n-\n-def test__poa_sky_diffuse_pv():\n- dhi = np.array([np.nan, 0.0, 500.])\n- f_x = np.array([0.2, 0.2, 0.5])\n- vf_shade_sky_integ = np.array([1.0, 0.5, 0.2])\n- vf_noshade_sky_integ = np.array([0.0, 0.5, 0.8])\n- poa = infinite_sheds._poa_sky_diffuse_pv(\n- f_x, dhi, vf_shade_sky_integ, vf_noshade_sky_integ)\n- expected_poa = np.array([np.nan, 0.0, 500 * (0.5 * 0.2 + 0.5 * 0.8)])\n- assert np.allclose(poa, expected_poa, equal_nan=True)\n-\n-\n-def test__ground_angle(test_system):\n- ts, _, _ = test_system\n- x = np.array([0., 0.5, 1.0])\n- angles = infinite_sheds._ground_angle(\n- x, ts['surface_tilt'], ts['gcr'])\n- expected_angles = np.array([0., 5.866738789543952, 9.896090638982903])\n- assert np.allclose(angles, expected_angles)\n-\n-\n-def test__ground_angle_zero_gcr():\n- surface_tilt = 30.0\n- x = np.array([0.0, 0.5, 1.0])\n- angles = infinite_sheds._ground_angle(x, surface_tilt, 0)\n- expected_angles = np.array([0, 0, 0])\n- assert np.allclose(angles, expected_angles)\n-\n-\n-def test__vf_row_ground(test_system):\n- ts, _, _ = test_system\n- x = np.array([0., 0.5, 1.0])\n- sqr3 = np.sqrt(3)\n- vfs = infinite_sheds._vf_row_ground(\n- x, ts['surface_tilt'], ts['gcr'])\n- expected_vfs = np.array([\n- 0.5 * (1. - sqr3 / 2),\n- 0.5 * ((4 + sqr3 / 2) / np.sqrt(17 + 4 * sqr3) - sqr3 / 2),\n- 0.5 * ((4 + sqr3) / np.sqrt(20 + 8 * sqr3) - sqr3 / 2)])\n- assert np.allclose(vfs, expected_vfs)\n-\n-\n-def test__vf_row_ground_integ(test_system):\n- ts, _, _ = test_system\n- gcr = ts['gcr']\n- surface_tilt = ts['surface_tilt']\n- f_x = np.array([0., 0.5, 1.0])\n- shaded, noshade = infinite_sheds._vf_row_ground_integ(\n- f_x, surface_tilt, gcr)\n-\n- def analytic(x, surface_tilt, gcr):\n- c = cosd(surface_tilt)\n- a = 1. / gcr\n- dx = np.sqrt(a**2 + 2 * a * c * x + x**2)\n- return c * dx - a * (c**2 - 1) * np.arctanh((a * c + x) / dx)\n-\n- expected_shade = 0.5 * (analytic(f_x, surface_tilt, gcr)\n- - analytic(0., surface_tilt, gcr)\n- - f_x * cosd(surface_tilt))\n- expected_noshade = 0.5 * (analytic(1., surface_tilt, gcr)\n- - analytic(f_x, surface_tilt, gcr)\n- - (1. - f_x) * cosd(surface_tilt))\n- assert np.allclose(shaded, expected_shade)\n- assert np.allclose(noshade, expected_noshade)\n-\n-\n def test__poa_ground_shadows():\n poa_ground, f_gnd_beam, df, vf_gnd_sky = (300., 0.5, 0.5, 0.2)\n result = infinite_sheds._poa_ground_shadows(\ndiff --git a/pvlib/tests/bifacial/test_utils.py b/pvlib/tests/bifacial/test_utils.py\n--- a/pvlib/tests/bifacial/test_utils.py\n+++ b/pvlib/tests/bifacial/test_utils.py\n@@ -4,6 +4,8 @@\n import numpy as np\n import pytest\n from pvlib.bifacial import utils\n+from pvlib.shading import masking_angle, ground_angle\n+from pvlib.tools import cosd\n \n \n @pytest.fixture\n@@ -79,10 +81,105 @@ def test__unshaded_ground_fraction(\n def test__vf_ground_sky_2d(test_system_fixed_tilt):\n # vector input\n ts, pts, vfs_gnd_sky = test_system_fixed_tilt\n- vfs = utils._vf_ground_sky_2d(pts, ts['rotation'], ts['gcr'],\n- ts['pitch'], ts['height'], max_rows=1)\n+ vfs = utils.vf_ground_sky_2d(ts['rotation'], ts['gcr'], pts,\n+ ts['pitch'], ts['height'], max_rows=1)\n assert np.allclose(vfs, vfs_gnd_sky, rtol=0.1) # middle point vf is off\n # test with singleton x\n- vf = utils._vf_ground_sky_2d(pts[0], ts['rotation'], ts['gcr'],\n- ts['pitch'], ts['height'], max_rows=1)\n+ vf = utils.vf_ground_sky_2d(ts['rotation'], ts['gcr'], pts[0],\n+ ts['pitch'], ts['height'], max_rows=1)\n assert np.isclose(vf, vfs_gnd_sky[0])\n+\n+\[email protected](\"vectorize\", [True, False])\n+def test_vf_ground_sky_2d_integ(test_system_fixed_tilt, vectorize):\n+ ts, pts, vfs_gnd_sky = test_system_fixed_tilt\n+ # pass rotation here since max_rows=1 for the hand-solved case in\n+ # the fixture test_system, which means the ground-to-sky view factor\n+ # isn't summed over enough rows for symmetry to hold.\n+ vf_integ = utils.vf_ground_sky_2d_integ(\n+ ts['rotation'], ts['gcr'], ts['height'], ts['pitch'],\n+ max_rows=1, npoints=3, vectorize=vectorize)\n+ expected_vf_integ = np.trapz(vfs_gnd_sky, pts, axis=0)\n+ assert np.isclose(vf_integ, expected_vf_integ, rtol=0.1)\n+\n+\n+def test_vf_row_sky_2d(test_system_fixed_tilt):\n+ ts, _, _ = test_system_fixed_tilt\n+ # with float input, fx at top of row\n+ vf = utils.vf_row_sky_2d(ts['surface_tilt'], ts['gcr'], 1.)\n+ expected = 0.5 * (1 + cosd(ts['surface_tilt']))\n+ assert np.isclose(vf, expected)\n+ # with array input\n+ fx = np.array([0., 0.5, 1.])\n+ vf = utils.vf_row_sky_2d(ts['surface_tilt'], ts['gcr'], fx)\n+ phi = masking_angle(ts['surface_tilt'], ts['gcr'], fx)\n+ expected = 0.5 * (1 + cosd(ts['surface_tilt'] + phi))\n+ assert np.allclose(vf, expected)\n+\n+\n+def test_vf_row_sky_2d_integ(test_system_fixed_tilt):\n+ ts, _, _ = test_system_fixed_tilt\n+ # with float input, check end position\n+ vf = utils.vf_row_sky_2d_integ(ts['surface_tilt'], ts['gcr'], 1., 1.)\n+ expected = utils.vf_row_sky_2d(ts['surface_tilt'], ts['gcr'], 1.)\n+ assert np.isclose(vf, expected)\n+ # with array input\n+ fx0 = np.array([0., 0.5])\n+ fx1 = np.array([0., 0.8])\n+ vf = utils.vf_row_sky_2d_integ(ts['surface_tilt'], ts['gcr'], fx0, fx1)\n+ phi = masking_angle(ts['surface_tilt'], ts['gcr'], fx0[0])\n+ y0 = 0.5 * (1 + cosd(ts['surface_tilt'] + phi))\n+ x = np.arange(fx0[1], fx1[1], 1e-4)\n+ phi_y = masking_angle(ts['surface_tilt'], ts['gcr'], x)\n+ y = 0.5 * (1 + cosd(ts['surface_tilt'] + phi_y))\n+ y1 = np.trapz(y, x) / (fx1[1] - fx0[1])\n+ expected = np.array([y0, y1])\n+ assert np.allclose(vf, expected, rtol=1e-3)\n+ # with defaults (0, 1)\n+ vf = utils.vf_row_sky_2d_integ(ts['surface_tilt'], ts['gcr'])\n+ x = np.arange(0, 1, 1e-4)\n+ phi_y = masking_angle(ts['surface_tilt'], ts['gcr'], x)\n+ y = 0.5 * (1 + cosd(ts['surface_tilt'] + phi_y))\n+ y1 = np.trapz(y, x) / (1 - 0)\n+ assert np.allclose(vf, y1, rtol=1e-3)\n+\n+\n+def test_vf_row_ground_2d(test_system_fixed_tilt):\n+ ts, _, _ = test_system_fixed_tilt\n+ # with float input, fx at bottom of row\n+ vf = utils.vf_row_ground_2d(ts['surface_tilt'], ts['gcr'], 0.)\n+ expected = 0.5 * (1. - cosd(ts['surface_tilt']))\n+ assert np.isclose(vf, expected)\n+ # with array input\n+ fx = np.array([0., 0.5, 1.0])\n+ vf = utils.vf_row_ground_2d(ts['surface_tilt'], ts['gcr'], fx)\n+ phi = ground_angle(ts['surface_tilt'], ts['gcr'], fx)\n+ expected = 0.5 * (1 - cosd(phi - ts['surface_tilt']))\n+ assert np.allclose(vf, expected)\n+\n+\n+def test_vf_ground_2d_integ(test_system_fixed_tilt):\n+ ts, _, _ = test_system_fixed_tilt\n+ # with float input, check end position\n+ vf = utils.vf_row_ground_2d_integ(ts['surface_tilt'], ts['gcr'], 0., 0.)\n+ expected = utils.vf_row_ground_2d(ts['surface_tilt'], ts['gcr'], 0.)\n+ assert np.isclose(vf, expected)\n+ # with array input\n+ fx0 = np.array([0., 0.5])\n+ fx1 = np.array([0., 0.8])\n+ vf = utils.vf_row_ground_2d_integ(ts['surface_tilt'], ts['gcr'], fx0, fx1)\n+ phi = ground_angle(ts['surface_tilt'], ts['gcr'], fx0[0])\n+ y0 = 0.5 * (1 - cosd(phi - ts['surface_tilt']))\n+ x = np.arange(fx0[1], fx1[1], 1e-4)\n+ phi_y = ground_angle(ts['surface_tilt'], ts['gcr'], x)\n+ y = 0.5 * (1 - cosd(phi_y - ts['surface_tilt']))\n+ y1 = np.trapz(y, x) / (fx1[1] - fx0[1])\n+ expected = np.array([y0, y1])\n+ assert np.allclose(vf, expected, rtol=1e-2)\n+ # with defaults (0, 1)\n+ vf = utils.vf_row_ground_2d_integ(ts['surface_tilt'], ts['gcr'], 0, 1)\n+ x = np.arange(0, 1, 1e-4)\n+ phi_y = ground_angle(ts['surface_tilt'], ts['gcr'], x)\n+ y = 0.5 * (1 - cosd(phi_y - ts['surface_tilt']))\n+ y1 = np.trapz(y, x) / (1 - 0)\n+ assert np.allclose(vf, y1, rtol=1e-2)\ndiff --git a/pvlib/tests/test_shading.py b/pvlib/tests/test_shading.py\n--- a/pvlib/tests/test_shading.py\n+++ b/pvlib/tests/test_shading.py\n@@ -7,6 +7,34 @@\n from pvlib import shading\n \n \[email protected]\n+def test_system():\n+ syst = {'height': 1.0,\n+ 'pitch': 2.,\n+ 'surface_tilt': 30.,\n+ 'surface_azimuth': 180.,\n+ 'rotation': -30.} # rotation of right edge relative to horizontal\n+ syst['gcr'] = 1.0 / syst['pitch']\n+ return syst\n+\n+\n+def test__ground_angle(test_system):\n+ ts = test_system\n+ x = np.array([0., 0.5, 1.0])\n+ angles = shading.ground_angle(\n+ ts['surface_tilt'], ts['gcr'], x)\n+ expected_angles = np.array([0., 5.866738789543952, 9.896090638982903])\n+ assert np.allclose(angles, expected_angles)\n+\n+\n+def test__ground_angle_zero_gcr():\n+ surface_tilt = 30.0\n+ x = np.array([0.0, 0.5, 1.0])\n+ angles = shading.ground_angle(surface_tilt, 0, x)\n+ expected_angles = np.array([0, 0, 0])\n+ assert np.allclose(angles, expected_angles)\n+\n+\n @pytest.fixture\n def surface_tilt():\n idx = pd.date_range('2019-01-01', freq='h', periods=3)\n", "problem_statement": "is vf_row_sky correct?\nhttps://github.com/pvlib/pvlib-python/blob/7e88d212c786d0ad334dce6fcafaf29339ff60ab/pvlib/bifacial/infinite_sheds.py#L146\r\n\r\nI think this should be:\r\n\r\n$$\\frac{1 + \\cos \\left( \\text{surface tilt} + \\psi_{t}\\ \\text{shaded} \\right)}{2}$$\r\n\r\nbecause in the reference frame of the module surface the angle pointing along the slant height to the sky is actually zero, $cos(0) = 1$, and the angle above the slant height to a horizontal line would be the `surface_tilt` itself, then the angle from the horizontal to the top of the next row is `psi_t_shaded` so finally this angle from the slant height all the way up to the top of the next row is `surface_tilt + psi_t_shaded`:\r\n\r\n\r\n\r\nFor example, this is why if `psi_t_shaded` is zero, then the view factor should collapse to the isotropic view factor $(1+\\cos(\\beta))/2$ as given on the [PVPMC website modeling reference for POA sky diffuse](https://pvpmc.sandia.gov/modeling-steps/1-weather-design-inputs/plane-of-array-poa-irradiance/calculating-poa-irradiance/poa-sky-diffuse/isotropic-sky-diffuse-model/).\r\n\r\nThe actual value difference between the two formulas can be quite small when `psi_t_shaded` is close to zero (_eg_ less than 5°), but it's significant when as the masking angle is larger (_eg_ greater than 5°).\n", "hints_text": "", "created_at": "2023-02-15T09:43:10Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/bifacial/test_infinite_sheds.py::test__poa_ground_shadows", "pvlib/tests/bifacial/test_infinite_sheds.py::test__shaded_fraction_floats", "pvlib/tests/bifacial/test_infinite_sheds.py::test__shaded_fraction_array", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_poa", "pvlib/tests/bifacial/test_infinite_sheds.py::test__backside_tilt", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance[True]", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance[False]", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_limiting_gcr", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_with_haydavies", "pvlib/tests/bifacial/test_utils.py::test__solar_projection_tangent", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.5-0.0-180.0-0.0-180.0-0.5]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[1.0-0.0-180.0-0.0-180.0-0.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[1.0-90.0-180.0-0.0-180.0-1.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.5-45.0-180.0-45.0-270.0-0.6464466094067263]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.5-45.0-180.0-90.0-180.0-0.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-0-180-0.5]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-180-0.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-90-0.5]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-0-1.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-135-0.1464466094067262]", "pvlib/tests/bifacial/test_utils.py::test__vf_ground_sky_2d", "pvlib/tests/bifacial/test_utils.py::test_vf_ground_sky_2d_integ[True]", "pvlib/tests/bifacial/test_utils.py::test_vf_ground_sky_2d_integ[False]", "pvlib/tests/bifacial/test_utils.py::test_vf_row_sky_2d", "pvlib/tests/bifacial/test_utils.py::test_vf_row_sky_2d_integ", "pvlib/tests/bifacial/test_utils.py::test_vf_row_ground_2d", "pvlib/tests/bifacial/test_utils.py::test_vf_ground_2d_integ", "pvlib/tests/test_shading.py::test__ground_angle", "pvlib/tests/test_shading.py::test__ground_angle_zero_gcr", "pvlib/tests/test_shading.py::test_masking_angle_series", "pvlib/tests/test_shading.py::test_masking_angle_scalar", "pvlib/tests/test_shading.py::test_masking_angle_zero_gcr", "pvlib/tests/test_shading.py::test_masking_angle_passias_series", "pvlib/tests/test_shading.py::test_masking_angle_passias_scalar", "pvlib/tests/test_shading.py::test_sky_diffuse_passias_series", "pvlib/tests/test_shading.py::test_sky_diffuse_passias_scalar"], "PASS_TO_PASS": [], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1764", "base_commit": "964dc435ca117d47c74da47345ace976b70a471f", "patch": "diff --git a/pvlib/singlediode.py b/pvlib/singlediode.py\n--- a/pvlib/singlediode.py\n+++ b/pvlib/singlediode.py\n@@ -2,15 +2,17 @@\n Low-level functions for solving the single diode equation.\n \"\"\"\n \n-from functools import partial\n import numpy as np\n from pvlib.tools import _golden_sect_DataFrame\n \n from scipy.optimize import brentq, newton\n from scipy.special import lambertw\n \n-# set keyword arguments for all uses of newton in this module\n-newton = partial(newton, tol=1e-6, maxiter=100, fprime2=None)\n+# newton method default parameters for this module\n+NEWTON_DEFAULT_PARAMS = {\n+ 'tol': 1e-6,\n+ 'maxiter': 100\n+}\n \n # intrinsic voltage per cell junction for a:Si, CdTe, Mertens et al.\n VOLTAGE_BUILTIN = 0.9 # [V]\n@@ -206,7 +208,7 @@ def bishop88_i_from_v(voltage, photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth,\n d2mutau=0, NsVbi=np.Inf, breakdown_factor=0.,\n breakdown_voltage=-5.5, breakdown_exp=3.28,\n- method='newton'):\n+ method='newton', method_kwargs=None):\n \"\"\"\n Find current given any voltage.\n \n@@ -247,22 +249,59 @@ def bishop88_i_from_v(voltage, photocurrent, saturation_current,\n method : str, default 'newton'\n Either ``'newton'`` or ``'brentq'``. ''method'' must be ``'newton'``\n if ``breakdown_factor`` is not 0.\n+ method_kwargs : dict, optional\n+ Keyword arguments passed to root finder method. See\n+ :py:func:`scipy:scipy.optimize.brentq` and\n+ :py:func:`scipy:scipy.optimize.newton` parameters.\n+ ``'full_output': True`` is allowed, and ``optimizer_output`` would be\n+ returned. See examples section.\n \n Returns\n -------\n current : numeric\n current (I) at the specified voltage (V). [A]\n+ optimizer_output : tuple, optional, if specified in ``method_kwargs``\n+ see root finder documentation for selected method.\n+ Found root is diode voltage in [1]_.\n+\n+ Examples\n+ --------\n+ Using the following arguments that may come from any\n+ `calcparams_.*` function in :py:mod:`pvlib.pvsystem`:\n+\n+ >>> args = {'photocurrent': 1., 'saturation_current': 9e-10, 'nNsVth': 4.,\n+ ... 'resistance_series': 4., 'resistance_shunt': 5000.0}\n+\n+ Use default values:\n+\n+ >>> i = bishop88_i_from_v(0.0, **args)\n+\n+ Specify tolerances and maximum number of iterations:\n+\n+ >>> i = bishop88_i_from_v(0.0, **args, method='newton',\n+ ... method_kwargs={'tol': 1e-3, 'rtol': 1e-3, 'maxiter': 20})\n+\n+ Retrieve full output from the root finder:\n+\n+ >>> i, method_output = bishop88_i_from_v(0.0, **args, method='newton',\n+ ... method_kwargs={'full_output': True})\n \"\"\"\n # collect args\n args = (photocurrent, saturation_current, resistance_series,\n resistance_shunt, nNsVth, d2mutau, NsVbi,\n breakdown_factor, breakdown_voltage, breakdown_exp)\n+ method = method.lower()\n+\n+ # method_kwargs create dict if not provided\n+ # this pattern avoids bugs with Mutable Default Parameters\n+ if not method_kwargs:\n+ method_kwargs = {}\n \n def fv(x, v, *a):\n # calculate voltage residual given diode voltage \"x\"\n return bishop88(x, *a)[1] - v\n \n- if method.lower() == 'brentq':\n+ if method == 'brentq':\n # first bound the search using voc\n voc_est = estimate_voc(photocurrent, saturation_current, nNsVth)\n \n@@ -274,27 +313,37 @@ def vd_from_brent(voc, v, iph, isat, rs, rsh, gamma, d2mutau, NsVbi,\n return brentq(fv, 0.0, voc,\n args=(v, iph, isat, rs, rsh, gamma, d2mutau, NsVbi,\n breakdown_factor, breakdown_voltage,\n- breakdown_exp))\n+ breakdown_exp),\n+ **method_kwargs)\n \n vd_from_brent_vectorized = np.vectorize(vd_from_brent)\n vd = vd_from_brent_vectorized(voc_est, voltage, *args)\n- elif method.lower() == 'newton':\n+ elif method == 'newton':\n # make sure all args are numpy arrays if max size > 1\n # if voltage is an array, then make a copy to use for initial guess, v0\n- args, v0 = _prepare_newton_inputs((voltage,), args, voltage)\n+ args, v0, method_kwargs = \\\n+ _prepare_newton_inputs((voltage,), args, voltage, method_kwargs)\n vd = newton(func=lambda x, *a: fv(x, voltage, *a), x0=v0,\n fprime=lambda x, *a: bishop88(x, *a, gradients=True)[4],\n- args=args)\n+ args=args,\n+ **method_kwargs)\n else:\n raise NotImplementedError(\"Method '%s' isn't implemented\" % method)\n- return bishop88(vd, *args)[0]\n+\n+ # When 'full_output' parameter is specified, returned 'vd' is a tuple with\n+ # many elements, where the root is the first one. So we use it to output\n+ # the bishop88 result and return tuple(scalar, tuple with method results)\n+ if method_kwargs.get('full_output') is True:\n+ return (bishop88(vd[0], *args)[0], vd)\n+ else:\n+ return bishop88(vd, *args)[0]\n \n \n def bishop88_v_from_i(current, photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth,\n d2mutau=0, NsVbi=np.Inf, breakdown_factor=0.,\n breakdown_voltage=-5.5, breakdown_exp=3.28,\n- method='newton'):\n+ method='newton', method_kwargs=None):\n \"\"\"\n Find voltage given any current.\n \n@@ -335,16 +384,54 @@ def bishop88_v_from_i(current, photocurrent, saturation_current,\n method : str, default 'newton'\n Either ``'newton'`` or ``'brentq'``. ''method'' must be ``'newton'``\n if ``breakdown_factor`` is not 0.\n+ method_kwargs : dict, optional\n+ Keyword arguments passed to root finder method. See\n+ :py:func:`scipy:scipy.optimize.brentq` and\n+ :py:func:`scipy:scipy.optimize.newton` parameters.\n+ ``'full_output': True`` is allowed, and ``optimizer_output`` would be\n+ returned. See examples section.\n \n Returns\n -------\n voltage : numeric\n voltage (V) at the specified current (I) in volts [V]\n+ optimizer_output : tuple, optional, if specified in ``method_kwargs``\n+ see root finder documentation for selected method.\n+ Found root is diode voltage in [1]_.\n+\n+ Examples\n+ --------\n+ Using the following arguments that may come from any\n+ `calcparams_.*` function in :py:mod:`pvlib.pvsystem`:\n+\n+ >>> args = {'photocurrent': 1., 'saturation_current': 9e-10, 'nNsVth': 4.,\n+ ... 'resistance_series': 4., 'resistance_shunt': 5000.0}\n+\n+ Use default values:\n+\n+ >>> v = bishop88_v_from_i(0.0, **args)\n+\n+ Specify tolerances and maximum number of iterations:\n+\n+ >>> v = bishop88_v_from_i(0.0, **args, method='newton',\n+ ... method_kwargs={'tol': 1e-3, 'rtol': 1e-3, 'maxiter': 20})\n+\n+ Retrieve full output from the root finder:\n+\n+ >>> v, method_output = bishop88_v_from_i(0.0, **args, method='newton',\n+ ... method_kwargs={'full_output': True})\n \"\"\"\n # collect args\n args = (photocurrent, saturation_current, resistance_series,\n resistance_shunt, nNsVth, d2mutau, NsVbi, breakdown_factor,\n breakdown_voltage, breakdown_exp)\n+ method = method.lower()\n+\n+ # method_kwargs create dict if not provided\n+ # this pattern avoids bugs with Mutable Default Parameters\n+ if not method_kwargs:\n+ method_kwargs = {}\n+\n # first bound the search using voc\n voc_est = estimate_voc(photocurrent, saturation_current, nNsVth)\n \n@@ -352,7 +439,7 @@ def fi(x, i, *a):\n # calculate current residual given diode voltage \"x\"\n return bishop88(x, *a)[0] - i\n \n- if method.lower() == 'brentq':\n+ if method == 'brentq':\n # brentq only works with scalar inputs, so we need a set up function\n # and np.vectorize to repeatedly call the optimizer with the right\n # arguments for possible array input\n@@ -361,26 +448,36 @@ def vd_from_brent(voc, i, iph, isat, rs, rsh, gamma, d2mutau, NsVbi,\n return brentq(fi, 0.0, voc,\n args=(i, iph, isat, rs, rsh, gamma, d2mutau, NsVbi,\n breakdown_factor, breakdown_voltage,\n- breakdown_exp))\n+ breakdown_exp),\n+ **method_kwargs)\n \n vd_from_brent_vectorized = np.vectorize(vd_from_brent)\n vd = vd_from_brent_vectorized(voc_est, current, *args)\n- elif method.lower() == 'newton':\n+ elif method == 'newton':\n # make sure all args are numpy arrays if max size > 1\n # if voc_est is an array, then make a copy to use for initial guess, v0\n- args, v0 = _prepare_newton_inputs((current,), args, voc_est)\n+ args, v0, method_kwargs = \\\n+ _prepare_newton_inputs((current,), args, voc_est, method_kwargs)\n vd = newton(func=lambda x, *a: fi(x, current, *a), x0=v0,\n fprime=lambda x, *a: bishop88(x, *a, gradients=True)[3],\n- args=args)\n+ args=args,\n+ **method_kwargs)\n else:\n raise NotImplementedError(\"Method '%s' isn't implemented\" % method)\n- return bishop88(vd, *args)[1]\n+\n+ # When 'full_output' parameter is specified, returned 'vd' is a tuple with\n+ # many elements, where the root is the first one. So we use it to output\n+ # the bishop88 result and return tuple(scalar, tuple with method results)\n+ if method_kwargs.get('full_output') is True:\n+ return (bishop88(vd[0], *args)[1], vd)\n+ else:\n+ return bishop88(vd, *args)[1]\n \n \n def bishop88_mpp(photocurrent, saturation_current, resistance_series,\n resistance_shunt, nNsVth, d2mutau=0, NsVbi=np.Inf,\n breakdown_factor=0., breakdown_voltage=-5.5,\n- breakdown_exp=3.28, method='newton'):\n+ breakdown_exp=3.28, method='newton', method_kwargs=None):\n \"\"\"\n Find max power point.\n \n@@ -419,43 +516,91 @@ def bishop88_mpp(photocurrent, saturation_current, resistance_series,\n method : str, default 'newton'\n Either ``'newton'`` or ``'brentq'``. ''method'' must be ``'newton'``\n if ``breakdown_factor`` is not 0.\n+ method_kwargs : dict, optional\n+ Keyword arguments passed to root finder method. See\n+ :py:func:`scipy:scipy.optimize.brentq` and\n+ :py:func:`scipy:scipy.optimize.newton` parameters.\n+ ``'full_output': True`` is allowed, and ``optimizer_output`` would be\n+ returned. See examples section.\n \n Returns\n -------\n tuple\n max power current ``i_mp`` [A], max power voltage ``v_mp`` [V], and\n max power ``p_mp`` [W]\n+ optimizer_output : tuple, optional, if specified in ``method_kwargs``\n+ see root finder documentation for selected method.\n+ Found root is diode voltage in [1]_.\n+\n+ Examples\n+ --------\n+ Using the following arguments that may come from any\n+ `calcparams_.*` function in :py:mod:`pvlib.pvsystem`:\n+\n+ >>> args = {'photocurrent': 1., 'saturation_current': 9e-10, 'nNsVth': 4.,\n+ ... 'resistance_series': 4., 'resistance_shunt': 5000.0}\n+\n+ Use default values:\n+\n+ >>> i_mp, v_mp, p_mp = bishop88_mpp(**args)\n+\n+ Specify tolerances and maximum number of iterations:\n+\n+ >>> i_mp, v_mp, p_mp = bishop88_mpp(**args, method='newton',\n+ ... method_kwargs={'tol': 1e-3, 'rtol': 1e-3, 'maxiter': 20})\n+\n+ Retrieve full output from the root finder:\n+\n+ >>> (i_mp, v_mp, p_mp), method_output = bishop88_mpp(**args,\n+ ... method='newton', method_kwargs={'full_output': True})\n \"\"\"\n # collect args\n args = (photocurrent, saturation_current, resistance_series,\n resistance_shunt, nNsVth, d2mutau, NsVbi, breakdown_factor,\n breakdown_voltage, breakdown_exp)\n+ method = method.lower()\n+\n+ # method_kwargs create dict if not provided\n+ # this pattern avoids bugs with Mutable Default Parameters\n+ if not method_kwargs:\n+ method_kwargs = {}\n+\n # first bound the search using voc\n voc_est = estimate_voc(photocurrent, saturation_current, nNsVth)\n \n def fmpp(x, *a):\n return bishop88(x, *a, gradients=True)[6]\n \n- if method.lower() == 'brentq':\n+ if method == 'brentq':\n # break out arguments for numpy.vectorize to handle broadcasting\n vec_fun = np.vectorize(\n lambda voc, iph, isat, rs, rsh, gamma, d2mutau, NsVbi, vbr_a, vbr,\n vbr_exp: brentq(fmpp, 0.0, voc,\n args=(iph, isat, rs, rsh, gamma, d2mutau, NsVbi,\n- vbr_a, vbr, vbr_exp))\n+ vbr_a, vbr, vbr_exp),\n+ **method_kwargs)\n )\n vd = vec_fun(voc_est, *args)\n- elif method.lower() == 'newton':\n+ elif method == 'newton':\n # make sure all args are numpy arrays if max size > 1\n # if voc_est is an array, then make a copy to use for initial guess, v0\n- args, v0 = _prepare_newton_inputs((), args, voc_est)\n+ args, v0, method_kwargs = \\\n+ _prepare_newton_inputs((), args, voc_est, method_kwargs)\n vd = newton(\n func=fmpp, x0=v0,\n- fprime=lambda x, *a: bishop88(x, *a, gradients=True)[7], args=args\n- )\n+ fprime=lambda x, *a: bishop88(x, *a, gradients=True)[7], args=args,\n+ **method_kwargs)\n else:\n raise NotImplementedError(\"Method '%s' isn't implemented\" % method)\n- return bishop88(vd, *args)\n+\n+ # When 'full_output' parameter is specified, returned 'vd' is a tuple with\n+ # many elements, where the root is the first one. So we use it to output\n+ # the bishop88 result and return\n+ # tuple(tuple with bishop88 solution, tuple with method results)\n+ if method_kwargs.get('full_output') is True:\n+ return (bishop88(vd[0], *args), vd)\n+ else:\n+ return bishop88(vd, *args)\n \n \n def _get_size_and_shape(args):\n@@ -482,7 +627,7 @@ def _get_size_and_shape(args):\n return size, shape\n \n \n-def _prepare_newton_inputs(i_or_v_tup, args, v0):\n+def _prepare_newton_inputs(i_or_v_tup, args, v0, method_kwargs):\n # broadcast arguments for newton method\n # the first argument should be a tuple, eg: (i,), (v,) or ()\n size, shape = _get_size_and_shape(i_or_v_tup + args)\n@@ -492,7 +637,12 @@ def _prepare_newton_inputs(i_or_v_tup, args, v0):\n # copy v0 to a new array and broadcast it to the shape of max size\n if shape is not None:\n v0 = np.broadcast_to(v0, shape).copy()\n- return args, v0\n+\n+ # set abs tolerance and maxiter from method_kwargs if not provided\n+ # apply defaults, but giving priority to user-specified values\n+ method_kwargs = {**NEWTON_DEFAULT_PARAMS, **method_kwargs}\n+\n+ return args, v0, method_kwargs\n \n \n def _lambertw_v_from_i(current, photocurrent, saturation_current,\n", "test_patch": "diff --git a/pvlib/tests/test_singlediode.py b/pvlib/tests/test_singlediode.py\n--- a/pvlib/tests/test_singlediode.py\n+++ b/pvlib/tests/test_singlediode.py\n@@ -412,3 +412,135 @@ def test_pvsyst_breakdown(method, brk_params, recomb_params, poa, temp_cell,\n \n vsc_88 = bishop88_v_from_i(isc_88, *x, **y, method=method)\n assert np.isclose(vsc_88, 0.0, *tol)\n+\n+\[email protected]\n+def bishop88_arguments():\n+ pvsyst_fs_495 = get_pvsyst_fs_495()\n+ # evaluate PVSyst model with thin-film recombination loss current\n+ # at reference conditions\n+ x = pvsystem.calcparams_pvsyst(\n+ effective_irradiance=pvsyst_fs_495['irrad_ref'],\n+ temp_cell=pvsyst_fs_495['temp_ref'],\n+ alpha_sc=pvsyst_fs_495['alpha_sc'],\n+ gamma_ref=pvsyst_fs_495['gamma_ref'],\n+ mu_gamma=pvsyst_fs_495['mu_gamma'], I_L_ref=pvsyst_fs_495['I_L_ref'],\n+ I_o_ref=pvsyst_fs_495['I_o_ref'], R_sh_ref=pvsyst_fs_495['R_sh_ref'],\n+ R_sh_0=pvsyst_fs_495['R_sh_0'], R_sh_exp=pvsyst_fs_495['R_sh_exp'],\n+ R_s=pvsyst_fs_495['R_s'],\n+ cells_in_series=pvsyst_fs_495['cells_in_series'],\n+ EgRef=pvsyst_fs_495['EgRef']\n+ )\n+ y = dict(d2mutau=pvsyst_fs_495['d2mutau'],\n+ NsVbi=VOLTAGE_BUILTIN*pvsyst_fs_495['cells_in_series'])\n+ # Convert (*x, **y) in a bishop88_.* call to dict of arguments\n+ args_dict = {\n+ 'photocurrent': x[0],\n+ 'saturation_current': x[1],\n+ 'resistance_series': x[2],\n+ 'resistance_shunt': x[3],\n+ 'nNsVth': x[4],\n+ }\n+ args_dict.update(y)\n+ return args_dict\n+\n+\[email protected]('method, method_kwargs', [\n+ ('newton', {\n+ 'tol': 1e-8,\n+ 'rtol': 1e-8,\n+ 'maxiter': 30,\n+ }),\n+ ('brentq', {\n+ 'xtol': 1e-8,\n+ 'rtol': 1e-8,\n+ 'maxiter': 30,\n+ })\n+])\n+def test_bishop88_kwargs_transfer(method, method_kwargs, mocker,\n+ bishop88_arguments):\n+ \"\"\"test method_kwargs modifying optimizer does not break anything\"\"\"\n+ # patch method namespace at singlediode module namespace\n+ optimizer_mock = mocker.patch('pvlib.singlediode.' + method)\n+\n+ # check kwargs passed to bishop_.* are a subset of the call args\n+ # since they are called with more keyword arguments\n+\n+ bishop88_i_from_v(0, **bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+ _, kwargs = optimizer_mock.call_args\n+ assert method_kwargs.items() <= kwargs.items()\n+\n+ bishop88_v_from_i(0, **bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+ _, kwargs = optimizer_mock.call_args\n+ assert method_kwargs.items() <= kwargs.items()\n+\n+ bishop88_mpp(**bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+ _, kwargs = optimizer_mock.call_args\n+ assert method_kwargs.items() <= kwargs.items()\n+\n+\[email protected]('method, method_kwargs', [\n+ ('newton', {\n+ 'tol': 1e-4,\n+ 'rtol': 1e-4,\n+ 'maxiter': 20,\n+ '_inexistent_param': \"0.01\"\n+ }),\n+ ('brentq', {\n+ 'xtol': 1e-4,\n+ 'rtol': 1e-4,\n+ 'maxiter': 20,\n+ '_inexistent_param': \"0.01\"\n+ })\n+])\n+def test_bishop88_kwargs_fails(method, method_kwargs, bishop88_arguments):\n+ \"\"\"test invalid method_kwargs passed onto the optimizer fail\"\"\"\n+\n+ pytest.raises(TypeError, bishop88_i_from_v,\n+ 0, **bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+\n+ pytest.raises(TypeError, bishop88_v_from_i,\n+ 0, **bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+\n+ pytest.raises(TypeError, bishop88_mpp,\n+ **bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+\n+\[email protected]('method', ['newton', 'brentq'])\n+def test_bishop88_full_output_kwarg(method, bishop88_arguments):\n+ \"\"\"test call to bishop88_.* with full_output=True return values are ok\"\"\"\n+ method_kwargs = {'full_output': True}\n+\n+ ret_val = bishop88_i_from_v(0, **bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+ assert isinstance(ret_val, tuple) # ret_val must be a tuple\n+ assert len(ret_val) == 2 # of two elements\n+ assert isinstance(ret_val[0], float) # first one has bishop88 result\n+ assert isinstance(ret_val[1], tuple) # second is output from optimizer\n+ # any root finder returns at least 2 elements with full_output=True\n+ assert len(ret_val[1]) >= 2\n+\n+ ret_val = bishop88_v_from_i(0, **bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+ assert isinstance(ret_val, tuple) # ret_val must be a tuple\n+ assert len(ret_val) == 2 # of two elements\n+ assert isinstance(ret_val[0], float) # first one has bishop88 result\n+ assert isinstance(ret_val[1], tuple) # second is output from optimizer\n+ # any root finder returns at least 2 elements with full_output=True\n+ assert len(ret_val[1]) >= 2\n+\n+ ret_val = bishop88_mpp(**bishop88_arguments, method=method,\n+ method_kwargs=method_kwargs)\n+ assert isinstance(ret_val, tuple) # ret_val must be a tuple\n+ assert len(ret_val) == 2 # of two elements\n+ assert isinstance(ret_val[0], tuple) # first one has bishop88 result\n+ assert len(ret_val[0]) == 3 # of three elements (I,V,P)\n+ assert isinstance(ret_val[1], tuple) # second is output from optimizer\n+ # any root finder returns at least 2 elements with full_output=True\n+ assert len(ret_val[1]) >= 2\n", "problem_statement": "Allow user to set tol and maxiter for singlediode newton method\nThe first few lines of `pvlib.singlediode` set `tol` and `maxiter` for all the solvers using the newton method:\r\n\r\n```\r\nfrom scipy.optimize import brentq, newton\r\nfrom scipy.special import lambertw\r\n\r\n# set keyword arguments for all uses of newton in this module\r\nnewton = partial(newton, tol=1e-6, maxiter=100, fprime2=None)\r\n```\r\n\r\nHowever, I would like to change `tol` and `maxiter` for my application. It would be great if these could be added instead as keyword arguments to the various functions so they can be adjusted by the user. Using a variety of singlediode model params, I have found that by setting tol=0.1 and maxiter=10, I can realize a 1.4x speedup in the `singeldiode.bishop88_mpp` algorithm while incurring a maximum error of 0.007038% and a mean absolute error of 0.000042% in calculated V_mp.\r\n\r\n\n", "hints_text": "At what level would they be exposed? At the `pvlib.singlediode.bishop88_xxx` functions or at a higher level, e.g., `pvlib.pvsystem.singlediode`?\nAt the level of bishop88_xxx would be good enough for my purposes. \nI support this as long as the interface is common for both the `newton` and `brentq` options.", "created_at": "2023-06-07T22:18:17Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_singlediode.py::test_bishop88_kwargs_transfer[newton-method_kwargs0]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_transfer[brentq-method_kwargs1]", "pvlib/tests/test_singlediode.py::test_bishop88_full_output_kwarg[newton]", "pvlib/tests/test_singlediode.py::test_bishop88_full_output_kwarg[brentq]"], "PASS_TO_PASS": ["pvlib/tests/test_singlediode.py::test_method_spr_e20_327[brentq]", "pvlib/tests/test_singlediode.py::test_method_spr_e20_327[newton]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[brentq]", "pvlib/tests/test_singlediode.py::test_newton_fs_495[newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_singlediode_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_ivcurve_pnts_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[1-newton]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-lambertw]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-brentq]", "pvlib/tests/test_singlediode.py::test_v_from_i_i_from_v_precision[2-newton]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[newton-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_recombination_loss[brentq-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[newton-brk_params1-recomb_params1-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params0-recomb_params0-1000-25-expected0-tol0]", "pvlib/tests/test_singlediode.py::test_pvsyst_breakdown[brentq-brk_params1-recomb_params1-888-55-expected1-tol1]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_fails[newton-method_kwargs0]", "pvlib/tests/test_singlediode.py::test_bishop88_kwargs_fails[brentq-method_kwargs1]"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1478", "base_commit": "3f397ed44075b01f4ba535750356859195a51b2d", "patch": "diff --git a/pvlib/clearsky.py b/pvlib/clearsky.py\n--- a/pvlib/clearsky.py\n+++ b/pvlib/clearsky.py\n@@ -960,8 +960,8 @@ def bird(zenith, airmass_relative, aod380, aod500, precipitable_water,\n Extraterrestrial radiation [W/m^2], defaults to 1364[W/m^2]\n asymmetry : numeric\n Asymmetry factor, defaults to 0.85\n- albedo : numeric\n- Albedo, defaults to 0.2\n+ albedo : numeric, default 0.2\n+ Ground surface albedo. [unitless]\n \n Returns\n -------\ndiff --git a/pvlib/irradiance.py b/pvlib/irradiance.py\n--- a/pvlib/irradiance.py\n+++ b/pvlib/irradiance.py\n@@ -304,7 +304,7 @@ def beam_component(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n def get_total_irradiance(surface_tilt, surface_azimuth,\n solar_zenith, solar_azimuth,\n dni, ghi, dhi, dni_extra=None, airmass=None,\n- albedo=.25, surface_type=None,\n+ albedo=0.25, surface_type=None,\n model='isotropic',\n model_perez='allsitescomposite1990'):\n r\"\"\"\n@@ -344,7 +344,7 @@ def get_total_irradiance(surface_tilt, surface_azimuth,\n airmass : None or numeric, default None\n Relative airmass (not adjusted for pressure). [unitless]\n albedo : numeric, default 0.25\n- Surface albedo. [unitless]\n+ Ground surface albedo. [unitless]\n surface_type : None or str, default None\n Surface type. See :py:func:`~pvlib.irradiance.get_ground_diffuse` for\n the list of accepted values.\n@@ -1872,7 +1872,7 @@ def gti_dirint(poa_global, aoi, solar_zenith, solar_azimuth, times,\n applied.\n \n albedo : numeric, default 0.25\n- Surface albedo\n+ Ground surface albedo. [unitless]\n \n model : String, default 'perez'\n Irradiance model. See :py:func:`get_sky_diffuse` for allowed values.\ndiff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -268,7 +268,7 @@ class ModelChainResult:\n _per_array_fields = {'total_irrad', 'aoi', 'aoi_modifier',\n 'spectral_modifier', 'cell_temperature',\n 'effective_irradiance', 'dc', 'diode_params',\n- 'dc_ohmic_losses', 'weather'}\n+ 'dc_ohmic_losses', 'weather', 'albedo'}\n \n # system-level information\n solar_position: Optional[pd.DataFrame] = field(default=None)\n@@ -366,6 +366,10 @@ class ModelChainResult:\n \"\"\"DatetimeIndex containing a copy of the index of the input weather data.\n \"\"\"\n \n+ albedo: Optional[PerArray[pd.Series]] = None\n+ \"\"\"Series (or tuple of Series, one for each array) containing albedo.\n+ \"\"\"\n+\n def _result_type(self, value):\n \"\"\"Coerce `value` to the correct type according to\n ``self._singleton_tuples``.\"\"\"\n@@ -1339,6 +1343,17 @@ def _prep_inputs_solar_pos(self, weather):\n **kwargs)\n return self\n \n+ def _prep_inputs_albedo(self, weather):\n+ \"\"\"\n+ Get albedo from weather\n+ \"\"\"\n+ try:\n+ self.results.albedo = _tuple_from_dfs(weather, 'albedo')\n+ except KeyError:\n+ self.results.albedo = tuple([\n+ a.albedo for a in self.system.arrays])\n+ return self\n+\n def _prep_inputs_airmass(self):\n \"\"\"\n Assign airmass\n@@ -1471,11 +1486,17 @@ def prepare_inputs(self, weather):\n \n Parameters\n ----------\n- weather : DataFrame, or tuple or list of DataFrame\n+ weather : DataFrame, or tuple or list of DataFrames\n Required column names include ``'dni'``, ``'ghi'``, ``'dhi'``.\n- Optional column names are ``'wind_speed'``, ``'temp_air'``; if not\n+ Optional column names are ``'wind_speed'``, ``'temp_air'``,\n+ ``'albedo'``.\n+\n+ If optional columns ``'wind_speed'``, ``'temp_air'`` are not\n provided, air temperature of 20 C and wind speed\n- of 0 m/s will be added to the DataFrame.\n+ of 0 m/s will be added to the ``weather`` DataFrame.\n+\n+ If optional column ``'albedo'`` is provided, albedo values in the\n+ ModelChain's PVSystem.arrays are ignored.\n \n If `weather` is a tuple or list, it must be of the same length and\n order as the Arrays of the ModelChain's PVSystem.\n@@ -1494,7 +1515,7 @@ def prepare_inputs(self, weather):\n Notes\n -----\n Assigns attributes to ``results``: ``times``, ``weather``,\n- ``solar_position``, ``airmass``, ``total_irrad``, ``aoi``\n+ ``solar_position``, ``airmass``, ``total_irrad``, ``aoi``, ``albedo``.\n \n See also\n --------\n@@ -1507,6 +1528,7 @@ def prepare_inputs(self, weather):\n \n self._prep_inputs_solar_pos(weather)\n self._prep_inputs_airmass()\n+ self._prep_inputs_albedo(weather)\n \n # PVSystem.get_irradiance and SingleAxisTracker.get_irradiance\n # and PVSystem.get_aoi and SingleAxisTracker.get_aoi\n@@ -1531,6 +1553,7 @@ def prepare_inputs(self, weather):\n _tuple_from_dfs(self.results.weather, 'dni'),\n _tuple_from_dfs(self.results.weather, 'ghi'),\n _tuple_from_dfs(self.results.weather, 'dhi'),\n+ albedo=self.results.albedo,\n airmass=self.results.airmass['airmass_relative'],\n model=self.transposition_model\n )\n@@ -1724,16 +1747,32 @@ def run_model(self, weather):\n Parameters\n ----------\n weather : DataFrame, or tuple or list of DataFrame\n- Irradiance column names must include ``'dni'``, ``'ghi'``, and\n- ``'dhi'``. If optional columns ``'temp_air'`` and ``'wind_speed'``\n+ Column names must include:\n+\n+ - ``'dni'``\n+ - ``'ghi'``\n+ - ``'dhi'``\n+\n+ Optional columns are:\n+\n+ - ``'temp_air'``\n+ - ``'cell_temperature'``\n+ - ``'module_temperature'``\n+ - ``'wind_speed'``\n+ - ``'albedo'``\n+\n+ If optional columns ``'temp_air'`` and ``'wind_speed'``\n are not provided, air temperature of 20 C and wind speed of 0 m/s\n are added to the DataFrame. If optional column\n ``'cell_temperature'`` is provided, these values are used instead\n- of `temperature_model`. If optional column `module_temperature`\n- is provided, `temperature_model` must be ``'sapm'``.\n+ of `temperature_model`. If optional column ``'module_temperature'``\n+ is provided, ``temperature_model`` must be ``'sapm'``.\n \n- If list or tuple, must be of the same length and order as the\n- Arrays of the ModelChain's PVSystem.\n+ If optional column ``'albedo'`` is provided, ``'albedo'`` may not\n+ be present on the ModelChain's PVSystem.Arrays.\n+\n+ If weather is a list or tuple, it must be of the same length and\n+ order as the Arrays of the ModelChain's PVSystem.\n \n Returns\n -------\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -134,7 +134,7 @@ class PVSystem:\n a single array is created from the other parameters (e.g.\n `surface_tilt`, `surface_azimuth`). Must contain at least one Array,\n if length of arrays is 0 a ValueError is raised. If `arrays` is\n- specified the following parameters are ignored:\n+ specified the following PVSystem parameters are ignored:\n \n - `surface_tilt`\n - `surface_azimuth`\n@@ -157,13 +157,14 @@ class PVSystem:\n North=0, East=90, South=180, West=270.\n \n albedo : None or float, default None\n- The ground albedo. If ``None``, will attempt to use\n- ``surface_type`` and ``irradiance.SURFACE_ALBEDOS``\n- to lookup albedo.\n+ Ground surface albedo. If ``None``, then ``surface_type`` is used\n+ to look up a value in ``irradiance.SURFACE_ALBEDOS``.\n+ If ``surface_type`` is also None then a ground surface albedo\n+ of 0.25 is used.\n \n surface_type : None or string, default None\n- The ground surface type. See ``irradiance.SURFACE_ALBEDOS``\n- for valid values.\n+ The ground surface type. See ``irradiance.SURFACE_ALBEDOS`` for\n+ valid values.\n \n module : None or string, default None\n The model name of the modules.\n@@ -333,30 +334,33 @@ def get_aoi(self, solar_zenith, solar_azimuth):\n \n @_unwrap_single_value\n def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n- dni_extra=None, airmass=None, model='haydavies',\n- **kwargs):\n+ dni_extra=None, airmass=None, albedo=None,\n+ model='haydavies', **kwargs):\n \"\"\"\n Uses the :py:func:`irradiance.get_total_irradiance` function to\n- calculate the plane of array irradiance components on a tilted\n- surface defined by ``self.surface_tilt``,\n- ``self.surface_azimuth``, and ``self.albedo``.\n+ calculate the plane of array irradiance components on the tilted\n+ surfaces defined by each array's ``surface_tilt`` and\n+ ``surface_azimuth``.\n \n Parameters\n ----------\n- solar_zenith : float or Series.\n+ solar_zenith : float or Series\n Solar zenith angle.\n- solar_azimuth : float or Series.\n+ solar_azimuth : float or Series\n Solar azimuth angle.\n dni : float or Series or tuple of float or Series\n- Direct Normal Irradiance\n+ Direct Normal Irradiance. [W/m2]\n ghi : float or Series or tuple of float or Series\n- Global horizontal irradiance\n+ Global horizontal irradiance. [W/m2]\n dhi : float or Series or tuple of float or Series\n- Diffuse horizontal irradiance\n- dni_extra : None, float or Series, default None\n- Extraterrestrial direct normal irradiance\n+ Diffuse horizontal irradiance. [W/m2]\n+ dni_extra : None, float, Series or tuple of float or Series,\\\n+ default None\n+ Extraterrestrial direct normal irradiance. [W/m2]\n airmass : None, float or Series, default None\n- Airmass\n+ Airmass. [unitless]\n+ albedo : None, float or Series, default None\n+ Ground surface albedo. [unitless]\n model : String, default 'haydavies'\n Irradiance model.\n \n@@ -376,17 +380,24 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n poa_irradiance : DataFrame or tuple of DataFrame\n Column names are: ``'poa_global', 'poa_direct', 'poa_diffuse',\n 'poa_sky_diffuse', 'poa_ground_diffuse'``.\n+\n+ See also\n+ --------\n+ pvlib.irradiance.get_total_irradiance\n \"\"\"\n dni = self._validate_per_array(dni, system_wide=True)\n ghi = self._validate_per_array(ghi, system_wide=True)\n dhi = self._validate_per_array(dhi, system_wide=True)\n+\n+ albedo = self._validate_per_array(albedo, system_wide=True)\n+\n return tuple(\n array.get_irradiance(solar_zenith, solar_azimuth,\n dni, ghi, dhi,\n- dni_extra, airmass, model,\n- **kwargs)\n- for array, dni, ghi, dhi in zip(\n- self.arrays, dni, ghi, dhi\n+ dni_extra=dni_extra, airmass=airmass,\n+ albedo=albedo, model=model, **kwargs)\n+ for array, dni, ghi, dhi, albedo in zip(\n+ self.arrays, dni, ghi, dhi, albedo\n )\n )\n \n@@ -1258,14 +1269,14 @@ class Array:\n If not provided, a FixedMount with zero tilt is used.\n \n albedo : None or float, default None\n- The ground albedo. If ``None``, will attempt to use\n- ``surface_type`` to look up an albedo value in\n- ``irradiance.SURFACE_ALBEDOS``. If a surface albedo\n- cannot be found then 0.25 is used.\n+ Ground surface albedo. If ``None``, then ``surface_type`` is used\n+ to look up a value in ``irradiance.SURFACE_ALBEDOS``.\n+ If ``surface_type`` is also None then a ground surface albedo\n+ of 0.25 is used.\n \n surface_type : None or string, default None\n- The ground surface type. See ``irradiance.SURFACE_ALBEDOS``\n- for valid values.\n+ The ground surface type. See ``irradiance.SURFACE_ALBEDOS`` for valid\n+ values.\n \n module : None or string, default None\n The model name of the modules.\n@@ -1425,15 +1436,14 @@ def get_aoi(self, solar_zenith, solar_azimuth):\n solar_zenith, solar_azimuth)\n \n def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n- dni_extra=None, airmass=None, model='haydavies',\n- **kwargs):\n+ dni_extra=None, airmass=None, albedo=None,\n+ model='haydavies', **kwargs):\n \"\"\"\n Get plane of array irradiance components.\n \n Uses the :py:func:`pvlib.irradiance.get_total_irradiance` function to\n calculate the plane of array irradiance components for a surface\n- defined by ``self.surface_tilt`` and ``self.surface_azimuth`` with\n- albedo ``self.albedo``.\n+ defined by ``self.surface_tilt`` and ``self.surface_azimuth``.\n \n Parameters\n ----------\n@@ -1442,15 +1452,17 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n solar_azimuth : float or Series.\n Solar azimuth angle.\n dni : float or Series\n- Direct Normal Irradiance\n- ghi : float or Series\n+ Direct normal irradiance. [W/m2]\n+ ghi : float or Series. [W/m2]\n Global horizontal irradiance\n dhi : float or Series\n- Diffuse horizontal irradiance\n+ Diffuse horizontal irradiance. [W/m2]\n dni_extra : None, float or Series, default None\n- Extraterrestrial direct normal irradiance\n+ Extraterrestrial direct normal irradiance. [W/m2]\n airmass : None, float or Series, default None\n- Airmass\n+ Airmass. [unitless]\n+ albedo : None, float or Series, default None\n+ Ground surface albedo. [unitless]\n model : String, default 'haydavies'\n Irradiance model.\n \n@@ -1463,7 +1475,14 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n poa_irradiance : DataFrame\n Column names are: ``'poa_global', 'poa_direct', 'poa_diffuse',\n 'poa_sky_diffuse', 'poa_ground_diffuse'``.\n+\n+ See also\n+ --------\n+ :py:func:`pvlib.irradiance.get_total_irradiance`\n \"\"\"\n+ if albedo is None:\n+ albedo = self.albedo\n+\n # not needed for all models, but this is easier\n if dni_extra is None:\n dni_extra = irradiance.get_extra_radiation(solar_zenith.index)\n@@ -1478,8 +1497,8 @@ def get_irradiance(self, solar_zenith, solar_azimuth, dni, ghi, dhi,\n dni, ghi, dhi,\n dni_extra=dni_extra,\n airmass=airmass,\n+ albedo=albedo,\n model=model,\n- albedo=self.albedo,\n **kwargs)\n \n def get_iam(self, aoi, iam_model='physical'):\n@@ -3293,7 +3312,7 @@ def dc_ohms_from_percent(vmp_ref, imp_ref, dc_ohmic_percent,\n \n See Also\n --------\n- :py:func:`~pvlib.pvsystem.dc_ohmic_losses`\n+ pvlib.pvsystem.dc_ohmic_losses\n \n References\n ----------\n@@ -3328,7 +3347,7 @@ def dc_ohmic_losses(resistance, current):\n \n See Also\n --------\n- :py:func:`~pvlib.pvsystem.dc_ohms_from_percent`\n+ pvlib.pvsystem.dc_ohms_from_percent\n \n References\n ----------\ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -188,7 +188,8 @@ def get_aoi(self, surface_tilt, surface_azimuth, solar_zenith,\n @_unwrap_single_value\n def get_irradiance(self, surface_tilt, surface_azimuth,\n solar_zenith, solar_azimuth, dni, ghi, dhi,\n- dni_extra=None, airmass=None, model='haydavies',\n+ albedo=None, dni_extra=None, airmass=None,\n+ model='haydavies',\n **kwargs):\n \"\"\"\n Uses the :func:`irradiance.get_total_irradiance` function to\n@@ -215,6 +216,8 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n Global horizontal irradiance\n dhi : float or Series\n Diffuse horizontal irradiance\n+ albedo : None, float or Series, default None\n+ Ground surface albedo. [unitless]\n dni_extra : float or Series, default None\n Extraterrestrial direct normal irradiance\n airmass : float or Series, default None\n@@ -245,6 +248,13 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n ghi = self._validate_per_array(ghi, system_wide=True)\n dhi = self._validate_per_array(dhi, system_wide=True)\n \n+ if albedo is None:\n+ # assign default albedo here because SingleAxisTracker\n+ # initializes albedo to None\n+ albedo = 0.25\n+\n+ albedo = self._validate_per_array(albedo, system_wide=True)\n+\n return tuple(\n irradiance.get_total_irradiance(\n surface_tilt,\n@@ -255,10 +265,10 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n dni_extra=dni_extra,\n airmass=airmass,\n model=model,\n- albedo=self.arrays[0].albedo,\n+ albedo=albedo,\n **kwargs)\n- for array, dni, ghi, dhi in zip(\n- self.arrays, dni, ghi, dhi\n+ for array, dni, ghi, dhi, albedo in zip(\n+ self.arrays, dni, ghi, dhi, albedo\n )\n )\n \n", "test_patch": "diff --git a/pvlib/tests/test_clearsky.py b/pvlib/tests/test_clearsky.py\n--- a/pvlib/tests/test_clearsky.py\n+++ b/pvlib/tests/test_clearsky.py\n@@ -756,6 +756,30 @@ def test_bird():\n assert np.allclose(\n testdata['Dif Hz'].where(dusk, 0.), diffuse_horz[1:48], rtol=1e-3\n )\n+ # repeat test with albedo as a Series\n+ alb_series = pd.Series(0.2, index=times)\n+ irrads = clearsky.bird(\n+ zenith, airmass, aod_380nm, aod_500nm, h2o_cm, o3_cm, press_mB * 100.,\n+ etr, b_a, alb_series\n+ )\n+ Eb, Ebh, Gh, Dh = (irrads[_] for _ in field_names)\n+ direct_beam = pd.Series(np.where(dawn, Eb, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Direct Beam'].where(dusk, 0.), direct_beam[1:48], rtol=1e-3\n+ )\n+ direct_horz = pd.Series(np.where(dawn, Ebh, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Direct Hz'].where(dusk, 0.), direct_horz[1:48], rtol=1e-3\n+ )\n+ global_horz = pd.Series(np.where(dawn, Gh, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Global Hz'].where(dusk, 0.), global_horz[1:48], rtol=1e-3\n+ )\n+ diffuse_horz = pd.Series(np.where(dawn, Dh, 0.), index=times).fillna(0.)\n+ assert np.allclose(\n+ testdata['Dif Hz'].where(dusk, 0.), diffuse_horz[1:48], rtol=1e-3\n+ )\n+\n # test keyword parameters\n irrads2 = clearsky.bird(\n zenith, airmass, aod_380nm, aod_500nm, h2o_cm, dni_extra=etr\ndiff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py\n--- a/pvlib/tests/test_irradiance.py\n+++ b/pvlib/tests/test_irradiance.py\n@@ -120,29 +120,38 @@ def test_get_extra_radiation_invalid():\n irradiance.get_extra_radiation(300, method='invalid')\n \n \n-def test_grounddiffuse_simple_float():\n+def test_get_ground_diffuse_simple_float():\n result = irradiance.get_ground_diffuse(40, 900)\n assert_allclose(result, 26.32000014911496)\n \n \n-def test_grounddiffuse_simple_series(irrad_data):\n+def test_get_ground_diffuse_simple_series(irrad_data):\n ground_irrad = irradiance.get_ground_diffuse(40, irrad_data['ghi'])\n assert ground_irrad.name == 'diffuse_ground'\n \n \n-def test_grounddiffuse_albedo_0(irrad_data):\n+def test_get_ground_diffuse_albedo_0(irrad_data):\n ground_irrad = irradiance.get_ground_diffuse(\n 40, irrad_data['ghi'], albedo=0)\n assert 0 == ground_irrad.all()\n \n \n+def test_get_ground_diffuse_albedo_series(times):\n+ albedo = pd.Series(0.2, index=times)\n+ ground_irrad = irradiance.get_ground_diffuse(\n+ 45, pd.Series(1000, index=times), albedo)\n+ expected = albedo * 0.5 * (1 - np.sqrt(2) / 2.) * 1000\n+ expected.name = 'diffuse_ground'\n+ assert_series_equal(ground_irrad, expected)\n+\n+\n def test_grounddiffuse_albedo_invalid_surface(irrad_data):\n with pytest.raises(KeyError):\n irradiance.get_ground_diffuse(\n 40, irrad_data['ghi'], surface_type='invalid')\n \n \n-def test_grounddiffuse_albedo_surface(irrad_data):\n+def test_get_ground_diffuse_albedo_surface(irrad_data):\n result = irradiance.get_ground_diffuse(40, irrad_data['ghi'],\n surface_type='sand')\n assert_allclose(result, [0, 3.731058, 48.778813, 12.035025], atol=1e-4)\n@@ -387,6 +396,25 @@ def test_get_total_irradiance(irrad_data, ephem_data, dni_et,\n 'poa_ground_diffuse']\n \n \[email protected]('model', ['isotropic', 'klucher',\n+ 'haydavies', 'reindl', 'king', 'perez'])\n+def test_get_total_irradiance_albedo(\n+ irrad_data, ephem_data, dni_et, relative_airmass, model):\n+ albedo = pd.Series(0.2, index=ephem_data.index)\n+ total = irradiance.get_total_irradiance(\n+ 32, 180,\n+ ephem_data['apparent_zenith'], ephem_data['azimuth'],\n+ dni=irrad_data['dni'], ghi=irrad_data['ghi'],\n+ dhi=irrad_data['dhi'],\n+ dni_extra=dni_et, airmass=relative_airmass,\n+ model=model,\n+ albedo=albedo)\n+\n+ assert total.columns.tolist() == ['poa_global', 'poa_direct',\n+ 'poa_diffuse', 'poa_sky_diffuse',\n+ 'poa_ground_diffuse']\n+\n+\n @pytest.mark.parametrize('model', ['isotropic', 'klucher',\n 'haydavies', 'reindl', 'king', 'perez'])\n def test_get_total_irradiance_scalars(model):\n@@ -698,6 +726,14 @@ def test_gti_dirint():\n \n assert_frame_equal(output, expected)\n \n+ # test with albedo as a Series\n+ albedo = pd.Series(0.05, index=times)\n+ output = irradiance.gti_dirint(\n+ poa_global, aoi, zenith, azimuth, times, surface_tilt, surface_azimuth,\n+ albedo=albedo)\n+\n+ assert_frame_equal(output, expected)\n+\n # test temp_dew input\n temp_dew = np.array([70, 80, 20])\n output = irradiance.gti_dirint(\ndiff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -495,6 +495,26 @@ def test_prepare_inputs_multi_weather(\n mc.prepare_inputs(input_type((weather, weather)))\n num_arrays = sapm_dc_snl_ac_system_Array.num_arrays\n assert len(mc.results.total_irrad) == num_arrays\n+ # check that albedo is transfered to mc.results from mc.system.arrays\n+ assert mc.results.albedo == (0.2, 0.2)\n+\n+\[email protected](\"input_type\", [tuple, list])\n+def test_prepare_inputs_albedo_in_weather(\n+ sapm_dc_snl_ac_system_Array, location, input_type):\n+ times = pd.date_range(start='20160101 1200-0700',\n+ end='20160101 1800-0700', freq='6H')\n+ mc = ModelChain(sapm_dc_snl_ac_system_Array, location)\n+ weather = pd.DataFrame({'ghi': 1, 'dhi': 1, 'dni': 1, 'albedo': 0.5},\n+ index=times)\n+ # weather as a single DataFrame\n+ mc.prepare_inputs(weather)\n+ num_arrays = sapm_dc_snl_ac_system_Array.num_arrays\n+ assert len(mc.results.albedo) == num_arrays\n+ # repeat with tuple of weather\n+ mc.prepare_inputs(input_type((weather, weather)))\n+ num_arrays = sapm_dc_snl_ac_system_Array.num_arrays\n+ assert len(mc.results.albedo) == num_arrays\n \n \n def test_prepare_inputs_no_irradiance(sapm_dc_snl_ac_system, location):\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -18,6 +18,7 @@\n from pvlib.pvsystem import FixedMount\n from pvlib import temperature\n from pvlib._deprecation import pvlibDeprecationWarning\n+from pvlib.tools import cosd\n \n \n @pytest.mark.parametrize('iam_model,model_params', [\n@@ -1673,51 +1674,70 @@ def test_PVSystem_multiple_array_get_aoi():\n assert aoi_one > 0\n \n \n-def test_PVSystem_get_irradiance():\n- system = pvsystem.PVSystem(surface_tilt=32, surface_azimuth=135)\[email protected]\n+def solar_pos():\n times = pd.date_range(start='20160101 1200-0700',\n end='20160101 1800-0700', freq='6H')\n location = Location(latitude=32, longitude=-111)\n- solar_position = location.get_solarposition(times)\n+ return location.get_solarposition(times)\n+\n+\n+def test_PVSystem_get_irradiance(solar_pos):\n+ system = pvsystem.PVSystem(surface_tilt=32, surface_azimuth=135)\n irrads = pd.DataFrame({'dni':[900,0], 'ghi':[600,0], 'dhi':[100,0]},\n- index=times)\n+ index=solar_pos.index)\n \n- irradiance = system.get_irradiance(solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ irradiance = system.get_irradiance(solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads['dni'],\n irrads['ghi'],\n irrads['dhi'])\n \n expected = pd.DataFrame(data=np.array(\n- [[ 883.65494055, 745.86141676, 137.79352379, 126.397131 ,\n- 11.39639279],\n- [ 0. , -0. , 0. , 0. , 0. ]]),\n+ [[883.65494055, 745.86141676, 137.79352379, 126.397131, 11.39639279],\n+ [0., -0., 0., 0., 0.]]),\n columns=['poa_global', 'poa_direct',\n 'poa_diffuse', 'poa_sky_diffuse',\n 'poa_ground_diffuse'],\n- index=times)\n+ index=solar_pos.index)\n+ assert_frame_equal(irradiance, expected, check_less_precise=2)\n+\n \n+def test_PVSystem_get_irradiance_albedo(solar_pos):\n+ system = pvsystem.PVSystem(surface_tilt=32, surface_azimuth=135)\n+ irrads = pd.DataFrame({'dni': [900, 0], 'ghi': [600, 0], 'dhi': [100, 0],\n+ 'albedo': [0.5, 0.5]},\n+ index=solar_pos.index)\n+ # albedo as a Series\n+ irradiance = system.get_irradiance(solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n+ irrads['dni'],\n+ irrads['ghi'],\n+ irrads['dhi'],\n+ albedo=irrads['albedo'])\n+ expected = pd.DataFrame(data=np.array(\n+ [[895.05134334, 745.86141676, 149.18992658, 126.397131, 22.79279558],\n+ [0., -0., 0., 0., 0.]]),\n+ columns=['poa_global', 'poa_direct', 'poa_diffuse', 'poa_sky_diffuse',\n+ 'poa_ground_diffuse'],\n+ index=solar_pos.index)\n assert_frame_equal(irradiance, expected, check_less_precise=2)\n \n \n-def test_PVSystem_get_irradiance_model(mocker):\n+def test_PVSystem_get_irradiance_model(mocker, solar_pos):\n spy_perez = mocker.spy(irradiance, 'perez')\n spy_haydavies = mocker.spy(irradiance, 'haydavies')\n system = pvsystem.PVSystem(surface_tilt=32, surface_azimuth=135)\n- times = pd.date_range(start='20160101 1200-0700',\n- end='20160101 1800-0700', freq='6H')\n- location = Location(latitude=32, longitude=-111)\n- solar_position = location.get_solarposition(times)\n irrads = pd.DataFrame({'dni': [900, 0], 'ghi': [600, 0], 'dhi': [100, 0]},\n- index=times)\n- system.get_irradiance(solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ index=solar_pos.index)\n+ system.get_irradiance(solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads['dni'],\n irrads['ghi'],\n irrads['dhi'])\n spy_haydavies.assert_called_once()\n- system.get_irradiance(solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ system.get_irradiance(solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads['dni'],\n irrads['ghi'],\n irrads['dhi'],\n@@ -1725,31 +1745,28 @@ def test_PVSystem_get_irradiance_model(mocker):\n spy_perez.assert_called_once()\n \n \n-def test_PVSystem_multi_array_get_irradiance():\n+def test_PVSystem_multi_array_get_irradiance(solar_pos):\n array_one = pvsystem.Array(pvsystem.FixedMount(surface_tilt=32,\n surface_azimuth=135))\n array_two = pvsystem.Array(pvsystem.FixedMount(surface_tilt=5,\n surface_azimuth=150))\n system = pvsystem.PVSystem(arrays=[array_one, array_two])\n- location = Location(latitude=32, longitude=-111)\n- times = pd.date_range(start='20160101 1200-0700',\n- end='20160101 1800-0700', freq='6H')\n- solar_position = location.get_solarposition(times)\n+\n irrads = pd.DataFrame({'dni': [900, 0], 'ghi': [600, 0], 'dhi': [100, 0]},\n- index=times)\n+ index=solar_pos.index)\n array_one_expected = array_one.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads['dni'], irrads['ghi'], irrads['dhi']\n )\n array_two_expected = array_two.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads['dni'], irrads['ghi'], irrads['dhi']\n )\n array_one_irrad, array_two_irrad = system.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads['dni'], irrads['ghi'], irrads['dhi']\n )\n assert_frame_equal(\n@@ -1760,7 +1777,7 @@ def test_PVSystem_multi_array_get_irradiance():\n )\n \n \n-def test_PVSystem_multi_array_get_irradiance_multi_irrad():\n+def test_PVSystem_multi_array_get_irradiance_multi_irrad(solar_pos):\n \"\"\"Test a system with two identical arrays but different irradiance.\n \n Because only the irradiance is different we expect the same output\n@@ -1771,39 +1788,36 @@ def test_PVSystem_multi_array_get_irradiance_multi_irrad():\n array_one = pvsystem.Array(pvsystem.FixedMount(0, 180))\n array_two = pvsystem.Array(pvsystem.FixedMount(0, 180))\n system = pvsystem.PVSystem(arrays=[array_one, array_two])\n- location = Location(latitude=32, longitude=-111)\n- times = pd.date_range(start='20160101 1200-0700',\n- end='20160101 1800-0700', freq='6H')\n- solar_position = location.get_solarposition(times)\n+\n irrads = pd.DataFrame({'dni': [900, 0], 'ghi': [600, 0], 'dhi': [100, 0]},\n- index=times)\n+ index=solar_pos.index)\n irrads_two = pd.DataFrame(\n {'dni': [0, 900], 'ghi': [0, 600], 'dhi': [0, 100]},\n- index=times\n+ index=solar_pos.index\n )\n array_irrad = system.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n (irrads['dhi'], irrads['dhi']),\n (irrads['ghi'], irrads['ghi']),\n (irrads['dni'], irrads['dni'])\n )\n assert_frame_equal(array_irrad[0], array_irrad[1])\n array_irrad = system.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n (irrads['dhi'], irrads_two['dhi']),\n (irrads['ghi'], irrads_two['ghi']),\n (irrads['dni'], irrads_two['dni'])\n )\n array_one_expected = array_one.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads['dhi'], irrads['ghi'], irrads['dni']\n )\n array_two_expected = array_two.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n irrads_two['dhi'], irrads_two['ghi'], irrads_two['dni']\n )\n assert not array_irrad[0].equals(array_irrad[1])\n@@ -1812,15 +1826,15 @@ def test_PVSystem_multi_array_get_irradiance_multi_irrad():\n with pytest.raises(ValueError,\n match=\"Length mismatch for per-array parameter\"):\n system.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n (irrads['dhi'], irrads_two['dhi'], irrads['dhi']),\n (irrads['ghi'], irrads_two['ghi']),\n irrads['dni']\n )\n array_irrad = system.get_irradiance(\n- solar_position['apparent_zenith'],\n- solar_position['azimuth'],\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n (irrads['dhi'], irrads_two['dhi']),\n irrads['ghi'],\n irrads['dni']\n@@ -1829,6 +1843,44 @@ def test_PVSystem_multi_array_get_irradiance_multi_irrad():\n assert not array_irrad[0].equals(array_irrad[1])\n \n \n+def test_Array_get_irradiance(solar_pos):\n+ array = pvsystem.Array(pvsystem.FixedMount(surface_tilt=32,\n+ surface_azimuth=135))\n+ irrads = pd.DataFrame({'dni': [900, 0], 'ghi': [600, 0], 'dhi': [100, 0]},\n+ index=solar_pos.index)\n+ # defaults for kwargs\n+ modeled = array.get_irradiance(\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n+ irrads['dni'], irrads['ghi'], irrads['dhi']\n+ )\n+ expected = pd.DataFrame(\n+ data=np.array(\n+ [[883.65494055, 745.86141676, 137.79352379, 126.397131,\n+ 11.39639279],\n+ [0., -0., 0., 0., 0.]]),\n+ columns=['poa_global', 'poa_direct', 'poa_diffuse', 'poa_sky_diffuse',\n+ 'poa_ground_diffuse'],\n+ index=solar_pos.index\n+ )\n+ assert_frame_equal(modeled, expected, check_less_precise=5)\n+ # with specified kwargs, use isotropic sky diffuse because it's easier\n+ modeled = array.get_irradiance(\n+ solar_pos['apparent_zenith'],\n+ solar_pos['azimuth'],\n+ irrads['dni'], irrads['ghi'], irrads['dhi'],\n+ albedo=0.5, model='isotropic'\n+ )\n+ sky_diffuse = irradiance.isotropic(array.mount.surface_tilt, irrads['dhi'])\n+ ground_diff = irradiance.get_ground_diffuse(\n+ array.mount.surface_tilt, irrads['ghi'], 0.5, surface_type=None)\n+ aoi = irradiance.aoi(array.mount.surface_tilt, array.mount.surface_azimuth,\n+ solar_pos['apparent_zenith'], solar_pos['azimuth'])\n+ direct = irrads['dni'] * cosd(aoi)\n+ expected = sky_diffuse + ground_diff + direct\n+ assert_series_equal(expected, expected, check_less_precise=5)\n+\n+\n @fail_on_pvlib_version('0.10')\n @pytest.mark.parametrize('attr', ['module_parameters', 'module', 'module_type',\n 'temperature_model_parameters', 'albedo',\ndiff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -393,6 +393,25 @@ def test_get_irradiance():\n \n assert_frame_equal(irradiance, expected, check_less_precise=2)\n \n+ # test with albedo as a Series\n+ irrads['albedo'] = [0.5, 0.5]\n+ with np.errstate(invalid='ignore'):\n+ irradiance = system.get_irradiance(tracker_data['surface_tilt'],\n+ tracker_data['surface_azimuth'],\n+ solar_zenith,\n+ solar_azimuth,\n+ irrads['dni'],\n+ irrads['ghi'],\n+ irrads['dhi'],\n+ albedo=irrads['albedo'])\n+\n+ expected = pd.Series(data=[21.05514984, nan], index=times,\n+ name='poa_ground_diffuse')\n+\n+ assert_series_equal(irradiance['poa_ground_diffuse'], expected,\n+ check_less_precise=2)\n+\n+\n \n def test_SingleAxisTracker___repr__():\n with pytest.warns(pvlibDeprecationWarning):\n", "problem_statement": "ModelChain should accept albedo in weather dataframe\n**Is your feature request related to a problem? Please describe.**\r\nAlbedo is treated as a scalar constant in pvlib, but it is of course a function of the weather and changes throughout the year. Albedo is currently set in the PVSystem or Array and cannot be altered using the ModelChain. Albedo is provided as a timeseries from many weather data services as well as through NREL's NSRBD and it would be useful to provide this data to the ModelChain.\r\n\r\nAdditionally, treating albedo as property of the Array seems to conflict with the [PVSystem Design Philosophy](https://pvlib-python.readthedocs.io/en/stable/pvsystem.html#design-philosophy), which highlights the separation of the PV system and the exogenous variables, such as the weather.\r\n\r\n**Describe the solution you'd like**\r\nModelChain.run_model() should accept albedo in the weather dataframe, like temperature and ghi.\r\n\r\n**Describe alternatives you've considered**\r\nAn alternative we have implemented is calling ModelChain.run_model() on each row of a dataframe and manually updating the albedo of the array in each tilmestep. This probably has some side effects that we are unaware of.\r\n\n", "hints_text": "I think I agree that it would make more sense to pass around ground albedo with the weather data instead of treating it as a characteristic of the array. \r\n\r\n> Albedo is treated as a scalar constant in pvlib\r\n\r\n> An alternative we have implemented is calling ModelChain.run_model() on each row of a dataframe and manually updating the albedo of the array in each tilmestep. \r\n\r\nIt is true that the docs for `Array` and `PVSystem` say that `albedo` is a float, but I think it also works to set albedo to a time series that matches the weather you pass to `ModelChain.run_model()`. At least that saves you from looping w/ scalar albedo values. \nI agree that albedo can change with e.g., precipitation or season, but it is also a property of the bare ground surface, and it is that perspective that put albedo with the system parameters. One use case for not having albedo in the weather data would be to evaluate the effect of different ground cover on array output.\r\n\r\nI am only away of the NSRDB offering albedo with weather data; are there other sources?\r\n\r\nI'm +1 on allowing `albedo` to be a Series. I'm neutral on bundling albedo with weather data, but I don't see a better option. We only have two data structures that supply `ModelChain`: the `weather` DataFrame, and the `PVSystem` instance. I don't think it is practical to create a third just for `albedo`, and it isn't any more work to add or modify `albedo` to `weather` than it is to extract `albedo` from downloaded weather data and add it to `PVSystem`.\r\n\r\n\nTo clarify my above message, I think it *already* works to set `PVSystem.albedo` or `Array.albedo` to a Series, despite the docs saying it must be float. \r\n\r\n> are there other sources?\r\n\r\nA non-exhaustive list of examples: [SolarAnywhere](https://www.solaranywhere.com/support/data-fields/albedo/), [SolarGIS](https://solargis.com/docs/getting-started/data-parameters), [MERRA2](https://disc.gsfc.nasa.gov/datasets/M2TMNXRAD_5.12.4/summary)\nDoes anyone know if including time-specific albedo this has been shown to be even more important with bifacials?\r\n\r\n(I would think yes.)\n> Does anyone know if including time-specific albedo this has been shown to be even more important with bifacials?\r\n> \r\n> (I would think yes.)\r\n\r\nYes, it is more important than for single-sided modules. There are ground surfaces where the albedo depends on the solar elevation and hence time of day.\r\n\r\nOne caution about albedo from satellite-derived irradiance: those values are at least km^2 scale, and are observed from space, whereas a PV model is assuming that the albedo is localized (m^2) and has been determined from the irradiance reaching the ground. [SolarAnywhere ](https://www.solaranywhere.com/support/data-fields/albedo/)provides an informative list of caveats.\r\n\r\nThe good news is that the uncertainty in albedo is typically secondary to uncertainty in other data such as GHI, when considering uncertainty in energy production.\r\n\nWhich is the better course of action?\r\n\r\n1. Leave `albedo` on `PVsystem` or `Array`. Edit the docstrings and add tests to make it explicit that `PVSystem.albedo` or `Array.albedo` can be a Series. Advantages: avoids deprecating and removing `PVSystem.albedo`. Downside: users obtaining albedo from weather data sources have an extra step to perform when using `ModelChain` methods.\r\n2. Add `albedo` as an optional column in `weather`, and have `ModelChain` methods use `weather['albedo']` instead of `PVSystem.albedo` when `weather['albedo']` is present. Advantages: convenient for ModelChain users, and avoids deprecating `PVsystem.albedo`. Disadvatanges: potential for confusion when a user also assigns `PVSystem.albedo`. \r\n3. Move `albedo` from `PVSystem` to `weather`. Same advantages as 2, but requires deprecation, and adds an extra step for users who aren't getting albedo with weather data, and would probably lead to adding code to `ModelChain` similar to the code that infers albedo from `PVSystem.surface_type`.\n@cwhanse I lean toward option 1. However, it seems that for option 1, a user might have to duplicate computations already done in the `ModelChain` in the preliminary step of using the weather to compute the existing `PVSystem.albedo` (as some formulaic combination of ground conditions and weather). Do you know if this is really an issue?\nThanks for the discussion around this feature. I favor Option 2, noting that PVSystem.albedo is already an optional argument. Option 1 is prone to bugs and cases need to be handled checking for mismatches in series/dataframe lengths or perhaps same series lengths but different indices. I would discourage Option 3, as it seems there is both a basis for and utility in retaining albedo as a property of PVSystem.\nFor option 2, I would say raise an exception (or at very least a warning) if two albedos are specified. This could definitely be the source of a subtle computational bug when users don't realize a weather file they pulled is doing something they didn't intend.\n+1 for option 2, and I agree with @campanelli-sunpower that an exception should be raised if two albedos are specified\n+1 for option 2, but I like keeping the old method for the case where you just want to set either a single annual albedo or monthly albedos (tho not sure if this option currently exists). I agree also raise exception if both are specified - we can always change it later.", "created_at": "2022-06-21T18:33:24Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_albedo_in_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_albedo_in_weather[list]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_albedo", "pvlib/tests/test_pvsystem.py::test_Array_get_irradiance", "pvlib/tests/test_tracking.py::test_get_irradiance"], "PASS_TO_PASS": ["pvlib/tests/test_clearsky.py::test_ineichen_series", "pvlib/tests/test_clearsky.py::test_ineichen_series_perez_enhancement", "pvlib/tests/test_clearsky.py::test_ineichen_scalar_input", "pvlib/tests/test_clearsky.py::test_ineichen_nans", "pvlib/tests/test_clearsky.py::test_ineichen_arrays", "pvlib/tests/test_clearsky.py::test_ineichen_dni_extra", "pvlib/tests/test_clearsky.py::test_ineichen_altitude", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_leapyear", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_nointerp", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_months", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_months_leapyear", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_nointerp_months", "pvlib/tests/test_clearsky.py::test_haurwitz", "pvlib/tests/test_clearsky.py::test_simplified_solis_scalar_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_scalar_neg_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_series_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_dni_extra", "pvlib/tests/test_clearsky.py::test_simplified_solis_pressure", "pvlib/tests/test_clearsky.py::test_simplified_solis_aod700", "pvlib/tests/test_clearsky.py::test_simplified_solis_precipitable_water", "pvlib/tests/test_clearsky.py::test_simplified_solis_small_scalar_pw", "pvlib/tests/test_clearsky.py::test_simplified_solis_return_arrays", "pvlib/tests/test_clearsky.py::test_simplified_solis_nans_arrays", "pvlib/tests/test_clearsky.py::test_simplified_solis_nans_series", "pvlib/tests/test_clearsky.py::test_linke_turbidity_corners", "pvlib/tests/test_clearsky.py::test_degrees_to_index_1", "pvlib/tests/test_clearsky.py::test_detect_clearsky", "pvlib/tests/test_clearsky.py::test_detect_clearsky_defaults", "pvlib/tests/test_clearsky.py::test_detect_clearsky_components", "pvlib/tests/test_clearsky.py::test_detect_clearsky_iterations", "pvlib/tests/test_clearsky.py::test_detect_clearsky_kwargs", "pvlib/tests/test_clearsky.py::test_detect_clearsky_window", "pvlib/tests/test_clearsky.py::test_detect_clearsky_time_interval", "pvlib/tests/test_clearsky.py::test_detect_clearsky_arrays", "pvlib/tests/test_clearsky.py::test_detect_clearsky_irregular_times", "pvlib/tests/test_clearsky.py::test_detect_clearsky_missing_index", "pvlib/tests/test_clearsky.py::test__line_length_windowed", "pvlib/tests/test_clearsky.py::test__max_diff_windowed", "pvlib/tests/test_clearsky.py::test__calc_stats", "pvlib/tests/test_clearsky.py::test_bird", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_float", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_series", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_reindl", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_negative_horizon", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_model_invalid", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_airmass", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_airmass", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_aoi_projection_precision", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent", "pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_noct_sam_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_run_model_tracker_list", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_len1_weather_tuple", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params4-noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_dc_model_incomplete", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_ohms_from_percent", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_no_dc_ohmic_loss", "pvlib/tests/test_modelchain.py::test_dc_ohmic_ext_def", "pvlib/tests/test_modelchain.py::test_dc_ohmic_not_a_model", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_type]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[temperature_model_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[albedo]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_tilt]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_azimuth]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[racking_model]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[modules_per_string]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[strings_per_inverter]", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]", "pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_calc_axis_tilt", "pvlib/tests/test_tracking.py::test_slope_aware_backtracking", "pvlib/tests/test_tracking.py::test_singleaxis_aoi_gh1221", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_types", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_kwargs", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_special"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1072", "base_commit": "04a523fafbd61bc2e49420963b84ed8e2bd1b3cf", "patch": "diff --git a/pvlib/temperature.py b/pvlib/temperature.py\n--- a/pvlib/temperature.py\n+++ b/pvlib/temperature.py\n@@ -599,8 +599,9 @@ def fuentes(poa_global, temp_air, wind_speed, noct_installed, module_height=5,\n # n.b. the way Fuentes calculates the first timedelta makes it seem like\n # the value doesn't matter -- rather than recreate it here, just assume\n # it's the same as the second timedelta:\n- timedelta_hours = np.diff(poa_global.index).astype(float) / 1e9 / 60 / 60\n- timedelta_hours = np.append([timedelta_hours[0]], timedelta_hours)\n+ timedelta_seconds = poa_global.index.to_series().diff().dt.total_seconds()\n+ timedelta_hours = timedelta_seconds / 3600\n+ timedelta_hours.iloc[0] = timedelta_hours.iloc[1]\n \n tamb_array = temp_air + 273.15\n sun_array = poa_global * absorp\n", "test_patch": "diff --git a/pvlib/tests/test_temperature.py b/pvlib/tests/test_temperature.py\n--- a/pvlib/tests/test_temperature.py\n+++ b/pvlib/tests/test_temperature.py\n@@ -190,3 +190,17 @@ def test_fuentes(filename, inoct):\n night_difference = expected_tcell[is_night] - actual_tcell[is_night]\n assert night_difference.max() < 6\n assert night_difference.min() > 0\n+\n+\[email protected]('tz', [None, 'Etc/GMT+5'])\n+def test_fuentes_timezone(tz):\n+ index = pd.date_range('2019-01-01', freq='h', periods=3, tz=tz)\n+\n+ df = pd.DataFrame({'poa_global': 1000, 'temp_air': 20, 'wind_speed': 1},\n+ index)\n+\n+ out = temperature.fuentes(df['poa_global'], df['temp_air'],\n+ df['wind_speed'], noct_installed=45)\n+\n+ assert_series_equal(out, pd.Series([47.85, 50.85, 50.85], index=index,\n+ name='tmod'))\n", "problem_statement": "temperature.fuentes errors when given tz-aware inputs on pandas>=1.0.0\n**Describe the bug**\r\nWhen the weather timeseries inputs to `temperature.fuentes` have tz-aware index, an internal call to `np.diff(index)` returns an array of `Timedelta` objects instead of an array of nanosecond ints, throwing an error immediately after. The error only happens when using pandas>=1.0.0; using 0.25.3 runs successfully, but emits the warning:\r\n\r\n```\r\n /home/kevin/anaconda3/envs/pvlib-dev/lib/python3.7/site-packages/numpy/lib/function_base.py:1243: FutureWarning: Converting timezone-aware DatetimeArray to timezone-naive ndarray with 'datetime64[ns]' dtype. In the future, this will return an ndarray with 'object' dtype where each element is a 'pandas.Timestamp' with the correct 'tz'.\r\n \tTo accept the future behavior, pass 'dtype=object'.\r\n \tTo keep the old behavior, pass 'dtype=\"datetime64[ns]\"'.\r\n a = asanyarray(a)\r\n```\r\n\r\n**To Reproduce**\r\n```python\r\nIn [1]: import pvlib\r\n ...: import pandas as pd\r\n ...: \r\n ...: index_naive = pd.date_range('2019-01-01', freq='h', periods=3)\r\n ...: \r\n ...: kwargs = {\r\n ...: 'poa_global': pd.Series(1000, index_naive),\r\n ...: 'temp_air': pd.Series(20, index_naive),\r\n ...: 'wind_speed': pd.Series(1, index_naive),\r\n ...: 'noct_installed': 45\r\n ...: }\r\n ...: \r\n\r\nIn [2]: print(pvlib.temperature.fuentes(**kwargs))\r\n2019-01-01 00:00:00 47.85\r\n2019-01-01 01:00:00 50.85\r\n2019-01-01 02:00:00 50.85\r\nFreq: H, Name: tmod, dtype: float64\r\n\r\nIn [3]: kwargs['poa_global'].index = index_naive.tz_localize('UTC')\r\n ...: print(pvlib.temperature.fuentes(**kwargs))\r\n ...: \r\nTraceback (most recent call last):\r\n\r\n File \"<ipython-input-3-ff99badadc91>\", line 2, in <module>\r\n print(pvlib.temperature.fuentes(**kwargs))\r\n\r\n File \"/home/kevin/anaconda3/lib/python3.7/site-packages/pvlib/temperature.py\", line 602, in fuentes\r\n timedelta_hours = np.diff(poa_global.index).astype(float) / 1e9 / 60 / 60\r\n\r\nTypeError: float() argument must be a string or a number, not 'Timedelta'\r\n```\r\n\r\n**Expected behavior**\r\n`temperature.fuentes` should work with both tz-naive and tz-aware inputs.\r\n\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.8.0\r\n - ``pandas.__version__``: 1.0.0+\r\n - python: 3.7.4 (default, Aug 13 2019, 20:35:49) \\n[GCC 7.3.0]\r\n\r\n\n", "hints_text": "", "created_at": "2020-10-01T00:53:14Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_temperature.py::test_fuentes_timezone[Etc/GMT+5]"], "PASS_TO_PASS": ["pvlib/tests/test_temperature.py::test_sapm_cell", "pvlib/tests/test_temperature.py::test_sapm_module", "pvlib/tests/test_temperature.py::test_sapm_cell_from_module", "pvlib/tests/test_temperature.py::test_sapm_ndarray", "pvlib/tests/test_temperature.py::test_sapm_series", "pvlib/tests/test_temperature.py::test_pvsyst_cell_default", "pvlib/tests/test_temperature.py::test_pvsyst_cell_kwargs", "pvlib/tests/test_temperature.py::test_pvsyst_cell_ndarray", "pvlib/tests/test_temperature.py::test_pvsyst_cell_series", "pvlib/tests/test_temperature.py::test_faiman_default", "pvlib/tests/test_temperature.py::test_faiman_kwargs", "pvlib/tests/test_temperature.py::test_faiman_list", "pvlib/tests/test_temperature.py::test_faiman_ndarray", "pvlib/tests/test_temperature.py::test_faiman_series", "pvlib/tests/test_temperature.py::test__temperature_model_params", "pvlib/tests/test_temperature.py::test_fuentes[pvwatts_8760_rackmount.csv-45]", "pvlib/tests/test_temperature.py::test_fuentes[pvwatts_8760_roofmount.csv-49]", "pvlib/tests/test_temperature.py::test_fuentes_timezone[None]"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1073", "base_commit": "b105021f7c1a47f888363af5585083fc27aefd4c", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -323,9 +323,9 @@ class ModelChain:\n as the first argument to a user-defined function.\n \n temperature_model: None, str or function, default None\n- Valid strings are 'sapm', 'pvsyst', and 'faiman'. The ModelChain\n- instance will be passed as the first argument to a user-defined\n- function.\n+ Valid strings are 'sapm', 'pvsyst', 'faiman', and 'fuentes'.\n+ The ModelChain instance will be passed as the first argument to a\n+ user-defined function.\n \n losses_model: str or function, default 'no_loss'\n Valid strings are 'pvwatts', 'no_loss'. The ModelChain instance\n@@ -866,6 +866,8 @@ def temperature_model(self, model):\n self._temperature_model = self.pvsyst_temp\n elif model == 'faiman':\n self._temperature_model = self.faiman_temp\n+ elif model == 'fuentes':\n+ self._temperature_model = self.fuentes_temp\n else:\n raise ValueError(model + ' is not a valid temperature model')\n # check system.temperature_model_parameters for consistency\n@@ -891,6 +893,8 @@ def infer_temperature_model(self):\n return self.pvsyst_temp\n elif {'u0', 'u1'} <= params:\n return self.faiman_temp\n+ elif {'noct_installed'} <= params:\n+ return self.fuentes_temp\n else:\n raise ValueError('could not infer temperature model from '\n 'system.temperature_module_parameters {}.'\n@@ -914,6 +918,12 @@ def faiman_temp(self):\n self.weather['wind_speed'])\n return self\n \n+ def fuentes_temp(self):\n+ self.cell_temperature = self.system.fuentes_celltemp(\n+ self.total_irrad['poa_global'], self.weather['temp_air'],\n+ self.weather['wind_speed'])\n+ return self\n+\n @property\n def losses_model(self):\n return self._losses_model\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -609,6 +609,46 @@ def faiman_celltemp(self, poa_global, temp_air, wind_speed=1.0):\n return temperature.faiman(poa_global, temp_air, wind_speed,\n **kwargs)\n \n+ def fuentes_celltemp(self, poa_global, temp_air, wind_speed):\n+ \"\"\"\n+ Use :py:func:`temperature.fuentes` to calculate cell temperature.\n+\n+ Parameters\n+ ----------\n+ poa_global : pandas Series\n+ Total incident irradiance [W/m^2]\n+\n+ temp_air : pandas Series\n+ Ambient dry bulb temperature [C]\n+\n+ wind_speed : pandas Series\n+ Wind speed [m/s]\n+\n+ Returns\n+ -------\n+ temperature_cell : pandas Series\n+ The modeled cell temperature [C]\n+\n+ Notes\n+ -----\n+ The Fuentes thermal model uses the module surface tilt for convection\n+ modeling. The SAM implementation of PVWatts hardcodes the surface tilt\n+ value at 30 degrees, ignoring whatever value is used for irradiance\n+ transposition. This method defaults to using ``self.surface_tilt``, but\n+ if you want to match the PVWatts behavior, you can override it by\n+ including a ``surface_tilt`` value in ``temperature_model_parameters``.\n+ \"\"\"\n+ # default to using the PVSystem attribute, but allow user to\n+ # override with a custom surface_tilt value\n+ kwargs = {'surface_tilt': self.surface_tilt}\n+ temp_model_kwargs = _build_kwargs([\n+ 'noct_installed', 'module_height', 'wind_height', 'emissivity',\n+ 'absorption', 'surface_tilt', 'module_width', 'module_length'],\n+ self.temperature_model_parameters)\n+ kwargs.update(temp_model_kwargs)\n+ return temperature.fuentes(poa_global, temp_air, wind_speed,\n+ **kwargs)\n+\n def first_solar_spectral_loss(self, pw, airmass_absolute):\n \n \"\"\"\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -138,6 +138,18 @@ def pvwatts_dc_pvwatts_ac_pvsyst_temp_system():\n return system\n \n \[email protected](scope=\"function\")\n+def pvwatts_dc_pvwatts_ac_fuentes_temp_system():\n+ module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003}\n+ temp_model_params = {'noct_installed': 45}\n+ inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95}\n+ system = PVSystem(surface_tilt=32.2, surface_azimuth=180,\n+ module_parameters=module_parameters,\n+ temperature_model_parameters=temp_model_params,\n+ inverter_parameters=inverter_parameters)\n+ return system\n+\n+\n @pytest.fixture(scope=\"function\")\n def system_no_aoi(cec_module_cs5p_220m, sapm_temperature_cs5p_220m,\n cec_inverter_parameters):\n@@ -317,6 +329,23 @@ def test_run_model_with_weather_faiman_temp(sapm_dc_snl_ac_system, location,\n assert not mc.ac.empty\n \n \n+def test_run_model_with_weather_fuentes_temp(sapm_dc_snl_ac_system, location,\n+ weather, mocker):\n+ weather['wind_speed'] = 5\n+ weather['temp_air'] = 10\n+ sapm_dc_snl_ac_system.temperature_model_parameters = {\n+ 'noct_installed': 45\n+ }\n+ mc = ModelChain(sapm_dc_snl_ac_system, location)\n+ mc.temperature_model = 'fuentes'\n+ m_fuentes = mocker.spy(sapm_dc_snl_ac_system, 'fuentes_celltemp')\n+ mc.run_model(weather)\n+ assert m_fuentes.call_count == 1\n+ assert_series_equal(m_fuentes.call_args[0][1], weather['temp_air'])\n+ assert_series_equal(m_fuentes.call_args[0][2], weather['wind_speed'])\n+ assert not mc.ac.empty\n+\n+\n def test_run_model_tracker(sapm_dc_snl_ac_system, location, weather, mocker):\n system = SingleAxisTracker(\n module_parameters=sapm_dc_snl_ac_system.module_parameters,\n@@ -479,14 +508,16 @@ def test_infer_spectral_model(location, sapm_dc_snl_ac_system,\n \n \n @pytest.mark.parametrize('temp_model', [\n- 'sapm_temp', 'faiman_temp', 'pvsyst_temp'])\n+ 'sapm_temp', 'faiman_temp', 'pvsyst_temp', 'fuentes_temp'])\n def test_infer_temp_model(location, sapm_dc_snl_ac_system,\n pvwatts_dc_pvwatts_ac_pvsyst_temp_system,\n pvwatts_dc_pvwatts_ac_faiman_temp_system,\n+ pvwatts_dc_pvwatts_ac_fuentes_temp_system,\n temp_model):\n dc_systems = {'sapm_temp': sapm_dc_snl_ac_system,\n 'pvsyst_temp': pvwatts_dc_pvwatts_ac_pvsyst_temp_system,\n- 'faiman_temp': pvwatts_dc_pvwatts_ac_faiman_temp_system}\n+ 'faiman_temp': pvwatts_dc_pvwatts_ac_faiman_temp_system,\n+ 'fuentes_temp': pvwatts_dc_pvwatts_ac_fuentes_temp_system}\n system = dc_systems[temp_model]\n mc = ModelChain(system, location,\n orientation_strategy='None', aoi_model='physical',\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -360,6 +360,50 @@ def test_PVSystem_faiman_celltemp(mocker):\n assert_allclose(out, 56.4, atol=1)\n \n \n+def test_PVSystem_fuentes_celltemp(mocker):\n+ noct_installed = 45\n+ temp_model_params = {'noct_installed': noct_installed}\n+ system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params)\n+ spy = mocker.spy(temperature, 'fuentes')\n+ index = pd.date_range('2019-01-01 11:00', freq='h', periods=3)\n+ temps = pd.Series(25, index)\n+ irrads = pd.Series(1000, index)\n+ winds = pd.Series(1, index)\n+ out = system.fuentes_celltemp(irrads, temps, winds)\n+ assert_series_equal(spy.call_args[0][0], irrads)\n+ assert_series_equal(spy.call_args[0][1], temps)\n+ assert_series_equal(spy.call_args[0][2], winds)\n+ assert spy.call_args[1]['noct_installed'] == noct_installed\n+ assert_series_equal(out, pd.Series([52.85, 55.85, 55.85], index,\n+ name='tmod'))\n+\n+\n+def test_PVSystem_fuentes_celltemp_override(mocker):\n+ # test that the surface_tilt value in the cell temp calculation can be\n+ # overridden but defaults to the surface_tilt attribute of the PVSystem\n+ spy = mocker.spy(temperature, 'fuentes')\n+\n+ noct_installed = 45\n+ index = pd.date_range('2019-01-01 11:00', freq='h', periods=3)\n+ temps = pd.Series(25, index)\n+ irrads = pd.Series(1000, index)\n+ winds = pd.Series(1, index)\n+\n+ # uses default value\n+ temp_model_params = {'noct_installed': noct_installed}\n+ system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params,\n+ surface_tilt=20)\n+ system.fuentes_celltemp(irrads, temps, winds)\n+ assert spy.call_args[1]['surface_tilt'] == 20\n+\n+ # can be overridden\n+ temp_model_params = {'noct_installed': noct_installed, 'surface_tilt': 30}\n+ system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params,\n+ surface_tilt=20)\n+ system.fuentes_celltemp(irrads, temps, winds)\n+ assert spy.call_args[1]['surface_tilt'] == 30\n+\n+\n def test__infer_temperature_model_params():\n system = pvsystem.PVSystem(module_parameters={},\n racking_model='open_rack',\n", "problem_statement": "expose pvlib.temperature.fuentes in PVSystem and ModelChain\nFollow up to #1032 and #1037 \n", "hints_text": "", "created_at": "2020-10-01T01:40:51Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp_override"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_infer_temp_model_no_params", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[snlinverter]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[adrinverter]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_deprecated_09[snlinverter]", "pvlib/tests/test_modelchain.py::test_deprecated_09[adrinverter]", "pvlib/tests/test_modelchain.py::test_ModelChain_kwargs_deprecated_09", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_location", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_latlon", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize___repr__", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem_creation", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_deprecated_09"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1181", "base_commit": "8b98768818ee5ad85d9479877533651a2e9dc2cd", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -63,11 +63,10 @@\n \n \n def basic_chain(times, latitude, longitude,\n+ surface_tilt, surface_azimuth,\n module_parameters, temperature_model_parameters,\n inverter_parameters,\n irradiance=None, weather=None,\n- surface_tilt=None, surface_azimuth=None,\n- orientation_strategy=None,\n transposition_model='haydavies',\n solar_position_method='nrel_numpy',\n airmass_model='kastenyoung1989',\n@@ -91,6 +90,17 @@ def basic_chain(times, latitude, longitude,\n Positive is east of the prime meridian.\n Use decimal degrees notation.\n \n+ surface_tilt : numeric\n+ Surface tilt angles in decimal degrees.\n+ The tilt angle is defined as degrees from horizontal\n+ (e.g. surface facing up = 0, surface facing horizon = 90)\n+\n+ surface_azimuth : numeric\n+ Surface azimuth angles in decimal degrees.\n+ The azimuth convention is defined\n+ as degrees east of north\n+ (North=0, South=180, East=90, West=270).\n+\n module_parameters : None, dict or Series\n Module parameters as defined by the SAPM. See pvsystem.sapm for\n details.\n@@ -112,23 +122,6 @@ def basic_chain(times, latitude, longitude,\n wind speed is 0 m/s.\n Columns must be 'wind_speed', 'temp_air'.\n \n- surface_tilt : None, float or Series, default None\n- Surface tilt angles in decimal degrees.\n- The tilt angle is defined as degrees from horizontal\n- (e.g. surface facing up = 0, surface facing horizon = 90)\n-\n- surface_azimuth : None, float or Series, default None\n- Surface azimuth angles in decimal degrees.\n- The azimuth convention is defined\n- as degrees east of north\n- (North=0, South=180, East=90, West=270).\n-\n- orientation_strategy : None or str, default None\n- The strategy for aligning the modules.\n- If not None, sets the ``surface_azimuth`` and ``surface_tilt``\n- properties of the ``system``. Allowed strategies include 'flat',\n- 'south_at_latitude_tilt'. Ignored for SingleAxisTracker systems.\n-\n transposition_model : str, default 'haydavies'\n Passed to system.get_irradiance.\n \n@@ -157,17 +150,6 @@ def basic_chain(times, latitude, longitude,\n power (Series).\n \"\"\"\n \n- # use surface_tilt and surface_azimuth if provided,\n- # otherwise set them using the orientation_strategy\n- if surface_tilt is not None and surface_azimuth is not None:\n- pass\n- elif orientation_strategy is not None:\n- surface_tilt, surface_azimuth = \\\n- get_orientation(orientation_strategy, latitude=latitude)\n- else:\n- raise ValueError('orientation_strategy or surface_tilt and '\n- 'surface_azimuth must be provided')\n-\n if altitude is None and pressure is None:\n altitude = 0.\n pressure = 101325.\n@@ -332,12 +314,6 @@ class ModelChain:\n A :py:class:`~pvlib.location.Location` object that represents\n the physical location at which to evaluate the model.\n \n- orientation_strategy : None or str, default None\n- The strategy for aligning the modules. If not None, sets the\n- ``surface_azimuth`` and ``surface_tilt`` properties of the\n- ``system``. Allowed strategies include 'flat',\n- 'south_at_latitude_tilt'. Ignored for SingleAxisTracker systems.\n-\n clearsky_model : str, default 'ineichen'\n Passed to location.get_clearsky.\n \n@@ -395,7 +371,6 @@ class ModelChain:\n 'dc', 'ac', 'diode_params', 'tracking']\n \n def __init__(self, system, location,\n- orientation_strategy=None,\n clearsky_model='ineichen',\n transposition_model='haydavies',\n solar_position_method='nrel_numpy',\n@@ -421,7 +396,6 @@ def __init__(self, system, location,\n self.temperature_model = temperature_model\n \n self.losses_model = losses_model\n- self.orientation_strategy = orientation_strategy\n \n self.weather = None\n self.times = None\n@@ -451,7 +425,6 @@ def __setattr__(self, key, value):\n \n @classmethod\n def with_pvwatts(cls, system, location,\n- orientation_strategy=None,\n clearsky_model='ineichen',\n airmass_model='kastenyoung1989',\n name=None,\n@@ -469,12 +442,6 @@ def with_pvwatts(cls, system, location,\n A :py:class:`~pvlib.location.Location` object that represents\n the physical location at which to evaluate the model.\n \n- orientation_strategy : None or str, default None\n- The strategy for aligning the modules. If not None, sets the\n- ``surface_azimuth`` and ``surface_tilt`` properties of the\n- ``system``. Allowed strategies include 'flat',\n- 'south_at_latitude_tilt'. Ignored for SingleAxisTracker systems.\n-\n clearsky_model : str, default 'ineichen'\n Passed to location.get_clearsky.\n \n@@ -502,7 +469,6 @@ def with_pvwatts(cls, system, location,\n >>> ModelChain.with_pvwatts(system, location)\n ModelChain:\n name: None\n- orientation_strategy: None\n clearsky_model: ineichen\n transposition_model: perez\n solar_position_method: nrel_numpy\n@@ -518,7 +484,6 @@ def with_pvwatts(cls, system, location,\n config.update(kwargs)\n return ModelChain(\n system, location,\n- orientation_strategy=orientation_strategy,\n clearsky_model=clearsky_model,\n airmass_model=airmass_model,\n name=name,\n@@ -527,7 +492,6 @@ def with_pvwatts(cls, system, location,\n \n @classmethod\n def with_sapm(cls, system, location,\n- orientation_strategy=None,\n clearsky_model='ineichen',\n transposition_model='haydavies',\n solar_position_method='nrel_numpy',\n@@ -548,12 +512,6 @@ def with_sapm(cls, system, location,\n A :py:class:`~pvlib.location.Location` object that represents\n the physical location at which to evaluate the model.\n \n- orientation_strategy : None or str, default None\n- The strategy for aligning the modules. If not None, sets the\n- ``surface_azimuth`` and ``surface_tilt`` properties of the\n- ``system``. Allowed strategies include 'flat',\n- 'south_at_latitude_tilt'. Ignored for SingleAxisTracker systems.\n-\n clearsky_model : str, default 'ineichen'\n Passed to location.get_clearsky.\n \n@@ -589,7 +547,6 @@ def with_sapm(cls, system, location,\n >>> ModelChain.with_sapm(system, location)\n ModelChain:\n name: None\n- orientation_strategy: None\n clearsky_model: ineichen\n transposition_model: haydavies\n solar_position_method: nrel_numpy\n@@ -605,7 +562,6 @@ def with_sapm(cls, system, location,\n config.update(kwargs)\n return ModelChain(\n system, location,\n- orientation_strategy=orientation_strategy,\n clearsky_model=clearsky_model,\n transposition_model=transposition_model,\n solar_position_method=solar_position_method,\n@@ -616,7 +572,7 @@ def with_sapm(cls, system, location,\n \n def __repr__(self):\n attrs = [\n- 'name', 'orientation_strategy', 'clearsky_model',\n+ 'name', 'clearsky_model',\n 'transposition_model', 'solar_position_method',\n 'airmass_model', 'dc_model', 'ac_model', 'aoi_model',\n 'spectral_model', 'temperature_model', 'losses_model'\n@@ -634,21 +590,6 @@ def getmcattr(self, attr):\n return ('ModelChain: \\n ' + '\\n '.join(\n f'{attr}: {getmcattr(self, attr)}' for attr in attrs))\n \n- @property\n- def orientation_strategy(self):\n- return self._orientation_strategy\n-\n- @orientation_strategy.setter\n- def orientation_strategy(self, strategy):\n- if strategy == 'None':\n- strategy = None\n-\n- if strategy is not None:\n- self.system.surface_tilt, self.system.surface_azimuth = \\\n- get_orientation(strategy, latitude=self.location.latitude)\n-\n- self._orientation_strategy = strategy\n-\n @property\n def dc_model(self):\n return self._dc_model\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -333,22 +333,6 @@ def test_with_pvwatts(pvwatts_dc_pvwatts_ac_system, location, weather):\n mc.run_model(weather)\n \n \[email protected]('strategy, expected', [\n- (None, (32.2, 180)), ('None', (32.2, 180)), ('flat', (0, 180)),\n- ('south_at_latitude_tilt', (32.2, 180))\n-])\n-def test_orientation_strategy(strategy, expected, sapm_dc_snl_ac_system,\n- location):\n- mc = ModelChain(sapm_dc_snl_ac_system, location,\n- orientation_strategy=strategy)\n-\n- # the || accounts for the coercion of 'None' to None\n- assert (mc.orientation_strategy == strategy or\n- mc.orientation_strategy is None)\n- assert sapm_dc_snl_ac_system.surface_tilt == expected[0]\n- assert sapm_dc_snl_ac_system.surface_azimuth == expected[1]\n-\n-\n def test_run_model_with_irradiance(sapm_dc_snl_ac_system, location):\n mc = ModelChain(sapm_dc_snl_ac_system, location)\n times = pd.date_range('20160101 1200-0700', periods=2, freq='6H')\n@@ -1235,8 +1219,7 @@ def test_infer_spectral_model(location, sapm_dc_snl_ac_system,\n 'cec': cec_dc_snl_ac_system,\n 'cec_native': cec_dc_native_snl_ac_system}\n system = dc_systems[dc_model]\n- mc = ModelChain(system, location,\n- orientation_strategy='None', aoi_model='physical')\n+ mc = ModelChain(system, location, aoi_model='physical')\n assert isinstance(mc, ModelChain)\n \n \n@@ -1252,8 +1235,7 @@ def test_infer_temp_model(location, sapm_dc_snl_ac_system,\n 'faiman_temp': pvwatts_dc_pvwatts_ac_faiman_temp_system,\n 'fuentes_temp': pvwatts_dc_pvwatts_ac_fuentes_temp_system}\n system = dc_systems[temp_model]\n- mc = ModelChain(system, location,\n- orientation_strategy='None', aoi_model='physical',\n+ mc = ModelChain(system, location, aoi_model='physical',\n spectral_model='no_loss')\n assert temp_model == mc.temperature_model.__name__\n assert isinstance(mc, ModelChain)\n@@ -1263,14 +1245,12 @@ def test_infer_temp_model_invalid(location, sapm_dc_snl_ac_system):\n sapm_dc_snl_ac_system.temperature_model_parameters.pop('a')\n with pytest.raises(ValueError):\n ModelChain(sapm_dc_snl_ac_system, location,\n- orientation_strategy='None', aoi_model='physical',\n- spectral_model='no_loss')\n+ aoi_model='physical', spectral_model='no_loss')\n \n \n def test_temperature_model_inconsistent(location, sapm_dc_snl_ac_system):\n with pytest.raises(ValueError):\n- ModelChain(sapm_dc_snl_ac_system, location,\n- orientation_strategy='None', aoi_model='physical',\n+ ModelChain(sapm_dc_snl_ac_system, location, aoi_model='physical',\n spectral_model='no_loss', temperature_model='pvsyst')\n \n \n@@ -1441,17 +1421,14 @@ def test_aoi_model_user_func(sapm_dc_snl_ac_system, location, weather, mocker):\n def test_infer_aoi_model(location, system_no_aoi, aoi_model):\n for k in iam._IAM_MODEL_PARAMS[aoi_model]:\n system_no_aoi.module_parameters.update({k: 1.0})\n- mc = ModelChain(system_no_aoi, location,\n- orientation_strategy='None',\n- spectral_model='no_loss')\n+ mc = ModelChain(system_no_aoi, location, spectral_model='no_loss')\n assert isinstance(mc, ModelChain)\n \n \n def test_infer_aoi_model_invalid(location, system_no_aoi):\n exc_text = 'could not infer AOI model'\n with pytest.raises(ValueError, match=exc_text):\n- ModelChain(system_no_aoi, location, orientation_strategy='None',\n- spectral_model='no_loss')\n+ ModelChain(system_no_aoi, location, spectral_model='no_loss')\n \n \n def constant_spectral_loss(mc):\n@@ -1623,23 +1600,6 @@ def test_ModelChain_attributes_deprecated_10(sapm_dc_snl_ac_system, location):\n mc.aoi = 5\n \n \n-def test_basic_chain_required(sam_data, cec_inverter_parameters,\n- sapm_temperature_cs5p_220m):\n- times = pd.date_range(start='20160101 1200-0700',\n- end='20160101 1800-0700', freq='6H')\n- latitude = 32\n- longitude = -111\n- altitude = 700\n- modules = sam_data['sandiamod']\n- module_parameters = modules['Canadian_Solar_CS5P_220M___2009_']\n- temp_model_params = sapm_temperature_cs5p_220m.copy()\n- with pytest.raises(ValueError):\n- dc, ac = modelchain.basic_chain(\n- times, latitude, longitude, module_parameters, temp_model_params,\n- cec_inverter_parameters, altitude=altitude\n- )\n-\n-\n @requires_tables\n def test_basic_chain_alt_az(sam_data, cec_inverter_parameters,\n sapm_temperature_cs5p_220m):\n@@ -1653,37 +1613,15 @@ def test_basic_chain_alt_az(sam_data, cec_inverter_parameters,\n module_parameters = modules['Canadian_Solar_CS5P_220M___2009_']\n temp_model_params = sapm_temperature_cs5p_220m.copy()\n dc, ac = modelchain.basic_chain(times, latitude, longitude,\n- module_parameters, temp_model_params,\n- cec_inverter_parameters,\n- surface_tilt=surface_tilt,\n- surface_azimuth=surface_azimuth)\n+ surface_tilt, surface_azimuth,\n+ module_parameters, temp_model_params,\n+ cec_inverter_parameters)\n \n expected = pd.Series(np.array([111.621405, -2.00000000e-02]),\n index=times)\n assert_series_equal(ac, expected)\n \n \n-@requires_tables\n-def test_basic_chain_strategy(sam_data, cec_inverter_parameters,\n- sapm_temperature_cs5p_220m):\n- times = pd.date_range(start='20160101 1200-0700',\n- end='20160101 1800-0700', freq='6H')\n- latitude = 32.2\n- longitude = -111\n- altitude = 700\n- modules = sam_data['sandiamod']\n- module_parameters = modules['Canadian_Solar_CS5P_220M___2009_']\n- temp_model_params = sapm_temperature_cs5p_220m.copy()\n- dc, ac = modelchain.basic_chain(\n- times, latitude, longitude, module_parameters, temp_model_params,\n- cec_inverter_parameters, orientation_strategy='south_at_latitude_tilt',\n- altitude=altitude)\n-\n- expected = pd.Series(np.array([178.382754, -2.00000000e-02]),\n- index=times)\n- assert_series_equal(ac, expected)\n-\n-\n @requires_tables\n def test_basic_chain_altitude_pressure(sam_data, cec_inverter_parameters,\n sapm_temperature_cs5p_220m):\n@@ -1698,10 +1636,9 @@ def test_basic_chain_altitude_pressure(sam_data, cec_inverter_parameters,\n module_parameters = modules['Canadian_Solar_CS5P_220M___2009_']\n temp_model_params = sapm_temperature_cs5p_220m.copy()\n dc, ac = modelchain.basic_chain(times, latitude, longitude,\n+ surface_tilt, surface_azimuth,\n module_parameters, temp_model_params,\n cec_inverter_parameters,\n- surface_tilt=surface_tilt,\n- surface_azimuth=surface_azimuth,\n pressure=93194)\n \n expected = pd.Series(np.array([113.190045, -2.00000000e-02]),\n@@ -1709,10 +1646,9 @@ def test_basic_chain_altitude_pressure(sam_data, cec_inverter_parameters,\n assert_series_equal(ac, expected)\n \n dc, ac = modelchain.basic_chain(times, latitude, longitude,\n+ surface_tilt, surface_azimuth,\n module_parameters, temp_model_params,\n cec_inverter_parameters,\n- surface_tilt=surface_tilt,\n- surface_azimuth=surface_azimuth,\n altitude=altitude)\n \n expected = pd.Series(np.array([113.189814, -2.00000000e-02]),\n@@ -1720,34 +1656,6 @@ def test_basic_chain_altitude_pressure(sam_data, cec_inverter_parameters,\n assert_series_equal(ac, expected)\n \n \[email protected]('strategy, strategy_str', [\n- ('south_at_latitude_tilt', 'south_at_latitude_tilt'),\n- (None, 'None')]) # GitHub issue 352\n-def test_ModelChain___repr__(sapm_dc_snl_ac_system, location, strategy,\n- strategy_str):\n-\n- mc = ModelChain(sapm_dc_snl_ac_system, location,\n- orientation_strategy=strategy, name='my mc')\n-\n- expected = '\\n'.join([\n- 'ModelChain: ',\n- ' name: my mc',\n- ' orientation_strategy: ' + strategy_str,\n- ' clearsky_model: ineichen',\n- ' transposition_model: haydavies',\n- ' solar_position_method: nrel_numpy',\n- ' airmass_model: kastenyoung1989',\n- ' dc_model: sapm',\n- ' ac_model: sandia_inverter',\n- ' aoi_model: sapm_aoi_loss',\n- ' spectral_model: sapm_spectral_loss',\n- ' temperature_model: sapm_temp',\n- ' losses_model: no_extra_losses'\n- ])\n-\n- assert mc.__repr__() == expected\n-\n-\n def test_complete_irradiance_clean_run(sapm_dc_snl_ac_system, location):\n \"\"\"The DataFrame should not change if all columns are passed\"\"\"\n mc = ModelChain(sapm_dc_snl_ac_system, location)\n", "problem_statement": "remove ModelChain.orientation_strategy\nI don't like that `ModelChain(system, location, orientation_strategy='flat`|`south_at_latitude_tilt`) modifies the `system` object. It's not something we do anywhere else in pvlib. `orientation_strategy` only supports flat and south_at_latitude_tilt, neither of which are commonly used in the real world in 2020. \r\n\r\nI think we should remove it, maybe even without deprecation, in 0.8.\r\n\r\nI'm ok with keeping the `modelchain.get_orientation` function for now.\n", "hints_text": "", "created_at": "2021-02-28T23:03:01Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_run_model_tracker_list", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1606", "base_commit": "c78b50f4337ecbe536a961336ca91a1176efc0e8", "patch": "diff --git a/pvlib/tools.py b/pvlib/tools.py\n--- a/pvlib/tools.py\n+++ b/pvlib/tools.py\n@@ -341,6 +341,8 @@ def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8):\n --------\n pvlib.singlediode._pwr_optfcn\n \"\"\"\n+ if np.any(upper - lower < 0.):\n+ raise ValueError('upper >= lower is required')\n \n phim1 = (np.sqrt(5) - 1) / 2\n \n@@ -349,16 +351,8 @@ def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8):\n df['VL'] = lower\n \n converged = False\n- iterations = 0\n \n- # handle all NaN case gracefully\n- with warnings.catch_warnings():\n- warnings.filterwarnings(action='ignore',\n- message='All-NaN slice encountered')\n- iterlimit = 1 + np.nanmax(\n- np.trunc(np.log(atol / (df['VH'] - df['VL'])) / np.log(phim1)))\n-\n- while not converged and (iterations <= iterlimit):\n+ while not converged:\n \n phi = phim1 * (df['VH'] - df['VL'])\n df['V1'] = df['VL'] + phi\n@@ -373,22 +367,16 @@ def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8):\n \n err = abs(df['V2'] - df['V1'])\n \n- # works with single value because err is np.float64\n- converged = (err[~np.isnan(err)] < atol).all()\n- # err will be less than atol before iterations hit the limit\n- # but just to be safe\n- iterations += 1\n-\n- if iterations > iterlimit:\n- raise Exception(\"Iterations exceeded maximum. Check that func\",\n- \" is not NaN in (lower, upper)\") # pragma: no cover\n+ # handle all NaN case gracefully\n+ with warnings.catch_warnings():\n+ warnings.filterwarnings(action='ignore',\n+ message='All-NaN slice encountered')\n+ converged = np.all(err[~np.isnan(err)] < atol)\n \n- try:\n- func_result = func(df, 'V1')\n- x = np.where(np.isnan(func_result), np.nan, df['V1'])\n- except KeyError:\n- func_result = np.full_like(upper, np.nan)\n- x = func_result.copy()\n+ # best estimate of location of maximum\n+ df['max'] = 0.5 * (df['V1'] + df['V2'])\n+ func_result = func(df, 'max')\n+ x = np.where(np.isnan(func_result), np.nan, df['max'])\n \n return func_result, x\n \n", "test_patch": "diff --git a/pvlib/tests/test_tools.py b/pvlib/tests/test_tools.py\n--- a/pvlib/tests/test_tools.py\n+++ b/pvlib/tests/test_tools.py\n@@ -45,6 +45,22 @@ def test__golden_sect_DataFrame_vector():\n v, x = tools._golden_sect_DataFrame(params, lower, upper,\n _obj_test_golden_sect)\n assert np.allclose(x, expected, atol=1e-8)\n+ # some upper and lower bounds equal\n+ params = {'c': np.array([1., 2., 1.]), 'n': np.array([1., 1., 1.])}\n+ lower = np.array([0., 0.001, 1.])\n+ upper = np.array([1., 1.2, 1.])\n+ expected = np.array([0.5, 0.25, 1.0]) # x values for maxima\n+ v, x = tools._golden_sect_DataFrame(params, lower, upper,\n+ _obj_test_golden_sect)\n+ assert np.allclose(x, expected, atol=1e-8)\n+ # all upper and lower bounds equal, arrays of length 1\n+ params = {'c': np.array([1.]), 'n': np.array([1.])}\n+ lower = np.array([1.])\n+ upper = np.array([1.])\n+ expected = np.array([1.]) # x values for maxima\n+ v, x = tools._golden_sect_DataFrame(params, lower, upper,\n+ _obj_test_golden_sect)\n+ assert np.allclose(x, expected, atol=1e-8)\n \n \n def test__golden_sect_DataFrame_nans():\n", "problem_statement": "golden-section search fails when upper and lower bounds are equal\n**Describe the bug**\r\nI was using pvlib for sometime now and until now I was always passing a big dataframe containing readings of a long period. Because of some changes in our software architecture, I need to pass the weather readings as a single reading (a dataframe with only one row) and I noticed that for readings that GHI-DHI are zero pvlib fails to calculate the output and returns below error while the same code executes correctly with weather information that has non-zero GHI-DHI:\r\n```python\r\nimport os\r\nimport pathlib\r\nimport time\r\nimport json\r\nfrom datetime import datetime\r\nfrom time import mktime, gmtime\r\n\r\nimport pandas as pd\r\n\r\nfrom pvlib import pvsystem\r\nfrom pvlib import location as pvlocation\r\nfrom pvlib import modelchain\r\nfrom pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS as PARAMS # not used -- to remove\r\nfrom pvlib.bifacial.pvfactors import pvfactors_timeseries\r\nfrom pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS\r\n\r\nclass PV:\r\n def pv_transform_time(self, val):\r\n # tt = gmtime(val / 1000)\r\n tt = gmtime(val)\r\n dd = datetime.fromtimestamp(mktime(tt))\r\n timestamp = pd.Timestamp(dd)\r\n return timestamp\r\n\r\n def __init__(self, model: str, inverter: str, latitude: float, longitude: float, **kwargs):\r\n # super().__init__(**kwargs)\r\n\r\n temperature_model_parameters = TEMPERATURE_MODEL_PARAMETERS[\"sapm\"][\r\n \"open_rack_glass_glass\"\r\n ]\r\n # Load the database of CEC module model parameters\r\n modules = pvsystem.retrieve_sam(\"cecmod\")\r\n # Load the database of CEC inverter model parameters\r\n inverters = pvsystem.retrieve_sam(\"cecinverter\")\r\n\r\n\r\n # A bare bone PV simulator\r\n\r\n # Load the database of CEC module model parameters\r\n modules = pvsystem.retrieve_sam('cecmod')\r\n inverters = pvsystem.retrieve_sam('cecinverter')\r\n module_parameters = modules[model]\r\n inverter_parameters = inverters[inverter]\r\n\r\n location = pvlocation.Location(latitude=latitude, longitude=longitude)\r\n system = pvsystem.PVSystem(module_parameters=module_parameters, inverter_parameters=inverter_parameters, temperature_model_parameters=temperature_model_parameters)\r\n self.modelchain = modelchain.ModelChain(system, location, aoi_model='no_loss', spectral_model=\"no_loss\")\r\n\r\n def process(self, data):\r\n weather = pd.read_json(data)\r\n # print(f\"raw_weather: {weather}\")\r\n weather.drop('time.1', axis=1, inplace=True)\r\n weather['time'] = pd.to_datetime(weather['time']).map(datetime.timestamp) # --> this works for the new process_weather code and also the old weather file\r\n weather[\"time\"] = weather[\"time\"].apply(self.pv_transform_time)\r\n weather.index = weather[\"time\"]\r\n # print(f\"weather: {weather}\")\r\n # print(weather.dtypes)\r\n # print(weather['ghi'][0])\r\n # print(type(weather['ghi'][0]))\r\n\r\n # simulate\r\n self.modelchain.run_model(weather)\r\n # print(self.modelchain.results.ac.to_frame().to_json())\r\n print(self.modelchain.results.ac)\r\n\r\n\r\n# good data\r\ngood_data = \"{\\\"time\\\":{\\\"12\\\":\\\"2010-01-01 13:30:00+00:00\\\"},\\\"ghi\\\":{\\\"12\\\":36},\\\"dhi\\\":{\\\"12\\\":36},\\\"dni\\\":{\\\"12\\\":0},\\\"Tamb\\\":{\\\"12\\\":8.0},\\\"WindVel\\\":{\\\"12\\\":5.0},\\\"WindDir\\\":{\\\"12\\\":270},\\\"time.1\\\":{\\\"12\\\":\\\"2010-01-01 13:30:00+00:00\\\"}}\"\r\n\r\n# data that causes error\r\ndata = \"{\\\"time\\\":{\\\"4\\\":\\\"2010-01-01 05:30:00+00:00\\\"},\\\"ghi\\\":{\\\"4\\\":0},\\\"dhi\\\":{\\\"4\\\":0},\\\"dni\\\":{\\\"4\\\":0},\\\"Tamb\\\":{\\\"4\\\":8.0},\\\"WindVel\\\":{\\\"4\\\":4.0},\\\"WindDir\\\":{\\\"4\\\":240},\\\"time.1\\\":{\\\"4\\\":\\\"2010-01-01 05:30:00+00:00\\\"}}\"\r\np1 = PV(model=\"Trina_Solar_TSM_300DEG5C_07_II_\", inverter=\"ABB__MICRO_0_25_I_OUTD_US_208__208V_\", latitude=51.204483, longitude=5.265472)\r\np1.process(good_data)\r\nprint(\"=====\")\r\np1.process(data)\r\n```\r\nError:\r\n```log\r\n$ python3 ./tmp-pv.py \r\ntime\r\n2010-01-01 13:30:00 7.825527\r\ndtype: float64\r\n=====\r\n/home/user/.local/lib/python3.10/site-packages/pvlib/tools.py:340: RuntimeWarning: divide by zero encountered in divide\r\n np.trunc(np.log(atol / (df['VH'] - df['VL'])) / np.log(phim1)))\r\nTraceback (most recent call last):\r\n File \"/home/user/workspace/enorch/simulator/simulator_processor/src/pv/./tmp-pv.py\", line 88, in <module>\r\n p1.process(data)\r\n File \"/home/user/workspace/enorch/simulator/simulator_processor/src/pv/./tmp-pv.py\", line 75, in process\r\n self.modelchain.run_model(weather)\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py\", line 1770, in run_model\r\n self._run_from_effective_irrad(weather)\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py\", line 1858, in _run_from_effective_irrad\r\n self.dc_model()\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py\", line 790, in cec\r\n return self._singlediode(self.system.calcparams_cec)\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/modelchain.py\", line 772, in _singlediode\r\n self.results.dc = tuple(itertools.starmap(\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/pvsystem.py\", line 931, in singlediode\r\n return singlediode(photocurrent, saturation_current,\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/pvsystem.py\", line 2826, in singlediode\r\n out = _singlediode._lambertw(\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/singlediode.py\", line 651, in _lambertw\r\n p_mp, v_mp = _golden_sect_DataFrame(params, 0., v_oc * 1.14,\r\n File \"/home/user/.local/lib/python3.10/site-packages/pvlib/tools.py\", line 364, in _golden_sect_DataFrame\r\n raise Exception(\"Iterations exceeded maximum. Check that func\",\r\nException: ('Iterations exceeded maximum. Check that func', ' is not NaN in (lower, upper)')\r\n```\r\n\r\nI have to mention that for now the workaround that I am using is to pass the weather data as a dataframe with two rows, the first row is a good weather data that pvlib can process and the second row is the incoming weather reading (I can also post that code if you want).\r\n\r\n**Expected behavior**\r\nPVlib should have consistent behavior and regardless of GHI-DHI readings.\r\n\r\n**Versions:**\r\n```python\r\n>>> import pvlib\r\n>>> import pandas\r\n>>> pvlib.__version__\r\n'0.9.1'\r\n>>> pandas.__version__\r\n'1.4.3'\r\n``` \r\n - python: 3.10.6\r\n- OS: Ubuntu 22.04.1 LTS\n", "hints_text": "Confirmed. This appears to be an oversight in `pvlib.tools._golden_section_DataFrame` involving error messaging, likely introduced with #1089 .\r\n\r\nIn this code when processing the content of `data`, photocurrent is 0., hence the shunt resistance is infinite and v_oc is 0. That sets the range for the golden section search to be [0., 0.]. [iterlimit](https://github.com/pvlib/pvlib-python/blob/582b956c63c463e5178fbb7a88fa545fa5b1c257/pvlib/tools.py#L358) is then -infinity, which skips the loop (`iterations <= iterlimit`) but since `iterations > iterlimit` raises the \"Iterations exceeded...\" exception.\r\n", "created_at": "2022-12-07T21:12:08Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_tools.py::test__golden_sect_DataFrame_vector"], "PASS_TO_PASS": ["pvlib/tests/test_tools.py::test_build_kwargs[keys0-input_dict0-expected0]", "pvlib/tests/test_tools.py::test_build_kwargs[keys1-input_dict1-expected1]", "pvlib/tests/test_tools.py::test_build_kwargs[keys2-input_dict2-expected2]", "pvlib/tests/test_tools.py::test_build_kwargs[keys3-input_dict3-expected3]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params0-0.0-1.0-0.5-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params1-0.0-1.0-0.07230200263994839-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params2-0.0-100.0-89.14332727531685-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_atol", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_nans", "pvlib/tests/test_tools.py::test_degrees_to_index_1"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1480", "base_commit": "35af84e9a7bede8dfe86d6d6c73002393544ab5a", "patch": "diff --git a/pvlib/tools.py b/pvlib/tools.py\n--- a/pvlib/tools.py\n+++ b/pvlib/tools.py\n@@ -85,6 +85,25 @@ def asind(number):\n return res\n \n \n+def acosd(number):\n+ \"\"\"\n+ Inverse Cosine returning an angle in degrees\n+\n+ Parameters\n+ ----------\n+ number : float\n+ Input number\n+\n+ Returns\n+ -------\n+ result : float\n+ arccos result\n+ \"\"\"\n+\n+ res = np.degrees(np.arccos(number))\n+ return res\n+\n+\n def localize_to_utc(time, location):\n \"\"\"\n Converts or localizes a time series to UTC.\ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -1,7 +1,7 @@\n import numpy as np\n import pandas as pd\n \n-from pvlib.tools import cosd, sind, tand\n+from pvlib.tools import cosd, sind, tand, acosd, asind\n from pvlib.pvsystem import (\n PVSystem, Array, SingleAxisTrackerMount, _unwrap_single_value\n )\n@@ -334,9 +334,9 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n Returns\n -------\n dict or DataFrame with the following columns:\n- * `tracker_theta`: The rotation angle of the tracker.\n- tracker_theta = 0 is horizontal, and positive rotation angles are\n- clockwise. [degrees]\n+ * `tracker_theta`: The rotation angle of the tracker is a right-handed\n+ rotation defined by `axis_azimuth`.\n+ tracker_theta = 0 is horizontal. [degrees]\n * `aoi`: The angle-of-incidence of direct irradiance onto the\n rotated panel surface. [degrees]\n * `surface_tilt`: The angle between the panel surface and the earth\n@@ -349,6 +349,7 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n --------\n pvlib.tracking.calc_axis_tilt\n pvlib.tracking.calc_cross_axis_tilt\n+ pvlib.tracking.calc_surface_orientation\n \n References\n ----------\n@@ -396,9 +397,10 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n cos_axis_tilt = cosd(axis_tilt)\n sin_axis_tilt = sind(axis_tilt)\n xp = x*cos_axis_azimuth - y*sin_axis_azimuth\n- yp = (x*cos_axis_tilt*sin_axis_azimuth\n- + y*cos_axis_tilt*cos_axis_azimuth\n- - z*sin_axis_tilt)\n+ # not necessary to calculate y'\n+ # yp = (x*cos_axis_tilt*sin_axis_azimuth\n+ # + y*cos_axis_tilt*cos_axis_azimuth\n+ # - z*sin_axis_tilt)\n zp = (x*sin_axis_tilt*sin_axis_azimuth\n + y*sin_axis_tilt*cos_axis_azimuth\n + z*cos_axis_tilt)\n@@ -446,81 +448,18 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n # system-plane normal\n tracker_theta = np.clip(tracker_theta, -max_angle, max_angle)\n \n- # Calculate panel normal vector in panel-oriented x, y, z coordinates.\n- # y-axis is axis of tracker rotation. tracker_theta is a compass angle\n- # (clockwise is positive) rather than a trigonometric angle.\n- # NOTE: the *0 is a trick to preserve NaN values.\n- panel_norm = np.array([sind(tracker_theta),\n- tracker_theta*0,\n- cosd(tracker_theta)])\n-\n- # sun position in vector format in panel-oriented x, y, z coordinates\n- sun_vec = np.array([xp, yp, zp])\n-\n- # calculate angle-of-incidence on panel\n- # TODO: use irradiance.aoi\n- projection = np.clip(np.sum(sun_vec*panel_norm, axis=0), -1, 1)\n- aoi = np.degrees(np.arccos(projection))\n-\n- # Calculate panel tilt and azimuth in a coordinate system where the panel\n- # tilt is the angle from horizontal, and the panel azimuth is the compass\n- # angle (clockwise from north) to the projection of the panel's normal to\n- # the earth's surface. These outputs are provided for convenience and\n- # comparison with other PV software which use these angle conventions.\n-\n- # Project normal vector to earth surface. First rotate about x-axis by\n- # angle -axis_tilt so that y-axis is also parallel to earth surface, then\n- # project.\n-\n- # Calculate standard rotation matrix\n- rot_x = np.array([[1, 0, 0],\n- [0, cosd(-axis_tilt), -sind(-axis_tilt)],\n- [0, sind(-axis_tilt), cosd(-axis_tilt)]])\n-\n- # panel_norm_earth contains the normal vector expressed in earth-surface\n- # coordinates (z normal to surface, y aligned with tracker axis parallel to\n- # earth)\n- panel_norm_earth = np.dot(rot_x, panel_norm).T\n-\n- # projection to plane tangent to earth surface, in earth surface\n- # coordinates\n- projected_normal = np.array([panel_norm_earth[:, 0],\n- panel_norm_earth[:, 1],\n- panel_norm_earth[:, 2]*0]).T\n-\n- # calculate vector magnitudes\n- projected_normal_mag = np.sqrt(np.nansum(projected_normal**2, axis=1))\n-\n- # renormalize the projected vector, avoid creating nan values.\n- non_zeros = projected_normal_mag != 0\n- projected_normal[non_zeros] = (projected_normal[non_zeros].T /\n- projected_normal_mag[non_zeros]).T\n-\n- # calculation of surface_azimuth\n- surface_azimuth = \\\n- np.degrees(np.arctan2(projected_normal[:, 1], projected_normal[:, 0]))\n-\n- # Rotate 0 reference from panel's x-axis to its y-axis and then back to\n- # north.\n- surface_azimuth = 90 - surface_azimuth + axis_azimuth\n-\n- # Map azimuth into [0,360) domain.\n- with np.errstate(invalid='ignore'):\n- surface_azimuth = surface_azimuth % 360\n-\n- # Calculate surface_tilt\n- dotproduct = (panel_norm_earth * projected_normal).sum(axis=1)\n- # for edge cases like axis_tilt=90, numpy's SIMD can produce values like\n- # dotproduct = (1 + 2e-16). Clip off the excess so that arccos works:\n- dotproduct = np.clip(dotproduct, -1, 1)\n- surface_tilt = 90 - np.degrees(np.arccos(dotproduct))\n+ # Calculate auxiliary angles\n+ surface = calc_surface_orientation(tracker_theta, axis_tilt, axis_azimuth)\n+ surface_tilt = surface['surface_tilt']\n+ surface_azimuth = surface['surface_azimuth']\n+ aoi = irradiance.aoi(surface_tilt, surface_azimuth,\n+ apparent_zenith, apparent_azimuth)\n \n # Bundle DataFrame for return values and filter for sun below horizon.\n out = {'tracker_theta': tracker_theta, 'aoi': aoi,\n- 'surface_tilt': surface_tilt, 'surface_azimuth': surface_azimuth}\n+ 'surface_azimuth': surface_azimuth, 'surface_tilt': surface_tilt}\n if index is not None:\n out = pd.DataFrame(out, index=index)\n- out = out[['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt']]\n out[zen_gt_90] = np.nan\n else:\n out = {k: np.where(zen_gt_90, np.nan, v) for k, v in out.items()}\n@@ -528,6 +467,60 @@ def singleaxis(apparent_zenith, apparent_azimuth,\n return out\n \n \n+def calc_surface_orientation(tracker_theta, axis_tilt=0, axis_azimuth=0):\n+ \"\"\"\n+ Calculate the surface tilt and azimuth angles for a given tracker rotation.\n+\n+ Parameters\n+ ----------\n+ tracker_theta : numeric\n+ Tracker rotation angle as a right-handed rotation around\n+ the axis defined by ``axis_tilt`` and ``axis_azimuth``. For example,\n+ with ``axis_tilt=0`` and ``axis_azimuth=180``, ``tracker_theta > 0``\n+ results in ``surface_azimuth`` to the West while ``tracker_theta < 0``\n+ results in ``surface_azimuth`` to the East. [degree]\n+ axis_tilt : float, default 0\n+ The tilt of the axis of rotation with respect to horizontal. [degree]\n+ axis_azimuth : float, default 0\n+ A value denoting the compass direction along which the axis of\n+ rotation lies. Measured east of north. [degree]\n+\n+ Returns\n+ -------\n+ dict or DataFrame\n+ Contains keys ``'surface_tilt'`` and ``'surface_azimuth'`` representing\n+ the module orientation accounting for tracker rotation and axis\n+ orientation. [degree]\n+\n+ References\n+ ----------\n+ .. [1] William F. Marion and Aron P. Dobos, \"Rotation Angle for the Optimum\n+ Tracking of One-Axis Trackers\", Technical Report NREL/TP-6A20-58891,\n+ July 2013. :doi:`10.2172/1089596`\n+ \"\"\"\n+ with np.errstate(invalid='ignore', divide='ignore'):\n+ surface_tilt = acosd(cosd(tracker_theta) * cosd(axis_tilt))\n+\n+ # clip(..., -1, +1) to prevent arcsin(1 + epsilon) issues:\n+ azimuth_delta = asind(np.clip(sind(tracker_theta) / sind(surface_tilt),\n+ a_min=-1, a_max=1))\n+ # Combine Eqs 2, 3, and 4:\n+ azimuth_delta = np.where(abs(tracker_theta) < 90,\n+ azimuth_delta,\n+ -azimuth_delta + np.sign(tracker_theta) * 180)\n+ # handle surface_tilt=0 case:\n+ azimuth_delta = np.where(sind(surface_tilt) != 0, azimuth_delta, 90)\n+ surface_azimuth = (axis_azimuth + azimuth_delta) % 360\n+\n+ out = {\n+ 'surface_tilt': surface_tilt,\n+ 'surface_azimuth': surface_azimuth,\n+ }\n+ if hasattr(tracker_theta, 'index'):\n+ out = pd.DataFrame(out)\n+ return out\n+\n+\n def calc_axis_tilt(slope_azimuth, slope_tilt, axis_azimuth):\n \"\"\"\n Calculate tracker axis tilt in the global reference frame when on a sloped\n", "test_patch": "diff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -517,3 +517,72 @@ def test_singleaxis_aoi_gh1221():\n fixed = pvlib.irradiance.aoi(90, 180, sp['apparent_zenith'], sp['azimuth'])\n fixed[np.isnan(tr['aoi'])] = np.nan\n assert np.allclose(tr['aoi'], fixed, equal_nan=True)\n+\n+\n+def test_calc_surface_orientation_types():\n+ # numpy arrays\n+ rotations = np.array([-10, 0, 10])\n+ expected_tilts = np.array([10, 0, 10], dtype=float)\n+ expected_azimuths = np.array([270, 90, 90], dtype=float)\n+ out = tracking.calc_surface_orientation(tracker_theta=rotations)\n+ np.testing.assert_allclose(expected_tilts, out['surface_tilt'])\n+ np.testing.assert_allclose(expected_azimuths, out['surface_azimuth'])\n+\n+ # pandas Series\n+ rotations = pd.Series(rotations)\n+ expected_tilts = pd.Series(expected_tilts).rename('surface_tilt')\n+ expected_azimuths = pd.Series(expected_azimuths).rename('surface_azimuth')\n+ out = tracking.calc_surface_orientation(tracker_theta=rotations)\n+ assert_series_equal(expected_tilts, out['surface_tilt'])\n+ assert_series_equal(expected_azimuths, out['surface_azimuth'])\n+\n+ # float\n+ for rotation, expected_tilt, expected_azimuth in zip(\n+ rotations, expected_tilts, expected_azimuths):\n+ out = tracking.calc_surface_orientation(rotation)\n+ assert out['surface_tilt'] == pytest.approx(expected_tilt)\n+ assert out['surface_azimuth'] == pytest.approx(expected_azimuth)\n+\n+\n+def test_calc_surface_orientation_kwargs():\n+ # non-default axis tilt & azimuth\n+ rotations = np.array([-10, 0, 10])\n+ expected_tilts = np.array([22.2687445, 20.0, 22.2687445])\n+ expected_azimuths = np.array([152.72683041, 180.0, 207.27316959])\n+ out = tracking.calc_surface_orientation(rotations,\n+ axis_tilt=20,\n+ axis_azimuth=180)\n+ np.testing.assert_allclose(out['surface_tilt'], expected_tilts)\n+ np.testing.assert_allclose(out['surface_azimuth'], expected_azimuths)\n+\n+\n+def test_calc_surface_orientation_special():\n+ # special cases for rotations\n+ rotations = np.array([-180, -90, -0, 0, 90, 180])\n+ expected_tilts = np.array([180, 90, 0, 0, 90, 180], dtype=float)\n+ expected_azimuths = [270, 270, 90, 90, 90, 90]\n+ out = tracking.calc_surface_orientation(rotations)\n+ np.testing.assert_allclose(out['surface_tilt'], expected_tilts)\n+ np.testing.assert_allclose(out['surface_azimuth'], expected_azimuths)\n+\n+ # special case for axis_tilt\n+ rotations = np.array([-10, 0, 10])\n+ expected_tilts = np.array([90, 90, 90], dtype=float)\n+ expected_azimuths = np.array([350, 0, 10], dtype=float)\n+ out = tracking.calc_surface_orientation(rotations, axis_tilt=90)\n+ np.testing.assert_allclose(out['surface_tilt'], expected_tilts)\n+ np.testing.assert_allclose(out['surface_azimuth'], expected_azimuths)\n+\n+ # special cases for axis_azimuth\n+ rotations = np.array([-10, 0, 10])\n+ expected_tilts = np.array([10, 0, 10], dtype=float)\n+ expected_azimuth_offsets = np.array([-90, 90, 90], dtype=float)\n+ for axis_azimuth in [0, 90, 180, 270, 360]:\n+ expected_azimuths = (axis_azimuth + expected_azimuth_offsets) % 360\n+ out = tracking.calc_surface_orientation(rotations,\n+ axis_azimuth=axis_azimuth)\n+ np.testing.assert_allclose(out['surface_tilt'], expected_tilts)\n+ # the rounding is a bit ugly, but necessary to test approximately equal\n+ # in a modulo-360 sense.\n+ np.testing.assert_allclose(np.round(out['surface_azimuth'], 4) % 360,\n+ expected_azimuths, rtol=1e-5, atol=1e-5)\n", "problem_statement": "Consider extracting the surface orientation calculation in pvlib.tracking.singleaxis() to its own function\n**Is your feature request related to a problem? Please describe.**\r\nThe usual workflow for modeling single-axis tracking in pvlib is to treat tracker rotation (`tracker_theta`) as an unknown to be calculated from solar position and array geometry. However, sometimes a user might have their own tracker rotations but not have the corresponding `surface_tilt` and `surface_azimuth` values. Here are a few motivating examples:\r\n- Using measured rotation angles\r\n- Post-processing the output of `tracking.singleaxis()` to include wind stow events or tracker stalls\r\n- Other tracking algorithms that determine rotation differently from the astronomical method\r\n\r\nAssuming I have my tracker rotations already in hand, getting the corresponding `surface_tilt` and `surface_azimuth` angles is not as easy as it should be. For the specific case of horizontal N-S axis the math isn't so bad, but either way it's annoying to have to DIY when pvlib already has code to calculate those angles from tracker rotation.\r\n\r\n**Describe the solution you'd like**\r\nA function `pvlib.tracking.rotation_to_orientation` that implements the same math in `pvlib.tracking.singleaxis` to go from `tracker_theta` to `surface_tilt` and `surface_azimuth`. Basically extract out the second half of `tracking.singleaxis` into a new function. Suggestions for the function name are welcome. To be explicit, this is more or less what I'm imagining:\r\n\r\n```python\r\ndef rotation_to_orientation(tracker_theta, axis_tilt=0, axis_azimuth=0, max_angle=90):\r\n # insert math from second half of tracking.singleaxis() here\r\n out = {'tracker_theta': tracker_theta, 'aoi': aoi,\r\n 'surface_tilt': surface_tilt, 'surface_azimuth': surface_azimuth}\r\n return pandas_if_needed(out)\r\n```\r\n\r\n**Describe alternatives you've considered**\r\nContinue suffering\r\n\r\n**Additional context**\r\nThis is one step towards a broader goal I have for `pvlib.tracking` to house other methods to determine tracker rotation in addition to the current astronomical method, the same way we have multiple temperature and transposition models. These functions would be responsible for determining tracker rotations, and they'd all use this `rotation_to_orientation` function to convert rotation to module orientation.\r\n\r\nSeparately, I wonder if the code could be simplified using the tilt and azimuth equations in Bill's technical report (https://www.nrel.gov/docs/fy13osti/58891.pdf) -- seems like what we're doing is overly complicated, although maybe I've just not studied it closely enough.\r\n\r\ncc @williamhobbs @spaneja \n", "hints_text": "I like this. \r\n\r\nThis is related to an issue submitted for NREL SAM, https://github.com/NREL/SAM/issues/850, and I think @mjprilliman is looking at something related. \n@kanderso-nrel Nice meeting you at PVSC the other day. I've been working on this a bit using the tilt and azimuth equations in the technical report by Bill Marion mentioned. I would like to use this for the custom backtracking schedules Nevados generates for the terrain following trackers. \r\n\r\nI have surface tilt working. It requires a dataframe `df` of axis tilt angles. I use the dataframe because Nevados has a different axis tilt for each bay in our tracker. stdf (surface tilt dataframe) starts as a dataframe of rotation angles (theta) indexed by timestep and is transformed into surface tilts. col.name is used to match the tracker and bay's rotation angle to their corresponding axis tilt.\r\n\r\n```\r\n def calc_surface_tilt(col):\r\n axis_tilt = df.at[col.name, 'axis_tilt']\r\n surface_tilt = np.rad2deg(\r\n np.arccos(\r\n np.cos(np.deg2rad(col)) * np.cos(np.deg2rad(axis_tilt))\r\n )\r\n )\r\n return surface_tilt\r\n\r\n stdf = stdf.apply(calc_surface_tilt, axis=0)\r\n```\r\n\r\nUnfortunately I can't seem to get surface azimuth working correctly. sadf (surface angle data frame) is almost equal to surface azimuth as calculated by pvlib, but not quite in the middle of the day. `ts2` is the output of `pvlib.tracking.singleaxis`\r\n\r\n\r\n```\r\n sadf = np.rad2deg(\r\n np.deg2rad(180) +\r\n np.arcsin(\r\n (\r\n np.sin(np.deg2rad(ts2['tracker_theta'])) /\r\n np.sin(np.deg2rad(ts2['surface_tilt']))\r\n ).clip(upper=1, lower=-1)\r\n )\r\n )\r\n```\r\n\r\n\r\n\r\n\r\n\r\n\nThanks @kurt-rhee for this investigation. Trying some simple examples on my end, things seem to line up. Here's a complete copy/pasteable example where I get negligible difference between the current pvlib approach and your code. Note that I did replace the hard-coded axis_azimuth of 180 in the surface_azimuth calculation. \r\n\r\n<details>\r\n <summary>Click to expand!</summary>\r\n\r\n```python\r\nimport pvlib\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\naxis_tilt = 20\r\naxis_azimuth = 230\r\nloc = pvlib.location.Location(40, -80)\r\ntimes = pd.date_range('2019-06-01', '2019-06-02', freq='5T', tz='Etc/GMT+5')\r\nsp = loc.get_solarposition(times)\r\ntr = pvlib.tracking.singleaxis(sp.apparent_zenith, sp.azimuth,\r\n axis_tilt=axis_tilt, axis_azimuth=axis_azimuth)\r\n\r\n\r\ndef rotation_to_orientation(tracker_theta, axis_tilt=0, axis_azimuth=0, max_angle=90):\r\n surface_tilt = np.rad2deg(\r\n np.arccos(\r\n np.cos(np.deg2rad(tracker_theta)) * np.cos(np.deg2rad(axis_tilt))\r\n )\r\n )\r\n surface_azimuth = np.rad2deg(\r\n np.deg2rad(axis_azimuth) +\r\n np.arcsin(\r\n (\r\n np.sin(np.deg2rad(tracker_theta)) /\r\n np.sin(np.deg2rad(surface_tilt))\r\n ).clip(upper=1, lower=-1)\r\n )\r\n )\r\n return pd.DataFrame({\r\n 'tracker_theta': tracker_theta,\r\n 'surface_tilt': surface_tilt,\r\n 'surface_azimuth': surface_azimuth,\r\n })\r\n\r\ntr2 = rotation_to_orientation(tr.tracker_theta, axis_tilt=axis_tilt, axis_azimuth=axis_azimuth)\r\n```\r\n\r\n</details>\r\n\r\n```python\r\nIn [53]: (tr[['surface_tilt', 'surface_azimuth']] - tr2[['surface_tilt', 'surface_azimuth']]).describe()\r\nOut[53]: \r\n surface_tilt surface_azimuth\r\ncount 1.780000e+02 1.780000e+02\r\nmean -6.586492e-16 3.193450e-15\r\nstd 8.916369e-15 2.864187e-14\r\nmin -2.842171e-14 -5.684342e-14\r\n25% -7.105427e-15 0.000000e+00\r\n50% 0.000000e+00 0.000000e+00\r\n75% 3.552714e-15 2.842171e-14\r\nmax 2.131628e-14 5.684342e-14\r\n```\nNot that there was much doubt, but I've convinced myself that Bill's surface orientation equations are mathematically equivalent to the approach pvlib takes. Here are some notes if anyone is interested: https://gist.github.com/kanderso-nrel/ac3051de41261df317180c794144d6a9\r\n\r\nIf we do switch to Bill's equations we should be sure to preserve the handling of NaN and edge cases of the current implementation.\nI realize that my small error metric is due to a small timeshift that I had in my data that changed my answer when resampling / averaging. \r\n\r\nCheers", "created_at": "2022-06-22T01:59:14Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_tracking.py::test_calc_surface_orientation_types", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_kwargs", "pvlib/tests/test_tracking.py::test_calc_surface_orientation_special"], "PASS_TO_PASS": ["pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_get_irradiance", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_calc_axis_tilt", "pvlib/tests/test_tracking.py::test_slope_aware_backtracking", "pvlib/tests/test_tracking.py::test_singleaxis_aoi_gh1221"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1682", "base_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91", "patch": "diff --git a/benchmarks/benchmarks/infinite_sheds.py b/benchmarks/benchmarks/infinite_sheds.py\n--- a/benchmarks/benchmarks/infinite_sheds.py\n+++ b/benchmarks/benchmarks/infinite_sheds.py\n@@ -10,7 +10,11 @@\n \n class InfiniteSheds:\n \n- def setup(self):\n+ # benchmark variant parameters (run both vectorize=True and False)\n+ params = [True, False]\n+ param_names = ['vectorize']\n+\n+ def setup(self, vectorize):\n self.times = pd.date_range(start='20180601', freq='1min',\n periods=1440)\n self.location = location.Location(40, -80)\n@@ -38,7 +42,7 @@ def setup(self):\n gcr=self.gcr\n )\n \n- def time_get_irradiance_poa_fixed(self):\n+ def time_get_irradiance_poa_fixed(self, vectorize):\n infinite_sheds.get_irradiance_poa(\n surface_tilt=self.surface_tilt,\n surface_azimuth=self.surface_azimuth,\n@@ -51,10 +55,11 @@ def time_get_irradiance_poa_fixed(self):\n dhi=self.clearsky_irradiance['dhi'],\n dni=self.clearsky_irradiance['dni'],\n albedo=self.albedo,\n- npoints=self.npoints\n+ npoints=self.npoints,\n+ vectorize=vectorize,\n )\n \n- def time_get_irradiance_poa_tracking(self):\n+ def time_get_irradiance_poa_tracking(self, vectorize):\n infinite_sheds.get_irradiance_poa(\n surface_tilt=self.tracking['surface_tilt'],\n surface_azimuth=self.tracking['surface_azimuth'],\n@@ -67,10 +72,11 @@ def time_get_irradiance_poa_tracking(self):\n dhi=self.clearsky_irradiance['dhi'],\n dni=self.clearsky_irradiance['dni'],\n albedo=self.albedo,\n- npoints=self.npoints\n+ npoints=self.npoints,\n+ vectorize=vectorize,\n )\n \n- def time_get_irradiance_fixed(self):\n+ def time_get_irradiance_fixed(self, vectorize):\n infinite_sheds.get_irradiance(\n surface_tilt=self.surface_tilt,\n surface_azimuth=self.surface_azimuth,\n@@ -83,10 +89,11 @@ def time_get_irradiance_fixed(self):\n dhi=self.clearsky_irradiance['dhi'],\n dni=self.clearsky_irradiance['dni'],\n albedo=self.albedo,\n- npoints=self.npoints\n+ npoints=self.npoints,\n+ vectorize=vectorize,\n )\n \n- def time_get_irradiance_tracking(self):\n+ def time_get_irradiance_tracking(self, vectorize):\n infinite_sheds.get_irradiance(\n surface_tilt=self.tracking['surface_tilt'],\n surface_azimuth=self.tracking['surface_azimuth'],\n@@ -99,5 +106,6 @@ def time_get_irradiance_tracking(self):\n dhi=self.clearsky_irradiance['dhi'],\n dni=self.clearsky_irradiance['dni'],\n albedo=self.albedo,\n- npoints=self.npoints\n+ npoints=self.npoints,\n+ vectorize=vectorize,\n )\ndiff --git a/pvlib/bifacial/infinite_sheds.py b/pvlib/bifacial/infinite_sheds.py\n--- a/pvlib/bifacial/infinite_sheds.py\n+++ b/pvlib/bifacial/infinite_sheds.py\n@@ -10,10 +10,10 @@\n from pvlib.irradiance import beam_component, aoi, haydavies\n \n def _vf_ground_sky_integ(surface_tilt, surface_azimuth, gcr, height,\n- pitch, max_rows=10, npoints=100):\n+ pitch, max_rows=10, npoints=100, vectorize=False):\n \"\"\"\n- Integrated and per-point view factors from the ground to the sky at points\n- between interior rows of the array.\n+ Integrated view factor to the sky from the ground underneath\n+ interior rows of the array.\n \n Parameters\n ----------\n@@ -35,20 +35,16 @@ def _vf_ground_sky_integ(surface_tilt, surface_azimuth, gcr, height,\n Maximum number of rows to consider in front and behind the current row.\n npoints : int, default 100\n Number of points used to discretize distance along the ground.\n+ vectorize : bool, default False\n+ If True, vectorize the view factor calculation across ``surface_tilt``.\n+ This increases speed with the cost of increased memory usage.\n \n Returns\n -------\n- fgnd_sky : float\n+ fgnd_sky : numeric\n Integration of view factor over the length between adjacent, interior\n- rows. [unitless]\n- fz : ndarray\n- Fraction of distance from the previous row to the next row. [unitless]\n- fz_sky : ndarray\n- View factors at discrete points between adjacent, interior rows.\n- [unitless]\n-\n+ rows. Shape matches that of ``surface_tilt``. [unitless]\n \"\"\"\n- # TODO: vectorize over surface_tilt\n # Abuse utils._vf_ground_sky_2d by supplying surface_tilt in place\n # of a signed rotation. This is OK because\n # 1) z span the full distance between 2 rows, and\n@@ -57,12 +53,16 @@ def _vf_ground_sky_integ(surface_tilt, surface_azimuth, gcr, height,\n # The VFs to the sky will thus be symmetric around z=0.5\n z = np.linspace(0, 1, npoints)\n rotation = np.atleast_1d(surface_tilt)\n- fz_sky = np.zeros((len(rotation), npoints))\n- for k, r in enumerate(rotation):\n- vf, _ = utils._vf_ground_sky_2d(z, r, gcr, pitch, height, max_rows)\n- fz_sky[k, :] = vf\n+ if vectorize:\n+ fz_sky = utils._vf_ground_sky_2d(z, rotation, gcr, pitch, height,\n+ max_rows)\n+ else:\n+ fz_sky = np.zeros((npoints, len(rotation)))\n+ for k, r in enumerate(rotation):\n+ vf = utils._vf_ground_sky_2d(z, r, gcr, pitch, height, max_rows)\n+ fz_sky[:, k] = vf[:, 0] # remove spurious rotation dimension\n # calculate the integrated view factor for all of the ground between rows\n- return np.trapz(fz_sky, z, axis=1)\n+ return np.trapz(fz_sky, z, axis=0)\n \n \n def _poa_ground_shadows(poa_ground, f_gnd_beam, df, vf_gnd_sky):\n@@ -401,7 +401,7 @@ def _shaded_fraction(solar_zenith, solar_azimuth, surface_tilt,\n def get_irradiance_poa(surface_tilt, surface_azimuth, solar_zenith,\n solar_azimuth, gcr, height, pitch, ghi, dhi, dni,\n albedo, model='isotropic', dni_extra=None, iam=1.0,\n- npoints=100):\n+ npoints=100, vectorize=False):\n r\"\"\"\n Calculate plane-of-array (POA) irradiance on one side of a row of modules.\n \n@@ -469,7 +469,12 @@ def get_irradiance_poa(surface_tilt, surface_azimuth, solar_zenith,\n on the surface that is not reflected away. [unitless]\n \n npoints : int, default 100\n- Number of points used to discretize distance along the ground.\n+ Number of discretization points for calculating integrated view\n+ factors.\n+\n+ vectorize : bool, default False\n+ If True, vectorize the view factor calculation across ``surface_tilt``.\n+ This increases speed with the cost of increased memory usage.\n \n Returns\n -------\n@@ -537,7 +542,8 @@ def get_irradiance_poa(surface_tilt, surface_azimuth, solar_zenith,\n # method differs from [1], Eq. 7 and Eq. 8; height is defined at row\n # center rather than at row lower edge as in [1].\n vf_gnd_sky = _vf_ground_sky_integ(\n- surface_tilt, surface_azimuth, gcr, height, pitch, max_rows, npoints)\n+ surface_tilt, surface_azimuth, gcr, height, pitch, max_rows, npoints,\n+ vectorize)\n # fraction of row slant height that is shaded from direct irradiance\n f_x = _shaded_fraction(solar_zenith, solar_azimuth, surface_tilt,\n surface_azimuth, gcr)\n@@ -610,7 +616,7 @@ def get_irradiance(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n gcr, height, pitch, ghi, dhi, dni,\n albedo, model='isotropic', dni_extra=None, iam_front=1.0,\n iam_back=1.0, bifaciality=0.8, shade_factor=-0.02,\n- transmission_factor=0, npoints=100):\n+ transmission_factor=0, npoints=100, vectorize=False):\n \"\"\"\n Get front and rear irradiance using the infinite sheds model.\n \n@@ -701,7 +707,12 @@ def get_irradiance(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n etc. A negative value is a reduction in back irradiance. [unitless]\n \n npoints : int, default 100\n- Number of points used to discretize distance along the ground.\n+ Number of discretization points for calculating integrated view\n+ factors.\n+\n+ vectorize : bool, default False\n+ If True, vectorize the view factor calculation across ``surface_tilt``.\n+ This increases speed with the cost of increased memory usage.\n \n Returns\n -------\n@@ -756,14 +767,14 @@ def get_irradiance(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n solar_zenith=solar_zenith, solar_azimuth=solar_azimuth,\n gcr=gcr, height=height, pitch=pitch, ghi=ghi, dhi=dhi, dni=dni,\n albedo=albedo, model=model, dni_extra=dni_extra, iam=iam_front,\n- npoints=npoints)\n+ npoints=npoints, vectorize=vectorize)\n # back side POA irradiance\n irrad_back = get_irradiance_poa(\n surface_tilt=backside_tilt, surface_azimuth=backside_sysaz,\n solar_zenith=solar_zenith, solar_azimuth=solar_azimuth,\n gcr=gcr, height=height, pitch=pitch, ghi=ghi, dhi=dhi, dni=dni,\n albedo=albedo, model=model, dni_extra=dni_extra, iam=iam_back,\n- npoints=npoints)\n+ npoints=npoints, vectorize=vectorize)\n \n colmap_front = {\n 'poa_global': 'poa_front',\ndiff --git a/pvlib/bifacial/utils.py b/pvlib/bifacial/utils.py\n--- a/pvlib/bifacial/utils.py\n+++ b/pvlib/bifacial/utils.py\n@@ -5,7 +5,6 @@\n import numpy as np\n from pvlib.tools import sind, cosd, tand\n \n-\n def _solar_projection_tangent(solar_zenith, solar_azimuth, surface_azimuth):\n \"\"\"\n Tangent of the angle between the zenith vector and the sun vector\n@@ -104,7 +103,7 @@ def _vf_ground_sky_2d(x, rotation, gcr, pitch, height, max_rows=10):\n Position on the ground between two rows, as a fraction of the pitch.\n x = 0 corresponds to the point on the ground directly below the\n center point of a row. Positive x is towards the right. [unitless]\n- rotation : float\n+ rotation : numeric\n Rotation angle of the row's right edge relative to row center.\n [degree]\n gcr : float\n@@ -120,30 +119,53 @@ def _vf_ground_sky_2d(x, rotation, gcr, pitch, height, max_rows=10):\n \n Returns\n -------\n- vf : numeric\n- Fraction of sky dome visible from each point on the ground. [unitless]\n- wedge_angles : array\n- Angles defining each wedge of sky that is blocked by a row. Shape is\n- (2, len(x), 2*max_rows+1). ``wedge_angles[0,:,:]`` is the\n- starting angle of each wedge, ``wedge_angles[1,:,:]`` is the end angle.\n- [degree]\n+ vf : array\n+ Fraction of sky dome visible from each point on the ground.\n+ Shape is (len(x), len(rotation)). [unitless]\n \"\"\"\n- x = np.atleast_1d(x) # handle float\n+ # This function creates large float64 arrays of size\n+ # (2*len(x)*len(rotation)*len(max_rows)) or ~100 MB for\n+ # typical time series inputs. This function makes heavy\n+ # use of numpy's out parameter to avoid allocating new\n+ # memory. Unfortunately that comes at the cost of some\n+ # readability: because arrays get reused to avoid new allocations,\n+ # variable names don't always match what they hold.\n+\n+ # handle floats:\n+ x = np.atleast_1d(x)[:, np.newaxis, np.newaxis]\n+ rotation = np.atleast_1d(rotation)[np.newaxis, :, np.newaxis]\n all_k = np.arange(-max_rows, max_rows + 1)\n width = gcr * pitch / 2.\n+ distance_to_row_centers = (all_k - x) * pitch\n+ dy = width * sind(rotation)\n+ dx = width * cosd(rotation)\n+\n+ phi = np.empty((2, x.shape[0], rotation.shape[1], len(all_k)))\n+\n # angles from x to right edge of each row\n- a1 = height + width * sind(rotation)\n- b1 = (all_k - x[:, np.newaxis]) * pitch + width * cosd(rotation)\n- phi_1 = np.degrees(np.arctan2(a1, b1))\n+ a1 = height + dy\n+ # temporarily store one leg of the triangle in phi:\n+ np.add(distance_to_row_centers, dx, out=phi[0])\n+ np.arctan2(a1, phi[0], out=phi[0])\n+\n # angles from x to left edge of each row\n- a2 = height - width * sind(rotation)\n- b2 = (all_k - x[:, np.newaxis]) * pitch - width * cosd(rotation)\n- phi_2 = np.degrees(np.arctan2(a2, b2))\n- phi = np.stack([phi_1, phi_2])\n- swap = phi[0, :, :] > phi[1, :, :]\n- # swap where phi_1 > phi_2 so that phi_1[0,:,:] is the lesser angle\n- phi = np.where(swap, phi[::-1], phi)\n- # right edge of next row - left edge of previous row\n- wedge_vfs = 0.5 * (cosd(phi[1, :, 1:]) - cosd(phi[0, :, :-1]))\n- vf = np.sum(np.where(wedge_vfs > 0, wedge_vfs, 0.), axis=1)\n- return vf, phi\n+ a2 = height - dy\n+ np.subtract(distance_to_row_centers, dx, out=phi[1])\n+ np.arctan2(a2, phi[1], out=phi[1])\n+\n+ # swap angles so that phi[0,:,:,:] is the lesser angle\n+ phi.sort(axis=0)\n+\n+ # now re-use phi's memory again, this time storing cos(phi).\n+ next_edge = phi[1, :, :, 1:]\n+ np.cos(next_edge, out=next_edge)\n+ prev_edge = phi[0, :, :, :-1]\n+ np.cos(prev_edge, out=prev_edge)\n+ # right edge of next row - left edge of previous row, again\n+ # reusing memory so that the difference is stored in next_edge.\n+ # Note that the 0.5 view factor coefficient is applied after summing\n+ # as a minor speed optimization.\n+ np.subtract(next_edge, prev_edge, out=next_edge)\n+ np.clip(next_edge, a_min=0., a_max=None, out=next_edge)\n+ vf = np.sum(next_edge, axis=-1) / 2\n+ return vf\n", "test_patch": "diff --git a/pvlib/tests/bifacial/test_infinite_sheds.py b/pvlib/tests/bifacial/test_infinite_sheds.py\n--- a/pvlib/tests/bifacial/test_infinite_sheds.py\n+++ b/pvlib/tests/bifacial/test_infinite_sheds.py\n@@ -42,7 +42,8 @@ def test_system():\n return syst, pts, vfs_ground_sky\n \n \n-def test__vf_ground_sky_integ(test_system):\[email protected](\"vectorize\", [True, False])\n+def test__vf_ground_sky_integ(test_system, vectorize):\n ts, pts, vfs_gnd_sky = test_system\n # pass rotation here since max_rows=1 for the hand-solved case in\n # the fixture test_system, which means the ground-to-sky view factor\n@@ -50,7 +51,7 @@ def test__vf_ground_sky_integ(test_system):\n vf_integ = infinite_sheds._vf_ground_sky_integ(\n ts['rotation'], ts['surface_azimuth'],\n ts['gcr'], ts['height'], ts['pitch'],\n- max_rows=1, npoints=3)\n+ max_rows=1, npoints=3, vectorize=vectorize)\n expected_vf_integ = np.trapz(vfs_gnd_sky, pts)\n assert np.isclose(vf_integ, expected_vf_integ, rtol=0.1)\n \n@@ -262,7 +263,8 @@ def test__backside_tilt():\n assert np.allclose(back_az, np.array([0., 330., 90., 180.]))\n \n \n-def test_get_irradiance():\[email protected](\"vectorize\", [True, False])\n+def test_get_irradiance(vectorize):\n # singleton inputs\n solar_zenith = 0.\n solar_azimuth = 180.\n@@ -282,7 +284,7 @@ def test_get_irradiance():\n surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n gcr, height, pitch, ghi, dhi, dni, albedo, iam_front, iam_back,\n bifaciality=0.8, shade_factor=-0.02, transmission_factor=0,\n- npoints=npoints)\n+ npoints=npoints, vectorize=vectorize)\n expected_front_diffuse = np.array([300.])\n expected_front_direct = np.array([700.])\n expected_front_global = expected_front_diffuse + expected_front_direct\n@@ -300,11 +302,11 @@ def test_get_irradiance():\n surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n gcr, height, pitch, ghi, dhi, dni, albedo, iam_front, iam_back,\n bifaciality=0.8, shade_factor=-0.02, transmission_factor=0,\n- npoints=npoints)\n+ npoints=npoints, vectorize=vectorize)\n result_front = infinite_sheds.get_irradiance_poa(\n surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,\n gcr, height, pitch, ghi, dhi, dni,\n- albedo, iam=iam_front)\n+ albedo, iam=iam_front, vectorize=vectorize)\n assert isinstance(result, pd.DataFrame)\n expected_poa_global = pd.Series(\n [1000., 500., result_front['poa_global'][2] * (1 + 0.8 * 0.98),\ndiff --git a/pvlib/tests/bifacial/test_utils.py b/pvlib/tests/bifacial/test_utils.py\n--- a/pvlib/tests/bifacial/test_utils.py\n+++ b/pvlib/tests/bifacial/test_utils.py\n@@ -35,7 +35,7 @@ def test_system_fixed_tilt():\n c22 = (-2 - sqr3) / np.sqrt(1.25**2 + (2 + sqr3)**2) # right edge row 0\n c23 = (0 - sqr3) / np.sqrt(1.25**2 + (0 - sqr3)**2) # right edge row 1\n vf_2 = 0.5 * (c23 - c22 + c21 - c20) # vf at point 1\n- vfs_ground_sky = np.array([vf_0, vf_1, vf_2])\n+ vfs_ground_sky = np.array([[vf_0], [vf_1], [vf_2]])\n return syst, pts, vfs_ground_sky\n \n \n@@ -79,10 +79,10 @@ def test__unshaded_ground_fraction(\n def test__vf_ground_sky_2d(test_system_fixed_tilt):\n # vector input\n ts, pts, vfs_gnd_sky = test_system_fixed_tilt\n- vfs, _ = utils._vf_ground_sky_2d(pts, ts['rotation'], ts['gcr'],\n- ts['pitch'], ts['height'], max_rows=1)\n+ vfs = utils._vf_ground_sky_2d(pts, ts['rotation'], ts['gcr'],\n+ ts['pitch'], ts['height'], max_rows=1)\n assert np.allclose(vfs, vfs_gnd_sky, rtol=0.1) # middle point vf is off\n # test with singleton x\n- vf, _ = utils._vf_ground_sky_2d(pts[0], ts['rotation'], ts['gcr'],\n- ts['pitch'], ts['height'], max_rows=1)\n+ vf = utils._vf_ground_sky_2d(pts[0], ts['rotation'], ts['gcr'],\n+ ts['pitch'], ts['height'], max_rows=1)\n assert np.isclose(vf, vfs_gnd_sky[0])\n", "problem_statement": "Infinite sheds perf improvement: vectorize over surface_tilt\nInfinite sheds is quite a bit slower than the modelchain POA modeling we use for frontside (as expected). I see a TODO comment in the code for _vf_ground_sky_integ (`_TODO: vectorize over surface_tilt_`) that could potentially result in some perf improvement for Infinite sheds calls with tracking systems.\n", "hints_text": "I haven't profiled it but I suspect you are right: [this line](https://github.com/pvlib/pvlib-python/blob/7bb30ad6e9d599d10510c7b37d95d56f14e846b4/pvlib/bifacial/infinite_sheds.py#L61) is the likely bottleneck.\n@wholmgren in #1627 you mentioned looking into optimizations for infinite sheds. I wonder if there is anything in the works?\r\n\r\nAlso here's a quick and dirty profile, for reference:\r\n\r\n\r\n\r\n```python\r\nimport pvlib\r\nimport pandas as pd\r\n\r\ntimes = pd.date_range('2019-01-01', '2019-02-01', freq='5T', tz='Etc/GMT+5')\r\nlocation = pvlib.location.Location(40, -80)\r\nsp = location.get_solarposition(times)\r\ncs = location.get_clearsky(times, solar_position=sp)\r\ntr = pvlib.tracking.singleaxis(sp.zenith, sp.azimuth)\r\n\r\ngcr = 0.5\r\nheight = 1.5\r\npitch = 3.0\r\nalbedo = 0.2\r\n\r\nresult = pvlib.bifacial.infinite_sheds.get_irradiance(\r\n surface_tilt=tr.surface_tilt, surface_azimuth=tr.surface_azimuth,\r\n solar_zenith=sp.zenith, solar_azimuth=sp.azimuth,\r\n gcr=0.5, height=1.5, pitch=3.0,\r\n ghi=cs.ghi, dhi=cs.dhi, dni=cs.dni, albedo=0.2\r\n)\r\n```\nI identified a few places with repeated calculations and started thinking about larger changes to mostly private functions that would avoid more repeated calculations. So all of that is largely complementary to vectorization.\nThis is a great conversation, thanks all for responding so quickly. Is there a timeline by which we could expect some of these perf changes to go in? Excited to use a faster Infinite Sheds. :)\nI tried out vectorizing over `surface_tilt` in `utils._vf_ground_sky_2d` and got a ~15-20% speed improvement for `infinite_sheds._vf_ground_sky_integ`. After those changes (and some minor unrelated optimizations), 80% of remaining runtime in `_vf_ground_sky_2d` is in the arctan and cosine calculations, so there might not be much room for additional improvement without changing how we do the math. I'll open a PR with some more formal benchmark results. \r\n\r\n@aturabi, separately from these code optimizations, you might take a look at reducing the `npoints` parameter. That parameter offers a trade-off between model resolution and speed, and I don't think we've done a real sensitivity analysis but I bet the default of 100 is overkill a lot of the time and you could get essentially the same simulation results faster with a lower (perhaps much lower) number. ", "created_at": "2023-03-03T00:30:38Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_ground_sky_integ[True]", "pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_ground_sky_integ[False]", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance[True]", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance[False]", "pvlib/tests/bifacial/test_utils.py::test__vf_ground_sky_2d"], "PASS_TO_PASS": ["pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_row_sky_integ", "pvlib/tests/bifacial/test_infinite_sheds.py::test__poa_sky_diffuse_pv", "pvlib/tests/bifacial/test_infinite_sheds.py::test__ground_angle", "pvlib/tests/bifacial/test_infinite_sheds.py::test__ground_angle_zero_gcr", "pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_row_ground", "pvlib/tests/bifacial/test_infinite_sheds.py::test__vf_row_ground_integ", "pvlib/tests/bifacial/test_infinite_sheds.py::test__poa_ground_shadows", "pvlib/tests/bifacial/test_infinite_sheds.py::test__shaded_fraction_floats", "pvlib/tests/bifacial/test_infinite_sheds.py::test__shaded_fraction_array", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_poa", "pvlib/tests/bifacial/test_infinite_sheds.py::test__backside_tilt", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_limiting_gcr", "pvlib/tests/bifacial/test_infinite_sheds.py::test_get_irradiance_with_haydavies", "pvlib/tests/bifacial/test_utils.py::test__solar_projection_tangent", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.5-0.0-180.0-0.0-180.0-0.5]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[1.0-0.0-180.0-0.0-180.0-0.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[1.0-90.0-180.0-0.0-180.0-1.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.5-45.0-180.0-45.0-270.0-0.6464466094067263]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.5-45.0-180.0-90.0-180.0-0.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-0-180-0.5]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-180-0.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-90-0.5]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-0-1.0]", "pvlib/tests/bifacial/test_utils.py::test__unshaded_ground_fraction[0.7071067811865476-45-180-45-135-0.1464466094067262]"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1832", "base_commit": "80edabe7b37ac798a9202b1424777c0cefbac0fe", "patch": "diff --git a/pvlib/iam.py b/pvlib/iam.py\n--- a/pvlib/iam.py\n+++ b/pvlib/iam.py\n@@ -20,7 +20,7 @@\n 'physical': {'n', 'K', 'L'},\n 'martin_ruiz': {'a_r'},\n 'sapm': {'B0', 'B1', 'B2', 'B3', 'B4', 'B5'},\n- 'interp': set()\n+ 'interp': {'theta_ref', 'iam_ref'}\n }\n \n \ndiff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -14,10 +14,9 @@\n from typing import Union, Tuple, Optional, TypeVar\n \n from pvlib import (atmosphere, clearsky, inverter, pvsystem, solarposition,\n- temperature)\n+ temperature, iam)\n import pvlib.irradiance # avoid name conflict with full import\n from pvlib.pvsystem import _DC_MODEL_PARAMS\n-from pvlib._deprecation import pvlibDeprecationWarning\n from pvlib.tools import _build_kwargs\n \n from pvlib._deprecation import deprecated\n@@ -279,7 +278,7 @@ def _mcr_repr(obj):\n # scalar, None, other?\n return repr(obj)\n \n- \n+\n # Type for fields that vary between arrays\n T = TypeVar('T')\n \n@@ -490,7 +489,7 @@ class ModelChain:\n If None, the model will be inferred from the parameters that\n are common to all of system.arrays[i].module_parameters.\n Valid strings are 'physical', 'ashrae', 'sapm', 'martin_ruiz',\n- 'no_loss'. The ModelChain instance will be passed as the\n+ 'interp' and 'no_loss'. The ModelChain instance will be passed as the\n first argument to a user-defined function.\n \n spectral_model: None, str, or function, default None\n@@ -917,6 +916,8 @@ def aoi_model(self, model):\n self._aoi_model = self.sapm_aoi_loss\n elif model == 'martin_ruiz':\n self._aoi_model = self.martin_ruiz_aoi_loss\n+ elif model == 'interp':\n+ self._aoi_model = self.interp_aoi_loss\n elif model == 'no_loss':\n self._aoi_model = self.no_aoi_loss\n else:\n@@ -928,22 +929,24 @@ def infer_aoi_model(self):\n module_parameters = tuple(\n array.module_parameters for array in self.system.arrays)\n params = _common_keys(module_parameters)\n- if {'K', 'L', 'n'} <= params:\n+ if iam._IAM_MODEL_PARAMS['physical'] <= params:\n return self.physical_aoi_loss\n- elif {'B5', 'B4', 'B3', 'B2', 'B1', 'B0'} <= params:\n+ elif iam._IAM_MODEL_PARAMS['sapm'] <= params:\n return self.sapm_aoi_loss\n- elif {'b'} <= params:\n+ elif iam._IAM_MODEL_PARAMS['ashrae'] <= params:\n return self.ashrae_aoi_loss\n- elif {'a_r'} <= params:\n+ elif iam._IAM_MODEL_PARAMS['martin_ruiz'] <= params:\n return self.martin_ruiz_aoi_loss\n+ elif iam._IAM_MODEL_PARAMS['interp'] <= params:\n+ return self.interp_aoi_loss\n else:\n raise ValueError('could not infer AOI model from '\n 'system.arrays[i].module_parameters. Check that '\n 'the module_parameters for all Arrays in '\n- 'system.arrays contain parameters for '\n- 'the physical, aoi, ashrae or martin_ruiz model; '\n- 'explicitly set the model with the aoi_model '\n- 'kwarg; or set aoi_model=\"no_loss\".')\n+ 'system.arrays contain parameters for the '\n+ 'physical, aoi, ashrae, martin_ruiz or interp '\n+ 'model; explicitly set the model with the '\n+ 'aoi_model kwarg; or set aoi_model=\"no_loss\".')\n \n def ashrae_aoi_loss(self):\n self.results.aoi_modifier = self.system.get_iam(\n@@ -972,6 +975,13 @@ def martin_ruiz_aoi_loss(self):\n )\n return self\n \n+ def interp_aoi_loss(self):\n+ self.results.aoi_modifier = self.system.get_iam(\n+ self.results.aoi,\n+ iam_model='interp'\n+ )\n+ return self\n+\n def no_aoi_loss(self):\n if self.system.num_arrays == 1:\n self.results.aoi_modifier = 1.0\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -8,6 +8,7 @@\n import io\n import itertools\n import os\n+import inspect\n from urllib.request import urlopen\n import numpy as np\n from scipy import constants\n@@ -388,7 +389,7 @@ def get_iam(self, aoi, iam_model='physical'):\n \n aoi_model : string, default 'physical'\n The IAM model to be used. Valid strings are 'physical', 'ashrae',\n- 'martin_ruiz' and 'sapm'.\n+ 'martin_ruiz', 'sapm' and 'interp'.\n Returns\n -------\n iam : numeric or tuple of numeric\n@@ -1151,7 +1152,7 @@ def get_iam(self, aoi, iam_model='physical'):\n \n aoi_model : string, default 'physical'\n The IAM model to be used. Valid strings are 'physical', 'ashrae',\n- 'martin_ruiz' and 'sapm'.\n+ 'martin_ruiz', 'sapm' and 'interp'.\n \n Returns\n -------\n@@ -1164,16 +1165,16 @@ def get_iam(self, aoi, iam_model='physical'):\n if `iam_model` is not a valid model name.\n \"\"\"\n model = iam_model.lower()\n- if model in ['ashrae', 'physical', 'martin_ruiz']:\n- param_names = iam._IAM_MODEL_PARAMS[model]\n- kwargs = _build_kwargs(param_names, self.module_parameters)\n- func = getattr(iam, model)\n+ if model in ['ashrae', 'physical', 'martin_ruiz', 'interp']:\n+ func = getattr(iam, model) # get function at pvlib.iam\n+ # get all parameters from function signature to retrieve them from\n+ # module_parameters if present\n+ params = set(inspect.signature(func).parameters.keys())\n+ params.discard('aoi') # exclude aoi so it can't be repeated\n+ kwargs = _build_kwargs(params, self.module_parameters)\n return func(aoi, **kwargs)\n elif model == 'sapm':\n return iam.sapm(aoi, self.module_parameters)\n- elif model == 'interp':\n- raise ValueError(model + ' is not implemented as an IAM model '\n- 'option for Array')\n else:\n raise ValueError(model + ' is not a valid IAM model')\n \n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -1455,6 +1455,27 @@ def test_aoi_model_no_loss(sapm_dc_snl_ac_system, location, weather):\n assert mc.results.ac[1] < 1\n \n \n+def test_aoi_model_interp(sapm_dc_snl_ac_system, location, weather, mocker):\n+ # similar to test_aoi_models but requires arguments to work, so we\n+ # add 'interp' aoi losses model arguments to module\n+ iam_ref = (1., 0.85)\n+ theta_ref = (0., 80.)\n+ sapm_dc_snl_ac_system.arrays[0].module_parameters['iam_ref'] = iam_ref\n+ sapm_dc_snl_ac_system.arrays[0].module_parameters['theta_ref'] = theta_ref\n+ mc = ModelChain(sapm_dc_snl_ac_system, location,\n+ dc_model='sapm', aoi_model='interp',\n+ spectral_model='no_loss')\n+ m = mocker.spy(iam, 'interp')\n+ mc.run_model(weather=weather)\n+ # only test kwargs\n+ assert m.call_args[1]['iam_ref'] == iam_ref\n+ assert m.call_args[1]['theta_ref'] == theta_ref\n+ assert isinstance(mc.results.ac, pd.Series)\n+ assert not mc.results.ac.empty\n+ assert mc.results.ac[0] > 150 and mc.results.ac[0] < 200\n+ assert mc.results.ac[1] < 1\n+\n+\n def test_aoi_model_user_func(sapm_dc_snl_ac_system, location, weather, mocker):\n m = mocker.spy(sys.modules[__name__], 'constant_aoi_loss')\n mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm',\n@@ -1468,7 +1489,7 @@ def test_aoi_model_user_func(sapm_dc_snl_ac_system, location, weather, mocker):\n \n \n @pytest.mark.parametrize('aoi_model', [\n- 'sapm', 'ashrae', 'physical', 'martin_ruiz'\n+ 'sapm', 'ashrae', 'physical', 'martin_ruiz', 'interp'\n ])\n def test_infer_aoi_model(location, system_no_aoi, aoi_model):\n for k in iam._IAM_MODEL_PARAMS[aoi_model]:\n@@ -1477,6 +1498,26 @@ def test_infer_aoi_model(location, system_no_aoi, aoi_model):\n assert isinstance(mc, ModelChain)\n \n \[email protected]('aoi_model,model_kwargs', [\n+ # model_kwargs has both required and optional kwargs; test all\n+ ('physical',\n+ {'n': 1.526, 'K': 4.0, 'L': 0.002, # required\n+ 'n_ar': 1.8}), # extra\n+ ('interp',\n+ {'theta_ref': (0, 75, 85, 90), 'iam_ref': (1, 0.8, 0.42, 0), # required\n+ 'method': 'cubic', 'normalize': False})]) # extra\n+def test_infer_aoi_model_with_extra_params(location, system_no_aoi, aoi_model,\n+ model_kwargs, weather, mocker):\n+ # test extra parameters not defined at iam._IAM_MODEL_PARAMS are passed\n+ m = mocker.spy(iam, aoi_model)\n+ system_no_aoi.arrays[0].module_parameters.update(**model_kwargs)\n+ mc = ModelChain(system_no_aoi, location, spectral_model='no_loss')\n+ assert isinstance(mc, ModelChain)\n+ mc.run_model(weather=weather)\n+ _, call_kwargs = m.call_args\n+ assert call_kwargs == model_kwargs\n+\n+\n def test_infer_aoi_model_invalid(location, system_no_aoi):\n exc_text = 'could not infer AOI model'\n with pytest.raises(ValueError, match=exc_text):\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -64,10 +64,15 @@ def test_PVSystem_get_iam_sapm(sapm_module_params, mocker):\n assert_allclose(out, 1.0, atol=0.01)\n \n \n-def test_PVSystem_get_iam_interp(sapm_module_params, mocker):\n- system = pvsystem.PVSystem(module_parameters=sapm_module_params)\n- with pytest.raises(ValueError):\n- system.get_iam(45, iam_model='interp')\n+def test_PVSystem_get_iam_interp(mocker):\n+ interp_module_params = {'iam_ref': (1., 0.8), 'theta_ref': (0., 80.)}\n+ system = pvsystem.PVSystem(module_parameters=interp_module_params)\n+ spy = mocker.spy(_iam, 'interp')\n+ aoi = ((0., 40., 80.),)\n+ expected = (1., 0.9, 0.8)\n+ out = system.get_iam(aoi, iam_model='interp')\n+ assert_allclose(out, expected)\n+ spy.assert_called_once_with(aoi[0], **interp_module_params)\n \n \n def test__normalize_sam_product_names():\n", "problem_statement": "Add interp method for modelchain aoi model.\nI would like to simulate the effect of different IAM functions on performance. Pvlib already has an `interp` method for the iam_loss function. However, it is not possible to use `interp` within model chain. Can we add this feature?\n", "hints_text": "", "created_at": "2023-08-12T17:27:43Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_aoi_model_interp", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[interp]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_with_extra_params[physical-model_kwargs0]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_with_extra_params[interp-model_kwargs1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_albedo_in_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_albedo_in_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_noct_sam_temp", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_len1_weather_tuple", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params4-noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_dc_model_incomplete", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_ohms_from_percent", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_no_dc_ohmic_loss", "pvlib/tests/test_modelchain.py::test_dc_ohmic_ext_def", "pvlib/tests/test_modelchain.py::test_dc_ohmic_not_a_model", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__", "pvlib/tests/test_modelchain.py::test_ModelChainResult___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss_deprecated", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_recombination", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[lambertw]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[brentq]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[newton]", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_Array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1089", "base_commit": "d5d1d66aae4913f0e23b9a79c655efa1bdafe5f4", "patch": "diff --git a/pvlib/ivtools/sdm.py b/pvlib/ivtools/sdm.py\n--- a/pvlib/ivtools/sdm.py\n+++ b/pvlib/ivtools/sdm.py\n@@ -979,7 +979,8 @@ def _filter_params(ee, isc, io, rs, rsh):\n negrs = rs < 0.\n badrs = np.logical_or(rs > rsh, np.isnan(rs))\n imagrs = ~(np.isreal(rs))\n- badio = np.logical_or(~(np.isreal(rs)), io <= 0)\n+ badio = np.logical_or(np.logical_or(~(np.isreal(rs)), io <= 0),\n+ np.isnan(io))\n goodr = np.logical_and(~badrsh, ~imagrs)\n goodr = np.logical_and(goodr, ~negrs)\n goodr = np.logical_and(goodr, ~badrs)\ndiff --git a/pvlib/tools.py b/pvlib/tools.py\n--- a/pvlib/tools.py\n+++ b/pvlib/tools.py\n@@ -277,51 +277,61 @@ def _build_args(keys, input_dict, dict_name):\n \n # Created April,2014\n # Author: Rob Andrews, Calama Consulting\n-\n-def _golden_sect_DataFrame(params, VL, VH, func):\n+# Modified: November, 2020 by C. W. Hansen, to add atol and change exit\n+# criteria\n+def _golden_sect_DataFrame(params, lower, upper, func, atol=1e-8):\n \"\"\"\n- Vectorized golden section search for finding MPP from a dataframe\n- timeseries.\n+ Vectorized golden section search for finding maximum of a function of a\n+ single variable.\n \n Parameters\n ----------\n- params : dict\n- Dictionary containing scalars or arrays\n- of inputs to the function to be optimized.\n- Each row should represent an independent optimization.\n+ params : dict or Dataframe\n+ Parameters to be passed to `func`.\n \n- VL: float\n- Lower bound of the optimization\n+ lower: numeric\n+ Lower bound for the optimization\n \n- VH: float\n- Upper bound of the optimization\n+ upper: numeric\n+ Upper bound for the optimization\n \n func: function\n- Function to be optimized must be in the form f(array-like, x)\n+ Function to be optimized. Must be in the form\n+ result = f(dict or DataFrame, str), where result is a dict or DataFrame\n+ that also contains the function output, and str is the key\n+ corresponding to the function's input variable.\n \n Returns\n -------\n- func(df,'V1') : DataFrame\n- function evaluated at the optimal point\n+ numeric\n+ function evaluated at the optimal points\n \n- df['V1']: Dataframe\n- Dataframe of optimal points\n+ numeric\n+ optimal points\n \n Notes\n -----\n- This function will find the MAXIMUM of a function\n+ This function will find the points where the function is maximized.\n+\n+ See also\n+ --------\n+ pvlib.singlediode._pwr_optfcn\n \"\"\"\n \n+ phim1 = (np.sqrt(5) - 1) / 2\n+\n df = params\n- df['VH'] = VH\n- df['VL'] = VL\n+ df['VH'] = upper\n+ df['VL'] = lower\n \n- errflag = True\n+ converged = False\n iterations = 0\n+ iterlimit = 1 + np.max(\n+ np.trunc(np.log(atol / (df['VH'] - df['VL'])) / np.log(phim1)))\n \n- while errflag:\n+ while not converged and (iterations < iterlimit):\n \n- phi = (np.sqrt(5)-1)/2*(df['VH']-df['VL'])\n+ phi = phim1 * (df['VH'] - df['VL'])\n df['V1'] = df['VL'] + phi\n df['V2'] = df['VH'] - phi\n \n@@ -332,15 +342,15 @@ def _golden_sect_DataFrame(params, VL, VH, func):\n df['VL'] = df['V2']*df['SW_Flag'] + df['VL']*(~df['SW_Flag'])\n df['VH'] = df['V1']*~df['SW_Flag'] + df['VH']*(df['SW_Flag'])\n \n- err = df['V1'] - df['V2']\n- try:\n- errflag = (abs(err) > .01).any()\n- except ValueError:\n- errflag = (abs(err) > .01)\n+ err = abs(df['V2'] - df['V1'])\n \n+ # works with single value because err is np.float64\n+ converged = (err < atol).all()\n+ # err will be less than atol before iterations hit the limit\n+ # but just to be safe\n iterations += 1\n \n- if iterations > 50:\n- raise Exception(\"EXCEPTION:iterations exceeded maximum (50)\")\n+ if iterations > iterlimit:\n+ raise Exception(\"iterations exceeded maximum\") # pragma: no cover\n \n return func(df, 'V1'), df['V1']\n", "test_patch": "diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -1313,32 +1313,35 @@ def test_singlediode_array():\n resistance_series, resistance_shunt, nNsVth,\n method='lambertw')\n \n- expected = np.array([\n- 0. , 0.54538398, 1.43273966, 2.36328163, 3.29255606,\n- 4.23101358, 5.16177031, 6.09368251, 7.02197553, 7.96846051,\n- 8.88220557])\n-\n- assert_allclose(sd['i_mp'], expected, atol=0.01)\n+ expected_i = np.array([\n+ 0., 0.54614798740338, 1.435026463529, 2.3621366610078, 3.2953968319952,\n+ 4.2303869378787, 5.1655276691892, 6.1000269648604, 7.0333996177802,\n+ 7.9653036915959, 8.8954716265647])\n+ expected_v = np.array([\n+ 0., 7.0966259059555, 7.9961986643428, 8.2222496810656, 8.3255927555753,\n+ 8.3766915453915, 8.3988872440242, 8.4027948807891, 8.3941399580559,\n+ 8.3763655188855, 8.3517057522791])\n+\n+ assert_allclose(sd['i_mp'], expected_i, atol=1e-8)\n+ assert_allclose(sd['v_mp'], expected_v, atol=1e-8)\n \n sd = pvsystem.singlediode(photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth)\n-\n expected = pvsystem.i_from_v(resistance_shunt, resistance_series, nNsVth,\n sd['v_mp'], saturation_current, photocurrent,\n method='lambertw')\n-\n- assert_allclose(sd['i_mp'], expected, atol=0.01)\n+ assert_allclose(sd['i_mp'], expected, atol=1e-8)\n \n \n def test_singlediode_floats():\n- out = pvsystem.singlediode(7, 6e-7, .1, 20, .5, method='lambertw')\n- expected = {'i_xx': 4.2498,\n- 'i_mp': 6.1275,\n- 'v_oc': 8.1063,\n- 'p_mp': 38.1937,\n- 'i_x': 6.7558,\n- 'i_sc': 6.9651,\n- 'v_mp': 6.2331,\n+ out = pvsystem.singlediode(7., 6.e-7, .1, 20., .5, method='lambertw')\n+ expected = {'i_xx': 4.264060478,\n+ 'i_mp': 6.136267360,\n+ 'v_oc': 8.106300147,\n+ 'p_mp': 38.19421055,\n+ 'i_x': 6.7558815684,\n+ 'i_sc': 6.965172322,\n+ 'v_mp': 6.224339375,\n 'i': None,\n 'v': None}\n assert isinstance(out, dict)\n@@ -1346,23 +1349,26 @@ def test_singlediode_floats():\n if k in ['i', 'v']:\n assert v is None\n else:\n- assert_allclose(v, expected[k], atol=1e-3)\n+ assert_allclose(v, expected[k], atol=1e-6)\n \n \n def test_singlediode_floats_ivcurve():\n- out = pvsystem.singlediode(7, 6e-7, .1, 20, .5, ivcurve_pnts=3, method='lambertw')\n- expected = {'i_xx': 4.2498,\n- 'i_mp': 6.1275,\n- 'v_oc': 8.1063,\n- 'p_mp': 38.1937,\n- 'i_x': 6.7558,\n- 'i_sc': 6.9651,\n- 'v_mp': 6.2331,\n- 'i': np.array([6.965172e+00, 6.755882e+00, 2.575717e-14]),\n- 'v': np.array([0., 4.05315, 8.1063])}\n+ out = pvsystem.singlediode(7., 6e-7, .1, 20., .5, ivcurve_pnts=3,\n+ method='lambertw')\n+ expected = {'i_xx': 4.264060478,\n+ 'i_mp': 6.136267360,\n+ 'v_oc': 8.106300147,\n+ 'p_mp': 38.19421055,\n+ 'i_x': 6.7558815684,\n+ 'i_sc': 6.965172322,\n+ 'v_mp': 6.224339375,\n+ 'i': np.array([\n+ 6.965172322, 6.755881568, 2.664535259e-14]),\n+ 'v': np.array([\n+ 0., 4.053150073, 8.106300147])}\n assert isinstance(out, dict)\n for k, v in out.items():\n- assert_allclose(v, expected[k], atol=1e-3)\n+ assert_allclose(v, expected[k], atol=1e-6)\n \n \n def test_singlediode_series_ivcurve(cec_module_params):\n@@ -1383,21 +1389,20 @@ def test_singlediode_series_ivcurve(cec_module_params):\n out = pvsystem.singlediode(IL, I0, Rs, Rsh, nNsVth, ivcurve_pnts=3,\n method='lambertw')\n \n- expected = OrderedDict([('i_sc', array([0., 3.01054475, 6.00675648])),\n- ('v_oc', array([0., 9.96886962, 10.29530483])),\n- ('i_mp', array([0., 2.65191983, 5.28594672])),\n- ('v_mp', array([0., 8.33392491, 8.4159707])),\n- ('p_mp', array([0., 22.10090078, 44.48637274])),\n- ('i_x', array([0., 2.88414114, 5.74622046])),\n- ('i_xx', array([0., 2.04340914, 3.90007956])),\n+ expected = OrderedDict([('i_sc', array([0., 3.01079860, 6.00726296])),\n+ ('v_oc', array([0., 9.96959733, 10.29603253])),\n+ ('i_mp', array([0., 2.656285960, 5.290525645])),\n+ ('v_mp', array([0., 8.321092255, 8.409413795])),\n+ ('p_mp', array([0., 22.10320053, 44.49021934])),\n+ ('i_x', array([0., 2.884132006, 5.746202281])),\n+ ('i_xx', array([0., 2.052691562, 3.909673879])),\n ('v', array([[0., 0., 0.],\n- [0., 4.98443481, 9.96886962],\n- [0., 5.14765242, 10.29530483]])),\n+ [0., 4.984798663, 9.969597327],\n+ [0., 5.148016266, 10.29603253]])),\n ('i', array([[0., 0., 0.],\n- [3.01079860e+00, 2.88414114e+00,\n- 3.10862447e-14],\n- [6.00726296e+00, 5.74622046e+00,\n- 0.00000000e+00]]))])\n+ [3.0107985972, 2.8841320056, 0.],\n+ [6.0072629615, 5.7462022810, 0.]]))])\n+\n \n for k, v in out.items():\n assert_allclose(v, expected[k], atol=1e-2)\n@@ -1414,7 +1419,7 @@ def test_singlediode_series_ivcurve(cec_module_params):\n method='lambertw').T\n \n for k, v in out.items():\n- assert_allclose(v, expected[k], atol=1e-2)\n+ assert_allclose(v, expected[k], atol=1e-6)\n \n \n def test_scale_voltage_current_power():\ndiff --git a/pvlib/tests/test_tools.py b/pvlib/tests/test_tools.py\n--- a/pvlib/tests/test_tools.py\n+++ b/pvlib/tests/test_tools.py\n@@ -1,6 +1,7 @@\n import pytest\n \n from pvlib import tools\n+import numpy as np\n \n \n @pytest.mark.parametrize('keys, input_dict, expected', [\n@@ -12,3 +13,35 @@\n def test_build_kwargs(keys, input_dict, expected):\n kwargs = tools._build_kwargs(keys, input_dict)\n assert kwargs == expected\n+\n+\n+def _obj_test_golden_sect(params, loc):\n+ return params[loc] * (1. - params['c'] * params[loc]**params['n'])\n+\n+\[email protected]('params, lb, ub, expected, func', [\n+ ({'c': 1., 'n': 1.}, 0., 1., 0.5, _obj_test_golden_sect),\n+ ({'c': 1e6, 'n': 6.}, 0., 1., 0.07230200263994839, _obj_test_golden_sect),\n+ ({'c': 0.2, 'n': 0.3}, 0., 100., 89.14332727531685, _obj_test_golden_sect)\n+])\n+def test__golden_sect_DataFrame(params, lb, ub, expected, func):\n+ v, x = tools._golden_sect_DataFrame(params, lb, ub, func)\n+ assert np.isclose(x, expected, atol=1e-8)\n+\n+\n+def test__golden_sect_DataFrame_atol():\n+ params = {'c': 0.2, 'n': 0.3}\n+ expected = 89.14332727531685\n+ v, x = tools._golden_sect_DataFrame(\n+ params, 0., 100., _obj_test_golden_sect, atol=1e-12)\n+ assert np.isclose(x, expected, atol=1e-12)\n+\n+\n+def test__golden_sect_DataFrame_vector():\n+ params = {'c': np.array([1., 2.]), 'n': np.array([1., 1.])}\n+ lower = np.array([0., 0.001])\n+ upper = np.array([1.1, 1.2])\n+ expected = np.array([0.5, 0.25])\n+ v, x = tools._golden_sect_DataFrame(params, lower, upper,\n+ _obj_test_golden_sect)\n+ assert np.allclose(x, expected, atol=1e-8)\n", "problem_statement": "Apparent numerical instability in I_mp calculation using PVsyst model\n**Describe the bug**\r\n\r\nI used these parameters in `pvlib.pvsystem.calcparams_pvsyst()` in order to calculate `I_mp` vs. `T` using `pvlib.pvsystem.singlediode()` with `effective_irradiance` fixed at 1000 W/m^2 and `temp_cell` having 1001 values ranging from 15 to 50 degC:\r\n\r\n`{'alpha_sc': 0.006, 'gamma_ref': 1.009, 'mu_gamma': -0.0005, 'I_L_ref': 13.429, 'I_o_ref': 3.719506010004821e-11, 'R_sh_ref': 800.0, 'R_sh_0': 3200.0, 'R_s': 0.187, 'cells_in_series': 72, 'R_sh_exp': 5.5, 'EgRef': 1.121, 'irrad_ref': 1000, 'temp_ref': 25}`\r\n\r\nMy purpose was to investigate the temperature coefficient of `I_mp`, and I got the following result, which appears to suffer from a numeric instability:\r\n\r\n\r\n\r\nFor comparison, the corresponding `V_mp` vs. `T` plot:\r\n\r\n\r\n\r\n**To Reproduce**\r\n\r\nRun the above calculations using the parameters provided.\r\n\r\n**Expected behavior**\r\n\r\nBetter numerical stability in `I_mp` vs. `T`.\r\n\r\n**Screenshots**\r\n\r\nSee above.\r\n\r\n**Versions:**\r\n\r\n - ``pvlib.__version__``: 0.8.0\r\n - ``numpy.__version__``: 1.19.2\r\n - ``scipy.__version__``: 1.5.2\r\n - ``pandas.__version__``: 1.1.3\r\n - python: 3.8.5\r\n\r\n**Additional context**\r\n\r\nI was going to attempt a numerical computation of the temperature coefficient of `I_mp` for a model translation to the SAPM. I have seen reports from CFV in which this coefficient is actually negative, and I have computed it alternately using the `P_mp` and `V_mp` temperature coefficients, and gotten a negative value for this particular PV module. Despite the apparent numerical instability in the above plot, it still suggests that the coefficient should be positive, not negative. Perhaps I am missing something here?\r\n\r\nAlso, I have not dug deep enough to figure out if the underlying issue is in `pvlib.pvsystem.singlediode()`.\n", "hints_text": "Confirmed. Looks like it's a lack of convergence in `pvlib.singlediode._lambertw`. Some time ago a similar issue was reported for PVLib Matlab, I think we bumped up the iteration count to fix it.\r\n\r\nIf you set `pvlib.singlediode(..., method='brentq',...)` the noise smooths away.\n@cwhanse Thanks. `method='brentq'` fixed the issue for me too. :)\r\n\r\nSince you're from Sandia, do have any insight about a \"typical\" sign of the T-coef for `I_mp` in the SAPM? It seems like the sign is positive for the PVsyst model and negative for the SAPM (~both~ in SOME CFV reports ~and by taking the derivative of `P_mp` = `I_mp` * `V_mp` w.r.t. `T` and solving for `dI_mp/ dT`~).\r\n\r\nUPDATE: With the `I_mp` calculation correction, it appears that I get a consistent + sign for the `I_mp` temperature coefficient in both computational methods. However, I do see this reported as a negative value in some places.\nI don't know that theory predicts a sign for this temperature coefficient.\r\n\r\nFor SAPM, when Sandia fits this model using outdoor measurements, a value is determined by fitting a line to Imp vs. cell temperature (backed out of Isc, Voc values). I've argued that given the resolution of measurements, the technique for determining cell temperature and maximum power point, and the regression method, that the value is usually statistically indistinguishable from zero.\r\n\r\nFor CFV-produced Pvsyst parameters, my guess is that CFV is determining alpha_imp by fitting a line to the Imp vs. cell temperature data (IEC61853 matrix test results using an indoor flasher with temperature variation control), which is the same method used by Sandia for the SAPM. Happy to connect you with CFV and you can ask them.\nThanks for sharing your understanding @cwhanse. I think I will have a convo with Daniel C. Zirzow at CFV at some point in the near future.\r\n\r\nShould I close this issue, or should it become a PR to change defaults to better ensure convergence?\nLeave it open, there's a pvlib issue to be addressed.\r\n\r\nI tracked down the source of the oscillatory behavior to [this line](https://github.com/pvlib/pvlib-python/blob/3e25627e34bfd5aadea041da85a30626322b3a99/pvlib/singlediode.py#L611). \r\n\r\n```\r\n argW = Rs[idx_p] * I0[idx_p] / (\r\n a[idx_p] * (Rs[idx_p] * Gsh[idx_p] + 1.)) * \\\r\n np.exp((Rs[idx_p] * (IL[idx_p] + I0[idx_p]) + V[idx_p]) /\r\n (a[idx_p] * (Rs[idx_p] * Gsh[idx_p] + 1.)))\r\n```\r\n\r\nIt's a product of two terms:\r\nconstant factor : Rs * I0 / (a (Rs Gsh + 1)) which is very small (~1E-10) and\r\nexponential factor: np.exp( (Rs * (IL + I0) + V) / (a * (Rs * Gsh + 1)) ) which is quite large (~1E+10), since the argument is ~20.\r\n\r\nThe constant factor increases smoothly with cell temperature, as expected. \r\n\r\nThe argument of the exponential term decreases with temperature but not smoothly. The cause seems to be that Vmp (`V` in that line of code) decreases but not smoothly. Vmp is calculated using `pvlib.tools._golden_sect_DataFrame`. I suspect the convergence of this root finder is the culprit.\r\n\n@cwhanse An incidental colleague of mine (Ken Roberts) figured out a way around the numerical convergence issues with using the LambertW function for solving the single diode equation. I have never had the time to do it full justice in code (I use simple newton in PVfit), but this \"Log Wright Omega\" function might be worth looking into for pvlib. Here are some references he shared with me. He was so pleasant to work with and I found his exposition very approachable.\r\n\r\n- https://arxiv.org/pdf/1504.01964.pdf\r\n- https://www.researchgate.net/publication/305991463", "created_at": "2020-11-16T23:21:16Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params0-0.0-1.0-0.5-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params1-0.0-1.0-0.07230200263994839-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params2-0.0-100.0-89.14332727531685-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_atol", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_vector"], "PASS_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[module_type]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[temperature_model_parameters]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[albedo]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_tilt]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[surface_azimuth]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[racking_model]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[modules_per_string]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_attributes[strings_per_inverter]", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_temperature_deprecated[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]", "pvlib/tests/test_tools.py::test_build_kwargs[keys0-input_dict0-expected0]", "pvlib/tests/test_tools.py::test_build_kwargs[keys1-input_dict1-expected1]", "pvlib/tests/test_tools.py::test_build_kwargs[keys2-input_dict2-expected2]", "pvlib/tests/test_tools.py::test_build_kwargs[keys3-input_dict3-expected3]"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1033", "base_commit": "a7edb8b582174ed45f2d3859f29261908f5e0ab5", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -179,7 +179,7 @@ def basic_chain(times, latitude, longitude,\n linke_turbidity,\n altitude=altitude,\n dni_extra=dni_extra\n- )\n+ )\n \n total_irrad = pvlib.irradiance.get_total_irradiance(\n surface_tilt,\n@@ -346,24 +346,6 @@ def __init__(self, system, location,\n self.ac_model = ac_model\n self.aoi_model = aoi_model\n self.spectral_model = spectral_model\n-\n- # TODO: deprecated kwarg temp_model. Remove use of temp_model in v0.8\n- temp_model = kwargs.pop('temp_model', None)\n- if temp_model is not None:\n- if temperature_model is None:\n- warnings.warn('The temp_model keyword argument is deprecated.'\n- ' Use temperature_model instead',\n- pvlibDeprecationWarning)\n- temperature_model = temp_model\n- elif temp_model == temperature_model:\n- warnings.warn('Provide only one of temperature_model or '\n- 'temp_model (deprecated).',\n- pvlibDeprecationWarning)\n- else:\n- raise ValueError(\n- 'Conflicting temperature_model {} and temp_model {}. '\n- 'temp_model is deprecated. Specify only temperature_model.'\n- .format(temperature_model, temp_model))\n self.temperature_model = temperature_model\n \n self.losses_model = losses_model\n@@ -544,7 +526,7 @@ def __repr__(self):\n 'transposition_model', 'solar_position_method',\n 'airmass_model', 'dc_model', 'ac_model', 'aoi_model',\n 'spectral_model', 'temperature_model', 'losses_model'\n- ]\n+ ]\n \n def getmcattr(self, attr):\n \"\"\"needed to avoid recursion in property lookups\"\"\"\n@@ -588,8 +570,8 @@ def dc_model(self, model):\n model = model.lower()\n if model in _DC_MODEL_PARAMS.keys():\n # validate module parameters\n- missing_params = _DC_MODEL_PARAMS[model] - \\\n- set(self.system.module_parameters.keys())\n+ missing_params = (_DC_MODEL_PARAMS[model]\n+ - set(self.system.module_parameters.keys()))\n if missing_params: # some parameters are not in module.keys()\n raise ValueError(model + ' selected for the DC model but '\n 'one or more required parameters are '\n@@ -834,8 +816,8 @@ def infer_spectral_model(self):\n \n def first_solar_spectral_loss(self):\n self.spectral_modifier = self.system.first_solar_spectral_loss(\n- self.weather['precipitable_water'],\n- self.airmass['airmass_absolute'])\n+ self.weather['precipitable_water'],\n+ self.airmass['airmass_absolute'])\n return self\n \n def sapm_spectral_loss(self):\n@@ -878,7 +860,10 @@ def temperature_model(self, model):\n \n def infer_temperature_model(self):\n params = set(self.system.temperature_model_parameters.keys())\n- if set(['a', 'b', 'deltaT']) <= params:\n+ # remove or statement in v0.9\n+ if set(['a', 'b', 'deltaT']) <= params or (\n+ not params and self.system.racking_model is None\n+ and self.system.module_type is None):\n return self.sapm_temp\n elif set(['u_c', 'u_v']) <= params:\n return self.pvsyst_temp\n@@ -945,7 +930,7 @@ def effective_irradiance_model(self):\n fd*self.total_irrad['poa_diffuse'])\n return self\n \n- def complete_irradiance(self, weather, times=None):\n+ def complete_irradiance(self, weather):\n \"\"\"\n Determine the missing irradiation columns. Only two of the\n following data columns (dni, ghi, dhi) are needed to calculate\n@@ -962,10 +947,6 @@ def complete_irradiance(self, weather, times=None):\n ``'wind_speed'``, ``'temp_air'``. All irradiance components\n are required. Air temperature of 20 C and wind speed\n of 0 m/s will be added to the DataFrame if not provided.\n- times : None, deprecated\n- Deprecated argument included for API compatibility, but not\n- used internally. The index of the weather DataFrame is used\n- for times.\n \n Returns\n -------\n@@ -994,11 +975,6 @@ def complete_irradiance(self, weather, times=None):\n \"\"\"\n self.weather = weather\n \n- if times is not None:\n- warnings.warn('times keyword argument is deprecated and will be '\n- 'removed in 0.8. The index of the weather DataFrame '\n- 'is used for times.', pvlibDeprecationWarning)\n-\n self.solar_position = self.location.get_solarposition(\n self.weather.index, method=self.solar_position_method)\n \n@@ -1029,7 +1005,7 @@ def complete_irradiance(self, weather, times=None):\n \n return self\n \n- def prepare_inputs(self, weather, times=None):\n+ def prepare_inputs(self, weather):\n \"\"\"\n Prepare the solar position, irradiance, and weather inputs to\n the model.\n@@ -1041,10 +1017,6 @@ def prepare_inputs(self, weather, times=None):\n ``'wind_speed'``, ``'temp_air'``. All irradiance components\n are required. Air temperature of 20 C and wind speed\n of 0 m/s will be added to the DataFrame if not provided.\n- times : None, deprecated\n- Deprecated argument included for API compatibility, but not\n- used internally. The index of the weather DataFrame is used\n- for times.\n \n Notes\n -----\n@@ -1064,11 +1036,6 @@ def prepare_inputs(self, weather, times=None):\n \n self.weather = weather\n \n- if times is not None:\n- warnings.warn('times keyword argument is deprecated and will be '\n- 'removed in 0.8. The index of the weather DataFrame '\n- 'is used for times.', pvlibDeprecationWarning)\n-\n self.times = self.weather.index\n try:\n kwargs = _build_kwargs(['pressure', 'temp_air'], weather)\n@@ -1126,7 +1093,7 @@ def prepare_inputs(self, weather, times=None):\n self.weather['temp_air'] = 20\n return self\n \n- def run_model(self, weather, times=None):\n+ def run_model(self, weather):\n \"\"\"\n Run the model.\n \n@@ -1137,10 +1104,6 @@ def run_model(self, weather, times=None):\n ``'wind_speed'``, ``'temp_air'``. All irradiance components\n are required. Air temperature of 20 C and wind speed\n of 0 m/s will be added to the DataFrame if not provided.\n- times : None, deprecated\n- Deprecated argument included for API compatibility, but not\n- used internally. The index of the weather DataFrame is used\n- for times.\n \n Returns\n -------\n@@ -1152,11 +1115,6 @@ def run_model(self, weather, times=None):\n ``dc``, ``ac``, ``losses``,\n ``diode_params`` (if dc_model is a single diode model)\n \"\"\"\n- if times is not None:\n- warnings.warn('times keyword argument is deprecated and will be '\n- 'removed in 0.8. The index of the weather DataFrame '\n- 'is used for times.', pvlibDeprecationWarning)\n-\n self.prepare_inputs(weather)\n self.aoi_model()\n self.spectral_model()\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -170,12 +170,12 @@ class PVSystem(object):\n def __init__(self,\n surface_tilt=0, surface_azimuth=180,\n albedo=None, surface_type=None,\n- module=None, module_type='glass_polymer',\n+ module=None, module_type=None,\n module_parameters=None,\n temperature_model_parameters=None,\n modules_per_string=1, strings_per_inverter=1,\n inverter=None, inverter_parameters=None,\n- racking_model='open_rack', losses_parameters=None, name=None,\n+ racking_model=None, losses_parameters=None, name=None,\n **kwargs):\n \n self.surface_tilt = surface_tilt\n@@ -201,25 +201,9 @@ def __init__(self,\n if temperature_model_parameters is None:\n self.temperature_model_parameters = \\\n self._infer_temperature_model_params()\n- # TODO: in v0.8 check if an empty dict is returned and raise error\n else:\n self.temperature_model_parameters = temperature_model_parameters\n \n- # TODO: deprecated behavior if PVSystem.temperature_model_parameters\n- # are not specified. Remove in v0.8\n- if not any(self.temperature_model_parameters):\n- warnings.warn(\n- 'Required temperature_model_parameters is not specified '\n- 'and parameters are not inferred from racking_model and '\n- 'module_type. Reverting to deprecated default: SAPM cell '\n- 'temperature model parameters for a glass/glass module in '\n- 'open racking. In the future '\n- 'PVSystem.temperature_model_parameters will be required',\n- pvlibDeprecationWarning)\n- params = temperature._temperature_model_params(\n- 'sapm', 'open_rack_glass_glass')\n- self.temperature_model_parameters = params\n-\n self.modules_per_string = modules_per_string\n self.strings_per_inverter = strings_per_inverter\n \n@@ -358,26 +342,6 @@ def get_iam(self, aoi, iam_model='physical'):\n else:\n raise ValueError(model + ' is not a valid IAM model')\n \n- def ashraeiam(self, aoi):\n- \"\"\"\n- Deprecated. Use ``PVSystem.get_iam`` instead.\n- \"\"\"\n- import warnings\n- warnings.warn('PVSystem.ashraeiam is deprecated and will be removed in'\n- 'v0.8, use PVSystem.get_iam instead',\n- pvlibDeprecationWarning)\n- return PVSystem.get_iam(self, aoi, iam_model='ashrae')\n-\n- def physicaliam(self, aoi):\n- \"\"\"\n- Deprecated. Use ``PVSystem.get_iam`` instead.\n- \"\"\"\n- import warnings\n- warnings.warn('PVSystem.physicaliam is deprecated and will be removed'\n- ' in v0.8, use PVSystem.get_iam instead',\n- pvlibDeprecationWarning)\n- return PVSystem.get_iam(self, aoi, iam_model='physical')\n-\n def calcparams_desoto(self, effective_irradiance, temp_cell, **kwargs):\n \"\"\"\n Use the :py:func:`calcparams_desoto` function, the input\n@@ -506,6 +470,21 @@ def sapm_celltemp(self, poa_global, temp_air, wind_speed):\n -------\n numeric, values in degrees C.\n \"\"\"\n+ # warn user about change in default behavior in 0.9.\n+ if (self.temperature_model_parameters == {} and self.module_type\n+ is None and self.racking_model is None):\n+ warnings.warn(\n+ 'temperature_model_parameters, racking_model, and module_type '\n+ 'are not specified. Reverting to deprecated default: SAPM '\n+ 'cell temperature model parameters for a glass/glass module '\n+ 'in open racking. In v0.9, temperature_model_parameters or a '\n+ 'valid combination of racking_model and module_type will be '\n+ 'required.',\n+ pvlibDeprecationWarning)\n+ params = temperature._temperature_model_params(\n+ 'sapm', 'open_rack_glass_glass')\n+ self.temperature_model_parameters = params\n+\n kwargs = _build_kwargs(['a', 'b', 'deltaT'],\n self.temperature_model_parameters)\n return temperature.sapm_cell(poa_global, temp_air, wind_speed,\n@@ -514,7 +493,7 @@ def sapm_celltemp(self, poa_global, temp_air, wind_speed):\n def _infer_temperature_model_params(self):\n # try to infer temperature model parameters from from racking_model\n # and module_type\n- param_set = self.racking_model + '_' + self.module_type\n+ param_set = '{}_{}'.format(self.racking_model, self.module_type)\n if param_set in temperature.TEMPERATURE_MODEL_PARAMETERS['sapm']:\n return temperature._temperature_model_params('sapm', param_set)\n elif 'freestanding' in param_set:\n@@ -543,16 +522,6 @@ def sapm_spectral_loss(self, airmass_absolute):\n \"\"\"\n return sapm_spectral_loss(airmass_absolute, self.module_parameters)\n \n- def sapm_aoi_loss(self, aoi):\n- \"\"\"\n- Deprecated. Use ``PVSystem.get_iam`` instead.\n- \"\"\"\n- import warnings\n- warnings.warn('PVSystem.sapm_aoi_loss is deprecated and will be'\n- ' removed in v0.8, use PVSystem.get_iam instead',\n- pvlibDeprecationWarning)\n- return PVSystem.get_iam(self, aoi, iam_model='sapm')\n-\n def sapm_effective_irradiance(self, poa_direct, poa_diffuse,\n airmass_absolute, aoi,\n reference_irradiance=1000):\n@@ -671,7 +640,7 @@ def first_solar_spectral_loss(self, pw, airmass_absolute):\n if 'first_solar_spectral_coefficients' in \\\n self.module_parameters.keys():\n coefficients = \\\n- self.module_parameters['first_solar_spectral_coefficients']\n+ self.module_parameters['first_solar_spectral_coefficients']\n module_type = None\n else:\n module_type = self._infer_cell_type()\n@@ -1071,27 +1040,6 @@ def calcparams_desoto(effective_irradiance, temp_cell,\n Source: [4]\n '''\n \n- # test for use of function pre-v0.6.0 API change\n- if isinstance(a_ref, dict) or \\\n- (isinstance(a_ref, pd.Series) and ('a_ref' in a_ref.keys())):\n- import warnings\n- warnings.warn('module_parameters detected as fourth positional'\n- + ' argument of calcparams_desoto. calcparams_desoto'\n- + ' will require one argument for each module model'\n- + ' parameter in v0.7.0 and later', DeprecationWarning)\n- try:\n- module_parameters = a_ref\n- a_ref = module_parameters['a_ref']\n- I_L_ref = module_parameters['I_L_ref']\n- I_o_ref = module_parameters['I_o_ref']\n- R_sh_ref = module_parameters['R_sh_ref']\n- R_s = module_parameters['R_s']\n- except Exception as e:\n- raise e('Module parameters could not be extracted from fourth'\n- + ' positional argument of calcparams_desoto. Check that'\n- + ' parameters are from the CEC database and/or update'\n- + ' your code for the new API for calcparams_desoto')\n-\n # Boltzmann constant in eV/K\n k = 8.617332478e-05\n \n@@ -1624,16 +1572,6 @@ def sapm(effective_irradiance, temp_cell, module):\n # reference_irradiance and expose\n temp_ref = 25\n irrad_ref = 1000\n- # TODO: remove this warning in v0.8 after deprecation period for change in\n- # effective irradiance units, made in v0.7\n- with np.errstate(invalid='ignore'): # turn off warning for NaN\n- ee = np.asarray(effective_irradiance)\n- ee_gt0 = ee[ee > 0.0]\n- if ee_gt0.size > 0 and np.all(ee_gt0 < 2.0):\n- import warnings\n- msg = 'effective_irradiance inputs appear to be in suns. Units ' \\\n- 'changed in v0.7 from suns to W/m2'\n- warnings.warn(msg, RuntimeWarning)\n \n q = 1.60218e-19 # Elementary charge in units of coulombs\n kb = 1.38066e-23 # Boltzmann's constant in units of J/K\n@@ -1695,85 +1633,6 @@ def sapm(effective_irradiance, temp_cell, module):\n return out\n \n \n-def _sapm_celltemp_translator(*args, **kwargs):\n- # TODO: remove this function after deprecation period for sapm_celltemp\n- new_kwargs = {}\n- # convert position arguments to kwargs\n- old_arg_list = ['poa_global', 'wind_speed', 'temp_air', 'model']\n- for pos in range(len(args)):\n- new_kwargs[old_arg_list[pos]] = args[pos]\n- # determine value for new kwarg 'model'\n- try:\n- param_set = new_kwargs['model']\n- new_kwargs.pop('model') # model is not a new kwarg\n- except KeyError:\n- # 'model' not in positional arguments, check kwargs\n- try:\n- param_set = kwargs['model']\n- kwargs.pop('model')\n- except KeyError:\n- # 'model' not in kwargs, use old default value\n- param_set = 'open_rack_glass_glass'\n- if type(param_set) is list:\n- new_kwargs.update({'a': param_set[0],\n- 'b': param_set[1],\n- 'deltaT': param_set[2]})\n- elif type(param_set) is dict:\n- new_kwargs.update(param_set)\n- else: # string\n- params = temperature._temperature_model_params('sapm', param_set)\n- new_kwargs.update(params)\n- new_kwargs.update(kwargs) # kwargs with unchanged names\n- new_kwargs['irrad_ref'] = 1000 # default for new kwarg\n- # convert old positional arguments to named kwargs\n- return temperature.sapm_cell(**new_kwargs)\n-\n-\n-sapm_celltemp = deprecated('0.7', alternative='temperature.sapm_cell',\n- name='sapm_celltemp', removal='0.8',\n- addendum='Note that the arguments and argument '\n- 'order for temperature.sapm_cell are different '\n- 'than for sapm_celltemp')(_sapm_celltemp_translator)\n-\n-\n-def _pvsyst_celltemp_translator(*args, **kwargs):\n- # TODO: remove this function after deprecation period for pvsyst_celltemp\n- new_kwargs = {}\n- # convert position arguments to kwargs\n- old_arg_list = ['poa_global', 'temp_air', 'wind_speed', 'eta_m',\n- 'alpha_absorption', 'model_params']\n- for pos in range(len(args)):\n- new_kwargs[old_arg_list[pos]] = args[pos]\n- # determine value for new kwarg 'model'\n- try:\n- param_set = new_kwargs['model_params']\n- new_kwargs.pop('model_params') # model_params is not a new kwarg\n- except KeyError:\n- # 'model_params' not in positional arguments, check kwargs\n- try:\n- param_set = kwargs['model_params']\n- kwargs.pop('model_params')\n- except KeyError:\n- # 'model_params' not in kwargs, use old default value\n- param_set = 'freestanding'\n- if type(param_set) in (list, tuple):\n- new_kwargs.update({'u_c': param_set[0],\n- 'u_v': param_set[1]})\n- else: # string\n- params = temperature._temperature_model_params('pvsyst', param_set)\n- new_kwargs.update(params)\n- new_kwargs.update(kwargs) # kwargs with unchanged names\n- # convert old positional arguments to named kwargs\n- return temperature.pvsyst_cell(**new_kwargs)\n-\n-\n-pvsyst_celltemp = deprecated(\n- '0.7', alternative='temperature.pvsyst_cell', name='pvsyst_celltemp',\n- removal='0.8', addendum='Note that the argument names for '\n- 'temperature.pvsyst_cell are different than '\n- 'for pvsyst_celltemp')(_pvsyst_celltemp_translator)\n-\n-\n def sapm_spectral_loss(airmass_absolute, module):\n \"\"\"\n Calculates the SAPM spectral loss coefficient, F1.\n@@ -2051,8 +1910,7 @@ def singlediode(photocurrent, saturation_current, resistance_series,\n # calculate the IV curve if requested using bishop88\n if ivcurve_pnts:\n vd = v_oc * (\n- (11.0 - np.logspace(np.log10(11.0), 0.0,\n- ivcurve_pnts)) / 10.0\n+ (11.0 - np.logspace(np.log10(11.0), 0.0, ivcurve_pnts)) / 10.0\n )\n ivcurve_i, ivcurve_v, _ = _singlediode.bishop88(vd, *args)\n \n@@ -2301,17 +2159,17 @@ def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage,\n # equation for the diode voltage V_d then backing out voltage\n args = (voltage, photocurrent, saturation_current, resistance_series,\n resistance_shunt, nNsVth)\n- I = _singlediode.bishop88_i_from_v(*args, method=method.lower())\n+ current = _singlediode.bishop88_i_from_v(*args, method=method.lower())\n # find the right size and shape for returns\n size, shape = _singlediode._get_size_and_shape(args)\n if size <= 1:\n if shape is not None:\n- I = np.tile(I, shape)\n- if np.isnan(I).any() and size <= 1:\n- I = np.repeat(I, size)\n+ current = np.tile(current, shape)\n+ if np.isnan(current).any() and size <= 1:\n+ current = np.repeat(current, size)\n if shape is not None:\n- I = I.reshape(shape)\n- return I\n+ current = current.reshape(shape)\n+ return current\n \n \n def scale_voltage_current_power(data, voltage=1, current=1):\n@@ -2390,7 +2248,7 @@ def pvwatts_dc(g_poa_effective, temp_cell, pdc0, gamma_pdc, temp_ref=25.):\n .. [1] A. P. Dobos, \"PVWatts Version 5 Manual\"\n http://pvwatts.nrel.gov/downloads/pvwattsv5.pdf\n (2014).\n- \"\"\"\n+ \"\"\" # noqa: E501\n \n pdc = (g_poa_effective * 0.001 * pdc0 *\n (1 + gamma_pdc * (temp_cell - temp_ref)))\n@@ -2452,18 +2310,6 @@ def pvwatts_losses(soiling=2, shading=3, snow=0, mismatch=2, wiring=2,\n return losses\n \n \n-ashraeiam = deprecated('0.7', alternative='iam.ashrae', name='ashraeiam',\n- removal='0.8')(iam.ashrae)\n-\n-\n-physicaliam = deprecated('0.7', alternative='iam.physical', name='physicaliam',\n- removal='0.8')(iam.physical)\n-\n-\n-sapm_aoi_loss = deprecated('0.7', alternative='iam.sapm', name='sapm_aoi_loss',\n- removal='0.8')(iam.sapm)\n-\n-\n snlinverter = deprecated('0.8', alternative='inverter.sandia',\n name='snlinverter', removal='0.9')(inverter.sandia)\n \n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -13,7 +13,7 @@\n from conftest import assert_series_equal\n import pytest\n \n-from conftest import fail_on_pvlib_version, requires_scipy, requires_tables\n+from conftest import fail_on_pvlib_version, requires_scipy\n \n \n @pytest.fixture(scope='function')\n@@ -153,6 +153,18 @@ def system_no_aoi(cec_module_cs5p_220m, sapm_temperature_cs5p_220m,\n return system\n \n \[email protected]\n+def system_no_temp(cec_module_cs5p_220m, cec_inverter_parameters):\n+ module_parameters = cec_module_cs5p_220m.copy()\n+ module_parameters['EgRef'] = 1.121\n+ module_parameters['dEgdT'] = -0.0002677\n+ inverter_parameters = cec_inverter_parameters.copy()\n+ system = PVSystem(surface_tilt=32.2, surface_azimuth=180,\n+ module_parameters=module_parameters,\n+ inverter_parameters=inverter_parameters)\n+ return system\n+\n+\n @pytest.fixture\n def location():\n return Location(32.2, -111, altitude=700)\n@@ -211,24 +223,6 @@ def test_run_model_with_irradiance(sapm_dc_snl_ac_system, location):\n assert_series_equal(ac, expected)\n \n \n-def test_run_model_times(sapm_dc_snl_ac_system, location):\n- mc = ModelChain(sapm_dc_snl_ac_system, location)\n- times = pd.date_range('20160101 1200-0700', periods=2, freq='6H')\n- irradiance = pd.DataFrame({'dni': 900, 'ghi': 600, 'dhi': 150},\n- index=times)\n- with pytest.warns(pvlibDeprecationWarning):\n- mc.run_model(irradiance, times=times)\n-\n-\n-def test_prepare_inputs_times(sapm_dc_snl_ac_system, location):\n- mc = ModelChain(sapm_dc_snl_ac_system, location)\n- times = pd.date_range('20160101 1200-0700', periods=2, freq='6H')\n- irradiance = pd.DataFrame({'dni': 900, 'ghi': 600, 'dhi': 150},\n- index=times)\n- with pytest.warns(pvlibDeprecationWarning):\n- mc.prepare_inputs(irradiance, times=times)\n-\n-\n def test_prepare_inputs_no_irradiance(sapm_dc_snl_ac_system, location):\n mc = ModelChain(sapm_dc_snl_ac_system, location)\n weather = pd.DataFrame()\n@@ -236,15 +230,6 @@ def test_prepare_inputs_no_irradiance(sapm_dc_snl_ac_system, location):\n mc.prepare_inputs(weather)\n \n \n-@requires_tables\n-def test_complete_irradiance_times(sapm_dc_snl_ac_system, location):\n- mc = ModelChain(sapm_dc_snl_ac_system, location)\n- times = pd.date_range('20160101 1200-0700', periods=2, freq='6H')\n- irradiance = pd.DataFrame({'ghi': 600., 'dhi': 150.}, index=times)\n- with pytest.warns(pvlibDeprecationWarning):\n- mc.complete_irradiance(irradiance, times=times)\n-\n-\n def test_run_model_perez(sapm_dc_snl_ac_system, location):\n mc = ModelChain(sapm_dc_snl_ac_system, location,\n transposition_model='perez')\n@@ -277,8 +262,6 @@ def test_run_model_with_weather_sapm_temp(sapm_dc_snl_ac_system, location,\n # test with sapm cell temperature model\n weather['wind_speed'] = 5\n weather['temp_air'] = 10\n- sapm_dc_snl_ac_system.racking_model = 'open_rack'\n- sapm_dc_snl_ac_system.module_type = 'glass_glass'\n mc = ModelChain(sapm_dc_snl_ac_system, location)\n mc.temperature_model = 'sapm'\n m_sapm = mocker.spy(sapm_dc_snl_ac_system, 'sapm_celltemp')\n@@ -437,6 +420,17 @@ def test_infer_temp_model_invalid(location, sapm_dc_snl_ac_system):\n spectral_model='no_loss')\n \n \n+# ModelChain.infer_temperature_model. remove or statement in v0.9\n+@requires_scipy\n+@fail_on_pvlib_version('0.9')\n+def test_infer_temp_model_no_params(location, system_no_temp, weather):\n+ mc = ModelChain(system_no_temp, location, aoi_model='physical',\n+ spectral_model='no_loss')\n+ match = \"Reverting to deprecated default: SAPM cell temperature\"\n+ with pytest.warns(pvlibDeprecationWarning, match=match):\n+ mc.run_model(weather)\n+\n+\n @requires_scipy\n def test_temperature_model_inconsistent(location, sapm_dc_snl_ac_system):\n with pytest.raises(ValueError):\n@@ -688,36 +682,6 @@ def test_bad_get_orientation():\n modelchain.get_orientation('bad value')\n \n \n-@fail_on_pvlib_version('0.8')\n-def test_deprecated_08():\n- # explicit system creation call because fail_on_pvlib_version\n- # does not support decorators.\n- # does not matter what the parameters are, just fake it until we make it\n- module_parameters = {'R_sh_ref': 1, 'a_ref': 1, 'I_o_ref': 1,\n- 'alpha_sc': 1, 'I_L_ref': 1, 'R_s': 1}\n- # do not assign PVSystem.temperature_model_parameters\n- # leave out PVSystem.racking_model and PVSystem.module_type\n- system = PVSystem(module_parameters=module_parameters)\n- # deprecated temp_model kwarg\n- warn_txt = 'temp_model keyword argument is deprecated'\n- with pytest.warns(pvlibDeprecationWarning, match=warn_txt):\n- ModelChain(system, location, dc_model='desoto', aoi_model='no_loss',\n- spectral_model='no_loss', ac_model='sandia',\n- temp_model='sapm')\n- # provide both temp_model and temperature_model kwargs\n- warn_txt = 'Provide only one of temperature_model'\n- with pytest.warns(pvlibDeprecationWarning, match=warn_txt):\n- ModelChain(system, location, dc_model='desoto', aoi_model='no_loss',\n- spectral_model='no_loss', ac_model='sandia',\n- temperature_model='sapm', temp_model='sapm')\n- # conflicting temp_model and temperature_model kwargs\n- exc_text = 'Conflicting temperature_model'\n- with pytest.raises(ValueError, match=exc_text):\n- ModelChain(system, location, dc_model='desoto', aoi_model='no_loss',\n- spectral_model='no_loss', ac_model='sandia',\n- temperature_model='pvsyst', temp_model='sapm')\n-\n-\n @fail_on_pvlib_version('0.9')\n @pytest.mark.parametrize('ac_model', ['snlinverter', 'adrinverter'])\n def test_deprecated_09(sapm_dc_snl_ac_system, cec_dc_adr_ac_system,\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -198,17 +198,6 @@ def test_sapm(sapm_module_params):\n pd.Series(sapm_module_params))\n \n \n-def test_pvsystem_sapm_warning(sapm_module_params):\n- # deprecation warning for change in effective_irradiance units in\n- # pvsystem.sapm\n- # TODO: remove after deprecation period (v0.8)\n- effective_irradiance = np.array([0.1, 0.2, 1.3])\n- temp_cell = np.array([25, 25, 50])\n- warn_txt = 'effective_irradiance inputs appear to be in suns'\n- with pytest.warns(RuntimeWarning, match=warn_txt):\n- pvsystem.sapm(effective_irradiance, temp_cell, sapm_module_params)\n-\n-\n def test_PVSystem_sapm(sapm_module_params, mocker):\n mocker.spy(pvsystem, 'sapm')\n system = pvsystem.PVSystem(module_parameters=sapm_module_params)\n@@ -386,14 +375,6 @@ def test__infer_temperature_model_params():\n assert expected == system._infer_temperature_model_params()\n \n \n-def test__infer_temperature_model_params_deprec_warning():\n- warn_txt = \"Reverting to deprecated default\"\n- with pytest.warns(pvlibDeprecationWarning, match=warn_txt):\n- pvsystem.PVSystem(module_parameters={},\n- racking_model='not_a_rack_model',\n- module_type='glass_polymer')\n-\n-\n def test_calcparams_desoto(cec_module_params):\n times = pd.date_range(start='2015-01-01', periods=3, freq='12H')\n effective_irradiance = pd.Series([0.0, 800.0, 800.0], index=times)\n@@ -1130,8 +1111,8 @@ def test_PVSystem___repr__():\n module: blah\n inverter: blarg\n albedo: 0.25\n- racking_model: open_rack\n- module_type: glass_polymer\n+ racking_model: None\n+ module_type: None\n temperature_model_parameters: {'a': -3.56}\"\"\"\n assert system.__repr__() == expected\n \n@@ -1153,8 +1134,8 @@ def test_PVSystem_localize___repr__():\n module: blah\n inverter: blarg\n albedo: 0.25\n- racking_model: open_rack\n- module_type: glass_polymer\n+ racking_model: None\n+ module_type: None\n temperature_model_parameters: {'a': -3.56}\"\"\"\n \n assert localized_system.__repr__() == expected\n@@ -1193,8 +1174,8 @@ def test_LocalizedPVSystem___repr__():\n module: blah\n inverter: blarg\n albedo: 0.25\n- racking_model: open_rack\n- module_type: glass_polymer\n+ racking_model: None\n+ module_type: None\n temperature_model_parameters: {'a': -3.56}\"\"\"\n \n assert localized_system.__repr__() == expected\n@@ -1318,94 +1299,6 @@ def test_PVSystem_pvwatts_ac_kwargs(mocker):\n assert out < pdc\n \n \n-@fail_on_pvlib_version('0.8')\n-def test_deprecated_08():\n- # deprecated function pvsystem.sapm_celltemp\n- with pytest.warns(pvlibDeprecationWarning):\n- pvsystem.sapm_celltemp(1000, 25, 1)\n- # deprecated function pvsystem.pvsyst_celltemp\n- with pytest.warns(pvlibDeprecationWarning):\n- pvsystem.pvsyst_celltemp(1000, 25)\n- module_parameters = {'R_sh_ref': 1, 'a_ref': 1, 'I_o_ref': 1,\n- 'alpha_sc': 1, 'I_L_ref': 1, 'R_s': 1,\n- 'B5': 0.0, 'B4': 0.0, 'B3': 0.0, 'B2': 0.0,\n- 'B1': 0.0, 'B0': 1.0,\n- 'b': 0.05, 'K': 4, 'L': 0.002, 'n': 1.526,\n- 'a_r': 0.16}\n- temp_model_params = temperature.TEMPERATURE_MODEL_PARAMETERS['sapm'][\n- 'open_rack_glass_glass']\n- # for missing temperature_model_parameters\n- with pytest.warns(pvlibDeprecationWarning):\n- pvsystem.PVSystem(module_parameters=module_parameters,\n- racking_model='open', module_type='glass_glass')\n- pv = pvsystem.PVSystem(module_parameters=module_parameters,\n- temperature_model_parameters=temp_model_params,\n- racking_model='open', module_type='glass_glass')\n- # deprecated method PVSystem.ashraeiam\n- with pytest.warns(pvlibDeprecationWarning):\n- pv.ashraeiam(45)\n- # deprecated function ashraeiam\n- with pytest.warns(pvlibDeprecationWarning):\n- pvsystem.ashraeiam(45)\n- # deprecated method PVSystem.physicaliam\n- with pytest.warns(pvlibDeprecationWarning):\n- pv.physicaliam(45)\n- # deprecated function physicaliam\n- with pytest.warns(pvlibDeprecationWarning):\n- pvsystem.physicaliam(45)\n- # deprecated method PVSystem.sapm_aoi_loss\n- with pytest.warns(pvlibDeprecationWarning):\n- pv.sapm_aoi_loss(45)\n- # deprecated function sapm_aoi_loss\n- with pytest.warns(pvlibDeprecationWarning):\n- pvsystem.sapm_aoi_loss(45, {'B5': 0.0, 'B4': 0.0, 'B3': 0.0, 'B2': 0.0,\n- 'B1': 0.0, 'B0': 1.0})\n-\n-\n-@fail_on_pvlib_version('0.8')\n-def test__pvsyst_celltemp_translator():\n- result = pvsystem._pvsyst_celltemp_translator(900, 20, 5)\n- assert_allclose(result, 45.137, 0.001)\n- result = pvsystem._pvsyst_celltemp_translator(900, 20, 5, 0.1, 0.9,\n- [29.0, 0.0])\n- assert_allclose(result, 45.137, 0.001)\n- result = pvsystem._pvsyst_celltemp_translator(poa_global=900, temp_air=20,\n- wind_speed=5)\n- assert_allclose(result, 45.137, 0.001)\n- result = pvsystem._pvsyst_celltemp_translator(900, 20, wind_speed=5)\n- assert_allclose(result, 45.137, 0.001)\n- result = pvsystem._pvsyst_celltemp_translator(900, 20, wind_speed=5.0,\n- u_c=23.5, u_v=6.25,\n- eta_m=0.1)\n- assert_allclose(result, 33.315, 0.001)\n- result = pvsystem._pvsyst_celltemp_translator(900, 20, wind_speed=5.0,\n- eta_m=0.1,\n- model_params=[23.5, 6.25])\n- assert_allclose(result, 33.315, 0.001)\n- result = pvsystem._pvsyst_celltemp_translator(900, 20, wind_speed=5.0,\n- eta_m=0.1,\n- model_params=(23.5, 6.25))\n- assert_allclose(result, 33.315, 0.001)\n-\n-\n-@fail_on_pvlib_version('0.8')\n-def test__sapm_celltemp_translator():\n- result = pvsystem._sapm_celltemp_translator(900, 5, 20,\n- 'open_rack_glass_glass')\n- assert_allclose(result, 43.509, 3)\n- result = pvsystem._sapm_celltemp_translator(900, 5, temp_air=20,\n- model='open_rack_glass_glass')\n- assert_allclose(result, 43.509, 3)\n- params = temperature.TEMPERATURE_MODEL_PARAMETERS['sapm'][\n- 'open_rack_glass_glass']\n- result = pvsystem._sapm_celltemp_translator(900, 5, 20, params)\n- assert_allclose(result, 43.509, 3)\n- result = pvsystem._sapm_celltemp_translator(900, 5, 20,\n- [params['a'], params['b'],\n- params['deltaT']])\n- assert_allclose(result, 43.509, 3)\n-\n-\n @fail_on_pvlib_version('0.9')\n def test_deprecated_09(cec_inverter_parameters, adr_inverter_parameters):\n # deprecated function pvsystem.snlinverter\n@@ -1417,3 +1310,8 @@ def test_deprecated_09(cec_inverter_parameters, adr_inverter_parameters):\n # deprecated function pvsystem.spvwatts_ac\n with pytest.warns(pvlibDeprecationWarning):\n pvsystem.pvwatts_ac(90, 100, 0.95)\n+ # for missing temperature_model_parameters\n+ match = \"Reverting to deprecated default: SAPM cell temperature\"\n+ system = pvsystem.PVSystem()\n+ with pytest.warns(pvlibDeprecationWarning, match=match):\n+ system.sapm_celltemp(1, 2, 3)\ndiff --git a/pvlib/tests/test_tracking.py b/pvlib/tests/test_tracking.py\n--- a/pvlib/tests/test_tracking.py\n+++ b/pvlib/tests/test_tracking.py\n@@ -453,8 +453,8 @@ def test_SingleAxisTracker___repr__():\n module: blah\n inverter: blarg\n albedo: 0.25\n- racking_model: open_rack\n- module_type: glass_polymer\n+ racking_model: None\n+ module_type: None\n temperature_model_parameters: {'a': -3.56}\"\"\"\n assert system.__repr__() == expected\n \n@@ -477,8 +477,8 @@ def test_LocalizedSingleAxisTracker___repr__():\n module: blah\n inverter: blarg\n albedo: 0.25\n- racking_model: open_rack\n- module_type: glass_polymer\n+ racking_model: None\n+ module_type: None\n temperature_model_parameters: {'a': -3.56}\n latitude: 32\n longitude: -111\n", "problem_statement": "PVSystem.temperature_model_parameters requirement\nThe `temperature_model_parameters` handling code below suggests to me that in 0.8 we're going to \r\n\r\n1. set default values `module_type=None` and `racking_model=None`.\r\n2. require user to specify either `temperature_model_parameters` or both `module_type` and `racking_model`.\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/27872b83b0932cc419116f79e442963cced935bb/pvlib/pvsystem.py#L208-L221\r\n\r\n@cwhanse is that correct?\r\n\r\nThe problem is that the only way to see this warning is to supply an invalid `module_type` or `racking_model`. That's because `PVSystem._infer_temperature_model` is called before the code above, and it looks up the default `module_type` and `racking_model` and successfully finds temperature coefficients.\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/27872b83b0932cc419116f79e442963cced935bb/pvlib/pvsystem.py#L201-L203\r\n\r\nSo I'm guessing that this warning has been seen by only a small fraction of people that need to see it. I'm ok moving forward with the removal in 0.8 or pushing to 0.9. \nremove deprecated functions in 0.8\n`pvsystem`:\r\n* `sapm_celltemp`\r\n* `pvsyst_celltemp`\r\n* `ashraeiam`\r\n* `physicaliam`\r\n* `sapm_aoi_loss`\r\n* `PVSystem.ashraeiam`\r\n* `PVSystem.physicaliam`\r\n* `PVSystem.sapm_aoi_loss`\r\n* inference of `PVSystem.temperature_model_parameters`\r\n\r\n`modelchain.ModelChain`:\r\n* remove `times` from `complete_irradiance`, `prepare_inputs`, `run_model`\r\n* remove `temp_model` kwarg\n", "hints_text": "> The `temperature_model_parameters` handling code below suggests to me that in 0.8 we're going to\r\n> \r\n> 1. set default values `module_type=None` and `racking_model=None`.\r\n> 2. require user to specify either `temperature_model_parameters` or both `module_type` and `racking_model`.\r\n> \r\n> @cwhanse is that correct?\r\n\r\nYes, that is the intent.\r\n\r\n> So I'm guessing that this warning has been seen by only a small fraction of people that need to see it. I'm ok moving forward with the removal in 0.8 or pushing to 0.9.\r\n\r\nThe warning should have been raised whenever condition #2 above wasn't met; it looks to me that has been the case. If that hasn't been the case I would prefer to fix the warning and push the deprecation out to v0.9. pvlib-python has had that unadvertised default temperature model assignment for a long time.\r\n\n> The problem is that the only way to see this warning is to supply an invalid `module_type` or `racking_model`. That's because `PVSystem._infer_temperature_model` is called before the code above, and it looks up the default `module_type` and `racking_model` and successfully finds temperature coefficients.\r\n\r\nI don't follow here - it looks to me that the warning should be raised if 1) `temperature_model_parameters` isn't specified, or 2) either `module_type` or `racking_model` are invalid. Maybe we're saying the same thing. `_infer_temperature_model` doesn't assign the default temperature model, that is done in the block of code that raises the warning. \r\n\r\n\nThe `module_type` and `racking_model` defaults prevent the warning from showing up in many use cases. If we change the defaults to `None` then the warning will be triggered. If we simultaneously remove the warning then code will break without users having ever seen the warning.\nWhat is the expected behavior for `PVSystem()`?\n> The `module_type` and `racking_model` defaults prevent the warning from showing up in many use cases. If we change the defaults to `None` then the warning will be triggered. If we simultaneously remove the warning then code will break without users having ever seen the warning.\r\n\r\nAha. I see the problem now, thanks. Perhaps remove the defaults in v0.8 and leave the warning until v0.9?\nOk, I'll work on that.\n", "created_at": "2020-08-25T18:51:23Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_infer_temp_model_no_params", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize___repr__", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_deprecated_09", "pvlib/tests/test_tracking.py::test_SingleAxisTracker___repr__", "pvlib/tests/test_tracking.py::test_LocalizedSingleAxisTracker___repr__"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[snlinverter]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[adrinverter]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_deprecated_09[snlinverter]", "pvlib/tests/test_modelchain.py::test_deprecated_09[adrinverter]", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_location", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_latlon", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem_creation", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_tracking.py::test_solar_noon", "pvlib/tests/test_tracking.py::test_scalars", "pvlib/tests/test_tracking.py::test_arrays", "pvlib/tests/test_tracking.py::test_nans", "pvlib/tests/test_tracking.py::test_arrays_multi", "pvlib/tests/test_tracking.py::test_azimuth_north_south", "pvlib/tests/test_tracking.py::test_max_angle", "pvlib/tests/test_tracking.py::test_backtrack", "pvlib/tests/test_tracking.py::test_axis_tilt", "pvlib/tests/test_tracking.py::test_axis_azimuth", "pvlib/tests/test_tracking.py::test_horizon_flat", "pvlib/tests/test_tracking.py::test_horizon_tilted", "pvlib/tests/test_tracking.py::test_low_sun_angles", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_creation", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_tracking", "pvlib/tests/test_tracking.py::test_LocalizedSingleAxisTracker_creation", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_localize", "pvlib/tests/test_tracking.py::test_SingleAxisTracker_localize_location", "pvlib/tests/test_tracking.py::test_get_aoi", "pvlib/tests/test_tracking.py::test_get_irradiance"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-718", "base_commit": "3c84edd644fa4db54955e2225a183fa3e0405eb0", "patch": "diff --git a/pvlib/__init__.py b/pvlib/__init__.py\n--- a/pvlib/__init__.py\n+++ b/pvlib/__init__.py\n@@ -7,6 +7,7 @@\n from pvlib import location\n from pvlib import solarposition\n from pvlib import iotools\n+from pvlib import ivtools\n from pvlib import tracking\n from pvlib import pvsystem\n from pvlib import spa\ndiff --git a/pvlib/ivtools.py b/pvlib/ivtools.py\nnew file mode 100644\n--- /dev/null\n+++ b/pvlib/ivtools.py\n@@ -0,0 +1,350 @@\n+# -*- coding: utf-8 -*-\n+\"\"\"\n+Created on Fri Mar 29 10:34:10 2019\n+\n+@author: cwhanse\n+\"\"\"\n+\n+import numpy as np\n+\n+\n+def fit_sdm_cec_sam(celltype, v_mp, i_mp, v_oc, i_sc, alpha_sc, beta_voc,\n+ gamma_pmp, cells_in_series, temp_ref=25):\n+ \"\"\"\n+ Estimates parameters for the CEC single diode model (SDM) using the SAM\n+ SDK.\n+\n+ Parameters\n+ ----------\n+ celltype : str\n+ Value is one of 'monoSi', 'multiSi', 'polySi', 'cis', 'cigs', 'cdte',\n+ 'amorphous'\n+ v_mp : float\n+ Voltage at maximum power point [V]\n+ i_mp : float\n+ Current at maximum power point [A]\n+ v_oc : float\n+ Open circuit voltage [V]\n+ i_sc : float\n+ Short circuit current [A]\n+ alpha_sc : float\n+ Temperature coefficient of short circuit current [A/C]\n+ beta_voc : float\n+ Temperature coefficient of open circuit voltage [V/C]\n+ gamma_pmp : float\n+ Temperature coefficient of power at maximum point point [%/C]\n+ cells_in_series : int\n+ Number of cells in series\n+ temp_ref : float, default 25\n+ Reference temperature condition [C]\n+\n+ Returns\n+ -------\n+ tuple of the following elements:\n+\n+ * I_L_ref : float\n+ The light-generated current (or photocurrent) at reference\n+ conditions [A]\n+\n+ * I_o_ref : float\n+ The dark or diode reverse saturation current at reference\n+ conditions [A]\n+\n+ * R_sh_ref : float\n+ The shunt resistance at reference conditions, in ohms.\n+\n+ * R_s : float\n+ The series resistance at reference conditions, in ohms.\n+\n+ * a_ref : float\n+ The product of the usual diode ideality factor ``n`` (unitless),\n+ number of cells in series ``Ns``, and cell thermal voltage at\n+ reference conditions [V]\n+\n+ * Adjust : float\n+ The adjustment to the temperature coefficient for short circuit\n+ current, in percent.\n+\n+ Raises\n+ ------\n+ ImportError if NREL-PySAM is not installed.\n+\n+ RuntimeError if parameter extraction is not successful.\n+\n+ Notes\n+ -----\n+ Inputs ``v_mp``, ``v_oc``, ``i_mp`` and ``i_sc`` are assumed to be from a\n+ single IV curve at constant irradiance and cell temperature. Irradiance is\n+ not explicitly used by the fitting procedure. The irradiance level at which\n+ the input IV curve is determined and the specified cell temperature\n+ ``temp_ref`` are the reference conditions for the output parameters\n+ ``I_L_ref``, ``I_o_ref``, ``R_sh_ref``, ``R_s``, ``a_ref`` and ``Adjust``.\n+\n+ References\n+ ----------\n+ [1] A. Dobos, \"An Improved Coefficient Calculator for the California\n+ Energy Commission 6 Parameter Photovoltaic Module Model\", Journal of\n+ Solar Energy Engineering, vol 134, 2012.\n+ \"\"\"\n+\n+ try:\n+ from PySAM import PySSC\n+ except ImportError:\n+ raise ImportError(\"Requires NREL's PySAM package at \"\n+ \"https://pypi.org/project/NREL-PySAM/.\")\n+\n+ datadict = {'tech_model': '6parsolve', 'financial_model': 'none',\n+ 'celltype': celltype, 'Vmp': v_mp,\n+ 'Imp': i_mp, 'Voc': v_oc, 'Isc': i_sc, 'alpha_isc': alpha_sc,\n+ 'beta_voc': beta_voc, 'gamma_pmp': gamma_pmp,\n+ 'Nser': cells_in_series, 'Tref': temp_ref}\n+\n+ result = PySSC.ssc_sim_from_dict(datadict)\n+ if result['cmod_success'] == 1:\n+ return tuple([result[k] for k in ['Il', 'Io', 'Rsh', 'Rs', 'a',\n+ 'Adj']])\n+ else:\n+ raise RuntimeError('Parameter estimation failed')\n+\n+\n+def fit_sde_sandia(voltage, current, v_oc=None, i_sc=None, v_mp_i_mp=None,\n+ vlim=0.2, ilim=0.1):\n+ r\"\"\"\n+ Fits the single diode equation (SDE) to an IV curve.\n+\n+ Parameters\n+ ----------\n+ voltage : ndarray\n+ 1D array of `float` type containing voltage at each point on the IV\n+ curve, increasing from 0 to ``v_oc`` inclusive [V]\n+\n+ current : ndarray\n+ 1D array of `float` type containing current at each point on the IV\n+ curve, from ``i_sc`` to 0 inclusive [A]\n+\n+ v_oc : float, default None\n+ Open circuit voltage [V]. If not provided, ``v_oc`` is taken as the\n+ last point in the ``voltage`` array.\n+\n+ i_sc : float, default None\n+ Short circuit current [A]. If not provided, ``i_sc`` is taken as the\n+ first point in the ``current`` array.\n+\n+ v_mp_i_mp : tuple of float, default None\n+ Voltage, current at maximum power point in units of [V], [A].\n+ If not provided, the maximum power point is found at the maximum of\n+ ``voltage`` \\times ``current``.\n+\n+ vlim : float, default 0.2\n+ Defines portion of IV curve where the exponential term in the single\n+ diode equation can be neglected, i.e.\n+ ``voltage`` <= ``vlim`` x ``v_oc`` [V]\n+\n+ ilim : float, default 0.1\n+ Defines portion of the IV curve where the exponential term in the\n+ single diode equation is signficant, approximately defined by\n+ ``current`` < (1 - ``ilim``) x ``i_sc`` [A]\n+\n+ Returns\n+ -------\n+ tuple of the following elements:\n+\n+ * photocurrent : float\n+ photocurrent [A]\n+ * saturation_current : float\n+ dark (saturation) current [A]\n+ * resistance_shunt : float\n+ shunt (parallel) resistance, in ohms\n+ * resistance_series : float\n+ series resistance, in ohms\n+ * nNsVth : float\n+ product of thermal voltage ``Vth`` [V], diode ideality factor\n+ ``n``, and number of series cells ``Ns``\n+\n+ Raises\n+ ------\n+ RuntimeError if parameter extraction is not successful.\n+\n+ Notes\n+ -----\n+ Inputs ``voltage``, ``current``, ``v_oc``, ``i_sc`` and ``v_mp_i_mp`` are\n+ assumed to be from a single IV curve at constant irradiance and cell\n+ temperature.\n+\n+ :py:func:`fit_single_diode_sandia` obtains values for the five parameters\n+ for the single diode equation [1]:\n+\n+ .. math::\n+\n+ I = I_{L} - I_{0} (\\exp \\frac{V + I R_{s}}{nNsVth} - 1)\n+ - \\frac{V + I R_{s}}{R_{sh}}\n+\n+ See :py:func:`pvsystem.singlediode` for definition of the parameters.\n+\n+ The extraction method [2] proceeds in six steps.\n+\n+ 1. In the single diode equation, replace :math:`R_{sh} = 1/G_{p}` and\n+ re-arrange\n+\n+ .. math::\n+\n+ I = \\frac{I_{L}}{1 + G_{p} R_{s}} - \\frac{G_{p} V}{1 + G_{p} R_{s}}\n+ - \\frac{I_{0}}{1 + G_{p} R_{s}} (\\exp(\\frac{V + I R_{s}}{nNsVth}) - 1)\n+\n+ 2. The linear portion of the IV curve is defined as\n+ :math:`V \\le vlim \\times v_oc`. Over this portion of the IV curve,\n+\n+ .. math::\n+\n+ \\frac{I_{0}}{1 + G_{p} R_{s}} (\\exp(\\frac{V + I R_{s}}{nNsVth}) - 1)\n+ \\approx 0\n+\n+ 3. Fit the linear portion of the IV curve with a line.\n+\n+ .. math::\n+\n+ I &\\approx \\frac{I_{L}}{1 + G_{p} R_{s}} - \\frac{G_{p} V}{1 + G_{p}\n+ R_{s}} \\\\\n+ &= \\beta_{0} + \\beta_{1} V\n+\n+ 4. The exponential portion of the IV curve is defined by\n+ :math:`\\beta_{0} + \\beta_{1} \\times V - I > ilim \\times i_sc`.\n+ Over this portion of the curve, :math:`exp((V + IRs)/nNsVth) >> 1`\n+ so that\n+\n+ .. math::\n+\n+ \\exp(\\frac{V + I R_{s}}{nNsVth}) - 1 \\approx\n+ \\exp(\\frac{V + I R_{s}}{nNsVth})\n+\n+ 5. Fit the exponential portion of the IV curve.\n+\n+ .. math::\n+\n+ \\log(\\beta_{0} - \\beta_{1} V - I)\n+ &\\approx \\log(\\frac{I_{0}}{1 + G_{p} R_{s}} + \\frac{V}{nNsVth}\n+ + \\frac{I R_{s}}{nNsVth} \\\\\n+ &= \\beta_{2} + beta_{3} V + \\beta_{4} I\n+\n+ 6. Calculate values for ``IL, I0, Rs, Rsh,`` and ``nNsVth`` from the\n+ regression coefficents :math:`\\beta_{0}, \\beta_{1}, \\beta_{3}` and\n+ :math:`\\beta_{4}`.\n+\n+\n+ References\n+ ----------\n+ [1] S.R. Wenham, M.A. Green, M.E. Watt, \"Applied Photovoltaics\" ISBN\n+ 0 86758 909 4\n+ [2] C. B. Jones, C. W. Hansen, Single Diode Parameter Extraction from\n+ In-Field Photovoltaic I-V Curves on a Single Board Computer, 46th IEEE\n+ Photovoltaic Specialist Conference, Chicago, IL, 2019\n+ \"\"\"\n+\n+ # If not provided, extract v_oc, i_sc, v_mp and i_mp from the IV curve data\n+ if v_oc is None:\n+ v_oc = voltage[-1]\n+ if i_sc is None:\n+ i_sc = current[0]\n+ if v_mp_i_mp is not None:\n+ v_mp, i_mp = v_mp_i_mp\n+ else:\n+ v_mp, i_mp = _find_mp(voltage, current)\n+\n+ # Find beta0 and beta1 from linear portion of the IV curve\n+ beta0, beta1 = _find_beta0_beta1(voltage, current, vlim, v_oc)\n+\n+ # Find beta3 and beta4 from the exponential portion of the IV curve\n+ beta3, beta4 = _find_beta3_beta4(voltage, current, beta0, beta1, ilim,\n+ i_sc)\n+\n+ # calculate single diode parameters from regression coefficients\n+ return _calculate_sde_parameters(beta0, beta1, beta3, beta4, v_mp, i_mp,\n+ v_oc)\n+\n+\n+def _find_mp(voltage, current):\n+ \"\"\"\n+ Finds voltage and current at maximum power point.\n+\n+ Parameters\n+ ----------\n+ voltage : ndarray\n+ 1D array containing voltage at each point on the IV curve, increasing\n+ from 0 to v_oc inclusive, of `float` type [V]\n+\n+ current : ndarray\n+ 1D array containing current at each point on the IV curve, decreasing\n+ from i_sc to 0 inclusive, of `float` type [A]\n+\n+ Returns\n+ -------\n+ v_mp, i_mp : tuple\n+ voltage ``v_mp`` and current ``i_mp`` at the maximum power point [V],\n+ [A]\n+ \"\"\"\n+ p = voltage * current\n+ idx = np.argmax(p)\n+ return voltage[idx], current[idx]\n+\n+\n+def _calc_I0(IL, I, V, Gp, Rs, nNsVth):\n+ return (IL - I - Gp * V - Gp * Rs * I) / np.exp((V + Rs * I) / nNsVth)\n+\n+\n+def _find_beta0_beta1(v, i, vlim, v_oc):\n+ # Get intercept and slope of linear portion of IV curve.\n+ # Start with V =< vlim * v_oc, extend by adding points until slope is\n+ # negative (downward).\n+ beta0 = np.nan\n+ beta1 = np.nan\n+ first_idx = np.searchsorted(v, vlim * v_oc)\n+ for idx in range(first_idx, len(v)):\n+ coef = np.polyfit(v[:idx], i[:idx], deg=1)\n+ if coef[0] < 0:\n+ # intercept term\n+ beta0 = coef[1].item()\n+ # sign change of slope to get positive parameter value\n+ beta1 = -coef[0].item()\n+ break\n+ if any(np.isnan([beta0, beta1])):\n+ raise RuntimeError(\"Parameter extraction failed: beta0={}, beta1={}\"\n+ .format(beta0, beta1))\n+ else:\n+ return beta0, beta1\n+\n+\n+def _find_beta3_beta4(voltage, current, beta0, beta1, ilim, i_sc):\n+ # Subtract the IV curve from the linear fit.\n+ y = beta0 - beta1 * voltage - current\n+ x = np.array([np.ones_like(voltage), voltage, current]).T\n+ # Select points where y > ilim * i_sc to regress log(y) onto x\n+ idx = (y > ilim * i_sc)\n+ result = np.linalg.lstsq(x[idx], np.log(y[idx]), rcond=None)\n+ coef = result[0]\n+ beta3 = coef[1].item()\n+ beta4 = coef[2].item()\n+ if any(np.isnan([beta3, beta4])):\n+ raise RuntimeError(\"Parameter extraction failed: beta3={}, beta4={}\"\n+ .format(beta3, beta4))\n+ else:\n+ return beta3, beta4\n+\n+\n+def _calculate_sde_parameters(beta0, beta1, beta3, beta4, v_mp, i_mp, v_oc):\n+ nNsVth = 1.0 / beta3\n+ Rs = beta4 / beta3\n+ Gp = beta1 / (1.0 - Rs * beta1)\n+ Rsh = 1.0 / Gp\n+ IL = (1 + Gp * Rs) * beta0\n+ # calculate I0\n+ I0_vmp = _calc_I0(IL, i_mp, v_mp, Gp, Rs, nNsVth)\n+ I0_voc = _calc_I0(IL, 0, v_oc, Gp, Rs, nNsVth)\n+ if any(np.isnan([I0_vmp, I0_voc])) or ((I0_vmp <= 0) and (I0_voc <= 0)):\n+ raise RuntimeError(\"Parameter extraction failed: I0 is undetermined.\")\n+ elif (I0_vmp > 0) and (I0_voc > 0):\n+ I0 = 0.5 * (I0_vmp + I0_voc)\n+ elif (I0_vmp > 0):\n+ I0 = I0_vmp\n+ else: # I0_voc > 0\n+ I0 = I0_voc\n+ return (IL, I0, Rsh, Rs, nNsVth)\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -44,8 +44,8 @@\n TESTS_REQUIRE = ['nose', 'pytest', 'pytest-cov', 'pytest-mock',\n 'pytest-timeout']\n EXTRAS_REQUIRE = {\n- 'optional': ['ephem', 'cython', 'netcdf4', 'numba', 'pvfactors', 'scipy',\n- 'siphon', 'tables'],\n+ 'optional': ['ephem', 'cython', 'netcdf4', 'nrel-pysam', 'numba',\n+ 'pvfactors', 'scipy', 'siphon', 'tables'],\n 'doc': ['ipython', 'matplotlib', 'sphinx', 'sphinx_rtd_theme'],\n 'test': TESTS_REQUIRE\n }\n", "test_patch": "diff --git a/pvlib/test/conftest.py b/pvlib/test/conftest.py\n--- a/pvlib/test/conftest.py\n+++ b/pvlib/test/conftest.py\n@@ -151,6 +151,15 @@ def has_numba():\n reason='requires pvfactors')\n \n \n+try:\n+ import PySAM # noqa: F401\n+ has_pysam = True\n+except ImportError:\n+ has_pysam = False\n+\n+requires_pysam = pytest.mark.skipif(not has_pysam, reason=\"requires PySAM\")\n+\n+\n @pytest.fixture(scope=\"session\")\n def sam_data():\n data = {}\ndiff --git a/pvlib/test/test_ivtools.py b/pvlib/test/test_ivtools.py\nnew file mode 100644\n--- /dev/null\n+++ b/pvlib/test/test_ivtools.py\n@@ -0,0 +1,242 @@\n+# -*- coding: utf-8 -*-\n+\"\"\"\n+Created on Thu May 9 10:51:15 2019\n+\n+@author: cwhanse\n+\"\"\"\n+\n+import numpy as np\n+import pandas as pd\n+import pytest\n+from pvlib import pvsystem\n+from pvlib import ivtools\n+from pvlib.test.conftest import requires_scipy, requires_pysam\n+\n+\[email protected]\n+def get_test_iv_params():\n+ return {'IL': 8.0, 'I0': 5e-10, 'Rsh': 1000, 'Rs': 0.2, 'nNsVth': 1.61864}\n+\n+\[email protected]\n+def get_cec_params_cansol_cs5p_220p():\n+ return {'input': {'V_mp_ref': 46.6, 'I_mp_ref': 4.73, 'V_oc_ref': 58.3,\n+ 'I_sc_ref': 5.05, 'alpha_sc': 0.0025,\n+ 'beta_voc': -0.19659, 'gamma_pmp': -0.43,\n+ 'cells_in_series': 96},\n+ 'output': {'a_ref': 2.3674, 'I_L_ref': 5.056, 'I_o_ref': 1.01e-10,\n+ 'R_sh_ref': 837.51, 'R_s': 1.004, 'Adjust': 2.3}}\n+\n+\n+@requires_scipy\n+def test_fit_sde_sandia(get_test_iv_params, get_bad_iv_curves):\n+ test_params = get_test_iv_params\n+ testcurve = pvsystem.singlediode(photocurrent=test_params['IL'],\n+ saturation_current=test_params['I0'],\n+ resistance_shunt=test_params['Rsh'],\n+ resistance_series=test_params['Rs'],\n+ nNsVth=test_params['nNsVth'],\n+ ivcurve_pnts=300)\n+ expected = tuple(test_params[k] for k in ['IL', 'I0', 'Rsh', 'Rs',\n+ 'nNsVth'])\n+ result = ivtools.fit_sde_sandia(voltage=testcurve['v'],\n+ current=testcurve['i'])\n+ assert np.allclose(result, expected, rtol=5e-5)\n+ result = ivtools.fit_sde_sandia(voltage=testcurve['v'],\n+ current=testcurve['i'],\n+ v_oc=testcurve['v_oc'],\n+ i_sc=testcurve['i_sc'])\n+ assert np.allclose(result, expected, rtol=5e-5)\n+ result = ivtools.fit_sde_sandia(voltage=testcurve['v'],\n+ current=testcurve['i'],\n+ v_oc=testcurve['v_oc'],\n+ i_sc=testcurve['i_sc'],\n+ v_mp_i_mp=(testcurve['v_mp'],\n+ testcurve['i_mp']))\n+ assert np.allclose(result, expected, rtol=5e-5)\n+ result = ivtools.fit_sde_sandia(voltage=testcurve['v'],\n+ current=testcurve['i'], vlim=0.1)\n+ assert np.allclose(result, expected, rtol=5e-5)\n+\n+\n+@requires_scipy\n+def test_fit_sde_sandia_bad_iv(get_bad_iv_curves):\n+ # bad IV curves for coverage of if/then in _calculate_sde_parameters\n+ v1, i1, v2, i2 = get_bad_iv_curves\n+ result = ivtools.fit_sde_sandia(voltage=v1, current=i1)\n+ assert np.allclose(result, (-2.4322856072799985, 8.854688976836396,\n+ -63.56227601452038, 111.18558915546389,\n+ -137.9965046659527))\n+ result = ivtools.fit_sde_sandia(voltage=v2, current=i2)\n+ assert np.allclose(result, (2.62405311949227, 1.8657963912925288,\n+ 110.35202827739991, -65.652554411442,\n+ 174.49362093001415))\n+\n+\n+@requires_pysam\n+def test_fit_sdm_cec_sam(get_cec_params_cansol_cs5p_220p):\n+ input_data = get_cec_params_cansol_cs5p_220p['input']\n+ I_L_ref, I_o_ref, R_sh_ref, R_s, a_ref, Adjust = \\\n+ ivtools.fit_sdm_cec_sam(\n+ celltype='polySi', v_mp=input_data['V_mp_ref'],\n+ i_mp=input_data['I_mp_ref'], v_oc=input_data['V_oc_ref'],\n+ i_sc=input_data['I_sc_ref'], alpha_sc=input_data['alpha_sc'],\n+ beta_voc=input_data['beta_voc'],\n+ gamma_pmp=input_data['gamma_pmp'],\n+ cells_in_series=input_data['cells_in_series'])\n+ expected = pd.Series(get_cec_params_cansol_cs5p_220p['output'])\n+ modeled = pd.Series(index=expected.index, data=np.nan)\n+ modeled['a_ref'] = a_ref\n+ modeled['I_L_ref'] = I_L_ref\n+ modeled['I_o_ref'] = I_o_ref\n+ modeled['R_sh_ref'] = R_sh_ref\n+ modeled['R_s'] = R_s\n+ modeled['Adjust'] = Adjust\n+ assert np.allclose(modeled.values, expected.values, rtol=5e-2)\n+ # test for fitting failure\n+ with pytest.raises(RuntimeError):\n+ I_L_ref, I_o_ref, R_sh_ref, R_s, a_ref, Adjust = \\\n+ ivtools.fit_sdm_cec_sam(\n+ celltype='polySi', v_mp=0.45, i_mp=5.25, v_oc=0.55, i_sc=5.5,\n+ alpha_sc=0.00275, beta_voc=0.00275, gamma_pmp=0.0055,\n+ cells_in_series=1, temp_ref=25)\n+\n+\[email protected]\n+def get_bad_iv_curves():\n+ # v1, i1 produces a bad value for I0_voc\n+ v1 = np.array([0, 0.338798867469060, 0.677597734938121, 1.01639660240718,\n+ 1.35519546987624, 1.69399433734530, 2.03279320481436,\n+ 2.37159207228342, 2.71039093975248, 3.04918980722154,\n+ 3.38798867469060, 3.72678754215966, 4.06558640962873,\n+ 4.40438527709779, 4.74318414456685, 5.08198301203591,\n+ 5.42078187950497, 5.75958074697403, 6.09837961444309,\n+ 6.43717848191215, 6.77597734938121, 7.11477621685027,\n+ 7.45357508431933, 7.79237395178839, 8.13117281925745,\n+ 8.46997168672651, 8.80877055419557, 9.14756942166463,\n+ 9.48636828913369, 9.82516715660275, 10.1639660240718,\n+ 10.5027648915409, 10.8415637590099, 11.1803626264790,\n+ 11.5191614939481, 11.8579603614171, 12.1967592288862,\n+ 12.5355580963552, 12.8743569638243, 13.2131558312934,\n+ 13.5519546987624, 13.8907535662315, 14.2295524337005,\n+ 14.5683513011696, 14.9071501686387, 15.2459490361077,\n+ 15.5847479035768, 15.9235467710458, 16.2623456385149,\n+ 16.6011445059840, 16.9399433734530, 17.2787422409221,\n+ 17.6175411083911, 17.9563399758602, 18.2951388433293,\n+ 18.6339377107983, 18.9727365782674, 19.3115354457364,\n+ 19.6503343132055, 19.9891331806746, 20.3279320481436,\n+ 20.6667309156127, 21.0055297830817, 21.3443286505508,\n+ 21.6831275180199, 22.0219263854889, 22.3607252529580,\n+ 22.6995241204270, 23.0383229878961, 23.3771218553652,\n+ 23.7159207228342, 24.0547195903033, 24.3935184577724,\n+ 24.7323173252414, 25.0711161927105, 25.4099150601795,\n+ 25.7487139276486, 26.0875127951177, 26.4263116625867,\n+ 26.7651105300558, 27.1039093975248, 27.4427082649939,\n+ 27.7815071324630, 28.1203059999320, 28.4591048674011,\n+ 28.7979037348701, 29.1367026023392, 29.4755014698083,\n+ 29.8143003372773, 30.1530992047464, 30.4918980722154,\n+ 30.8306969396845, 31.1694958071536, 31.5082946746226,\n+ 31.8470935420917, 32.1858924095607, 32.5246912770298,\n+ 32.8634901444989, 33.2022890119679, 33.5410878794370])\n+ i1 = np.array([3.39430882774470, 2.80864492110761, 3.28358165429196,\n+ 3.41191190551673, 3.11975662808148, 3.35436585834612,\n+ 3.23953272899809, 3.60307083325333, 2.80478101508277,\n+ 2.80505102853845, 3.16918996870373, 3.21088388439857,\n+ 3.46332865310431, 3.09224155015883, 3.17541550741062,\n+ 3.32470179290389, 3.33224664316240, 3.07709000050741,\n+ 2.89141245343405, 3.01365768561537, 3.23265176770231,\n+ 3.32253647634228, 2.97900657569736, 3.31959549243966,\n+ 3.03375461550111, 2.97579298978937, 3.25432831375159,\n+ 2.89178382564454, 3.00341909207567, 3.72637492250097,\n+ 3.28379856976360, 2.96516169245835, 3.25658381110230,\n+ 3.41655911533139, 3.02718097944604, 3.11458376760376,\n+ 3.24617304369762, 3.45935502367636, 3.21557333256913,\n+ 3.27611176482650, 2.86954135732485, 3.32416319254657,\n+ 3.15277467598732, 3.08272557013770, 3.15602202666259,\n+ 3.49432799877150, 3.53863997177632, 3.10602611478455,\n+ 3.05373911151821, 3.09876772570781, 2.97417228624287,\n+ 2.84573593699237, 3.16288578405195, 3.06533173612783,\n+ 3.02118336639575, 3.34374977225502, 2.97255164138821,\n+ 3.19286135682863, 3.10999753817133, 3.26925354620079,\n+ 3.11957809501529, 3.20155017481720, 3.31724984405837,\n+ 3.42879043512927, 3.17933067619240, 3.47777362613969,\n+ 3.20708912539777, 3.48205761174907, 3.16804363684327,\n+ 3.14055472378230, 3.13445657434470, 2.91152696252998,\n+ 3.10984113847427, 2.80443349399489, 3.23146278164875,\n+ 2.94521083406108, 3.17388903141715, 3.05930294897030,\n+ 3.18985234673287, 3.27946609274898, 3.33717523113602,\n+ 2.76394303462702, 3.19375132937510, 2.82628616689450,\n+ 2.85238527394143, 2.82975892599489, 2.79196912313914,\n+ 2.72860792049395, 2.75585977414140, 2.44280222448805,\n+ 2.36052347370628, 2.26785071765738, 2.10868255743462,\n+ 2.06165739407987, 1.90047259509385, 1.39925575828709,\n+ 1.24749015957606, 0.867823806536762, 0.432752457749993, 0])\n+ # v2, i2 produces a bad value for I0_vmp\n+ v2 = np.array([0, 0.365686097622586, 0.731372195245173, 1.09705829286776,\n+ 1.46274439049035, 1.82843048811293, 2.19411658573552,\n+ 2.55980268335810, 2.92548878098069, 3.29117487860328,\n+ 3.65686097622586, 4.02254707384845, 4.38823317147104,\n+ 4.75391926909362, 5.11960536671621, 5.48529146433880,\n+ 5.85097756196138, 6.21666365958397, 6.58234975720655,\n+ 6.94803585482914, 7.31372195245173, 7.67940805007431,\n+ 8.04509414769690, 8.41078024531949, 8.77646634294207,\n+ 9.14215244056466, 9.50783853818725, 9.87352463580983,\n+ 10.2392107334324, 10.6048968310550, 10.9705829286776,\n+ 11.3362690263002, 11.7019551239228, 12.0676412215454,\n+ 12.4333273191679, 12.7990134167905, 13.1646995144131,\n+ 13.5303856120357, 13.8960717096583, 14.2617578072809,\n+ 14.6274439049035, 14.9931300025260, 15.3588161001486,\n+ 15.7245021977712, 16.0901882953938, 16.4558743930164,\n+ 16.8215604906390, 17.1872465882616, 17.5529326858841,\n+ 17.9186187835067, 18.2843048811293, 18.6499909787519,\n+ 19.0156770763745, 19.3813631739971, 19.7470492716197,\n+ 20.1127353692422, 20.4784214668648, 20.8441075644874,\n+ 21.2097936621100, 21.5754797597326, 21.9411658573552,\n+ 22.3068519549778, 22.6725380526004, 23.0382241502229,\n+ 23.4039102478455, 23.7695963454681, 24.1352824430907,\n+ 24.5009685407133, 24.8666546383359, 25.2323407359585,\n+ 25.5980268335810, 25.9637129312036, 26.3293990288262,\n+ 26.6950851264488, 27.0607712240714, 27.4264573216940,\n+ 27.7921434193166, 28.1578295169392, 28.5235156145617,\n+ 28.8892017121843, 29.2548878098069, 29.6205739074295,\n+ 29.9862600050521, 30.3519461026747, 30.7176322002973,\n+ 31.0833182979198, 31.4490043955424, 31.8146904931650,\n+ 32.1803765907876, 32.5460626884102, 32.9117487860328,\n+ 33.2774348836554, 33.6431209812779, 34.0088070789005,\n+ 34.3744931765231, 34.7401792741457, 35.1058653717683,\n+ 35.4715514693909, 35.8372375670135, 36.2029236646360])\n+ i2 = np.array([6.49218806928330, 6.49139336899548, 6.17810697175204,\n+ 6.75197816263663, 6.59529074137515, 6.18164578868300,\n+ 6.38709397931910, 6.30685422248427, 6.44640615548925,\n+ 6.88727230397772, 6.42074852785591, 6.46348580823746,\n+ 6.38642309763941, 5.66356277572311, 6.61010381702082,\n+ 6.33288284311125, 6.22475343933610, 6.30651399433833,\n+ 6.44435022944051, 6.43741711131908, 6.03536180208946,\n+ 6.23814639328170, 5.97229140403242, 6.20790000748341,\n+ 6.22933550182341, 6.22992127804882, 6.13400871899299,\n+ 6.83491312449950, 6.07952797245846, 6.35837746415450,\n+ 6.41972128662324, 6.85256717258275, 6.25807797296759,\n+ 6.25124948151766, 6.22229212812413, 6.72249444167406,\n+ 6.41085549981649, 6.75792874870056, 6.22096181559171,\n+ 6.47839564388996, 6.56010208597432, 6.63300966556949,\n+ 6.34617546039339, 6.79812221146153, 6.14486056194136,\n+ 6.14979256889311, 6.16883037644880, 6.57309183229605,\n+ 6.40064681038509, 6.18861448239873, 6.91340138179698,\n+ 5.94164388433788, 6.23638991745862, 6.31898940411710,\n+ 6.45247884556830, 6.58081455524297, 6.64915284801713,\n+ 6.07122119270245, 6.41398258148256, 6.62144271089614,\n+ 6.36377197712687, 6.51487678829345, 6.53418950147730,\n+ 6.18886469125371, 6.26341063475750, 6.83488211680259,\n+ 6.62699397226695, 6.41286837534735, 6.44060085001851,\n+ 6.48114130629288, 6.18607038456406, 6.16923370572396,\n+ 6.64223126283631, 6.07231852289266, 5.79043710204375,\n+ 6.48463886529882, 6.36263392044401, 6.11212476454494,\n+ 6.14573900812925, 6.12568047243240, 6.43836230231577,\n+ 6.02505694060219, 6.13819468942244, 6.22100593815064,\n+ 6.02394682666345, 5.89016573063789, 5.74448527739202,\n+ 5.50415294280017, 5.31883018164157, 4.87476769510305,\n+ 4.74386713755523, 4.60638346931628, 4.06177345572680,\n+ 3.73334482123538, 3.13848311672243, 2.71638862600768,\n+ 2.02963773590165, 1.49291145092070, 0.818343889647352, 0])\n+\n+ return v1, i1, v2, i2\n", "problem_statement": "CEC 6-parameter coefficient generation\nSAM is able to extract the CEC parameters required for calcparams_desoto. This is done through the 'CEC Performance Model with User Entered Specifications' module model, and coefficients are automatically extracted given nameplate parameters Voc, Isc, Imp, Vmp and TempCoeff. The method is based on Aron Dobos' \"An Improved Coefficient Calculator for the California Energy Commission 6 Parameter Photovoltaic Module Model \", 2012\r\n\r\nIdeally we should be able to work with the SAM open source code, extract the bit that does the coefficient generation, and put it into a PVLib function that would allow users to run calcparams_desoto with any arbitrary module type. At the moment we are dependent on PV modules loaded into the SAM or CEC database.\r\n\r\nThank you!\r\n\n", "hints_text": "SAM solution routine is located at https://github.com/NREL/ssc/blob/develop/shared/6par_solve.h , function \"solve_with_sanity_and_heuristics\" . Additional dependencies on other files 6par_newton.h, 6par_search.h, 6par_jacobian.h, 6par_lu.h, 6par_gamma.h, all located in https://github.com/NREL/ssc/tree/develop/shared . \nI'd like to try to take this up sometime soon, maybe by the end of the year? Is anyone else working on it? I haven't seen a PR. Does anyone have any strong opinions? Is seems like there's a SAM implementation, is there a PVLIB-MATLAB version already? thx\nI'm not working on it. If it is practical, it would be great to wrap the SAM method. NREL put a lot of effort into the heuristics for initial values and updating. We have a function in PVLib for MATLAB but it's a very different algorithm. For consistency with the parameter databases it would be better to use the SAM algorithm.\nDo I read between the lines that the two algorithms do not converge on the same parameters? Then it would be of great interest to have python implementations of each! Or perhaps even more important: documents describing the full algorithms along with every heuristic, assumption and constraint they implement...\n@adriesse yes. Each model fitting algorithm I'm aware of, will produce different parameter values from the same data although the predicted IV curves may be similar.\nFWIW I am trying to establish a common/fair metric to compare different model fits in PVfit. In addition to choosing, say, which residual(s) to analyze, the effect of model discrepancy significantly affects such comparisons. PVfit\u2019s orthogonal distance regression (ODR) fits to the single-diode model (SDM) often are worse than other algorithms\u2019 fits in terms of terminal current residuals, but I have observed consistently that this is likely due to model discrepancy. One might claim that ODR is being more \u201chonest\u201d here, but I think it really means that the model should be improved. Note that PVfit\u2019s ODR alternatively optimizes the residual of the sum of currents at the high-voltage diode node in the equivalent-circuit model, and it doesn\u2019t make unfounded assumptions about error-free measurements in all data channels except the terminal current (which also has implications for parameter non-identifiability). I have seen plenty of evidence that ODR fits are \u201cgood\u201d in the absence of significant model discrepancy, such as for some (but not all!) double-diode model (DDM) fits across various material systems. \n> If it is practical, it would be great to wrap the SAM method. \r\n\r\nTwo kinds of practicalities here:\r\n\r\n1. Technical. I don't know how to do it but I am sure it's possible. I am ok with it so long as pvlib remains straightforward to install from source.\r\n2. Legal. We would need assurance from NREL that it's ok for pvlib to distribute this SAM code under the terms of a MIT license rather than SAM's mixed MIT/GPL license.\r\n\nIn the next 6-8 months, the NREL team will be updating our python wrapper for the SAM software development kit so that you can pip install the sam-sdk and call its routines in a much more native pythonic fashion. That might be a quick way to implement the CEC parameter generation to solve both the technical and legal practicalities Will mentions above, as well as the many file dependencies involved with that routine. The SDK is licensed separately from the SAM open source code under an MIT type license, so that distribution with pvlib would be ok, and once we have it set up as a python package, that should make it a non-issue to include with pvlib installation from source. \r\n\r\nTo @adriesse 's point, the publication associated with the method implemented in SAM is here: http://solarenergyengineering.asmedigitalcollection.asme.org/article.aspx?articleid=1458865 \nThanks @janinefreeman that is great news!\n@janinefreeman Does NREL's web site no longer provide free preprints of Aron's paper?\n@thunderfish24 I'm not finding a copy of it in NREL's pubs database, but it looks like you may be able to get it here (didn't create an account to give it a try): https://www.osti.gov/biblio/1043759 \n@thunderfish24 I sent you a preprint.", "created_at": "2019-05-13T14:43:11Z", "version": "0.5", "FAIL_TO_PASS": ["pvlib/test/test_ivtools.py::test_fit_sde_sandia", "pvlib/test/test_ivtools.py::test_fit_sde_sandia_bad_iv"], "PASS_TO_PASS": [], "environment_setup_commit": "84818c6d950142927359ffe308c728a0c080ddce"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1653", "base_commit": "faf27fee1fcbae3b7056bd02f9e98b7d6e5cb42d", "patch": "diff --git a/pvlib/snow.py b/pvlib/snow.py\n--- a/pvlib/snow.py\n+++ b/pvlib/snow.py\n@@ -219,7 +219,7 @@ def _townsend_effective_snow(snow_total, snow_events):\n \n def loss_townsend(snow_total, snow_events, surface_tilt, relative_humidity,\n temp_air, poa_global, slant_height, lower_edge_height,\n- angle_of_repose=40):\n+ string_factor=1.0, angle_of_repose=40):\n '''\n Calculates monthly snow loss based on the Townsend monthly snow loss\n model [1]_.\n@@ -230,7 +230,8 @@ def loss_townsend(snow_total, snow_events, surface_tilt, relative_humidity,\n Snow received each month. Referred to as S in [1]_. [cm]\n \n snow_events : array-like\n- Number of snowfall events each month. Referred to as N in [1]_. [-]\n+ Number of snowfall events each month. May be int or float type for\n+ the average events in a typical month. Referred to as N in [1]_.\n \n surface_tilt : float\n Tilt angle of the array. [deg]\n@@ -250,6 +251,11 @@ def loss_townsend(snow_total, snow_events, surface_tilt, relative_humidity,\n lower_edge_height : float\n Distance from array lower edge to the ground. [m]\n \n+ string_factor : float, default 1.0\n+ Multiplier applied to monthly loss fraction. Use 1.0 if the DC array\n+ has only one string of modules in the slant direction, use 0.75\n+ otherwise. [-]\n+\n angle_of_repose : float, default 40\n Piled snow angle, assumed to stabilize at 40\u00b0, the midpoint of\n 25\u00b0-55\u00b0 avalanching slope angles. [deg]\n@@ -263,7 +269,12 @@ def loss_townsend(snow_total, snow_events, surface_tilt, relative_humidity,\n -----\n This model has not been validated for tracking arrays; however, for\n tracking arrays [1]_ suggests using the maximum rotation angle in place\n- of ``surface_tilt``.\n+ of ``surface_tilt``. The author of [1]_ recommends using one-half the\n+ table width for ``slant_height``, i.e., the distance from the tracker\n+ axis to the module edge.\n+\n+ The parameter `string_factor` is an enhancement added to the model after\n+ publication of [1]_ per private communication with the model's author.\n \n References\n ----------\n@@ -273,13 +284,22 @@ def loss_townsend(snow_total, snow_events, surface_tilt, relative_humidity,\n :doi:`10.1109/PVSC.2011.6186627`\n '''\n \n+ # unit conversions from cm and m to in, from C to K, and from % to fraction\n+ # doing this early to facilitate comparison of this code with [1]\n+ snow_total_inches = snow_total / 2.54 # to inches\n+ relative_humidity_fraction = relative_humidity / 100.\n+ poa_global_kWh = poa_global / 1000.\n+ slant_height_inches = slant_height * 39.37\n+ lower_edge_height_inches = lower_edge_height * 39.37\n+ temp_air_kelvin = temp_air + 273.15\n+\n C1 = 5.7e04\n C2 = 0.51\n \n- snow_total_prev = np.roll(snow_total, 1)\n+ snow_total_prev = np.roll(snow_total_inches, 1)\n snow_events_prev = np.roll(snow_events, 1)\n \n- effective_snow = _townsend_effective_snow(snow_total, snow_events)\n+ effective_snow = _townsend_effective_snow(snow_total_inches, snow_events)\n effective_snow_prev = _townsend_effective_snow(\n snow_total_prev,\n snow_events_prev\n@@ -288,37 +308,38 @@ def loss_townsend(snow_total, snow_events, surface_tilt, relative_humidity,\n 1 / 3 * effective_snow_prev\n + 2 / 3 * effective_snow\n )\n- effective_snow_weighted_m = effective_snow_weighted / 100\n \n- lower_edge_height_clipped = np.maximum(lower_edge_height, 0.01)\n+ # the lower limit of 0.1 in^2 is per private communication with the model's\n+ # author. CWH 1/30/2023\n+ lower_edge_distance = np.clip(\n+ lower_edge_height_inches**2 - effective_snow_weighted**2, a_min=0.1,\n+ a_max=None)\n gamma = (\n- slant_height\n- * effective_snow_weighted_m\n+ slant_height_inches\n+ * effective_snow_weighted\n * cosd(surface_tilt)\n- / (lower_edge_height_clipped**2 - effective_snow_weighted_m**2)\n+ / lower_edge_distance\n * 2\n * tand(angle_of_repose)\n )\n \n ground_interference_term = 1 - C2 * np.exp(-gamma)\n- relative_humidity_fraction = relative_humidity / 100\n- temp_air_kelvin = temp_air + 273.15\n- effective_snow_weighted_in = effective_snow_weighted / 2.54\n- poa_global_kWh = poa_global / 1000\n \n # Calculate Eqn. 3 in the reference.\n # Although the reference says Eqn. 3 calculates percentage loss, the y-axis\n # of Figure 7 indicates Eqn. 3 calculates fractional loss. Since the slope\n # of the line in Figure 7 is the same as C1 in Eqn. 3, it is assumed that\n # Eqn. 3 calculates fractional loss.\n+\n loss_fraction = (\n C1\n- * effective_snow_weighted_in\n+ * effective_snow_weighted\n * cosd(surface_tilt)**2\n * ground_interference_term\n * relative_humidity_fraction\n / temp_air_kelvin**2\n / poa_global_kWh**0.67\n+ * string_factor\n )\n \n return np.clip(loss_fraction, 0, 1)\n", "test_patch": "diff --git a/pvlib/tests/test_snow.py b/pvlib/tests/test_snow.py\n--- a/pvlib/tests/test_snow.py\n+++ b/pvlib/tests/test_snow.py\n@@ -6,6 +6,8 @@\n from pvlib import snow\n from pvlib.tools import sind\n \n+import pytest\n+\n \n def test_fully_covered_nrel():\n dt = pd.date_range(start=\"2019-1-1 12:00:00\", end=\"2019-1-1 18:00:00\",\n@@ -108,6 +110,7 @@ def test__townsend_effective_snow():\n \n \n def test_loss_townsend():\n+ # hand-calculated solution\n snow_total = np.array([25.4, 25.4, 12.7, 2.54, 0, 0, 0, 0, 0, 0, 12.7,\n 25.4])\n snow_events = np.array([2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 2, 3])\n@@ -118,6 +121,7 @@ def test_loss_townsend():\n poa_global = np.array([350000, 350000, 350000, 350000, 350000, 350000,\n 350000, 350000, 350000, 350000, 350000, 350000])\n angle_of_repose = 40\n+ string_factor = 1.0\n slant_height = 2.54\n lower_edge_height = 0.254\n expected = np.array([0.07696253, 0.07992262, 0.06216201, 0.01715392, 0, 0,\n@@ -125,5 +129,84 @@ def test_loss_townsend():\n actual = snow.loss_townsend(snow_total, snow_events, surface_tilt,\n relative_humidity, temp_air,\n poa_global, slant_height,\n- lower_edge_height, angle_of_repose)\n+ lower_edge_height, string_factor,\n+ angle_of_repose)\n np.testing.assert_allclose(expected, actual, rtol=1e-05)\n+\n+\[email protected](\n+ 'poa_global,surface_tilt,slant_height,lower_edge_height,string_factor,expected', # noQA: E501\n+ [\n+ (np.asarray(\n+ [60., 80., 100., 125., 175., 225., 225., 210., 175., 125., 90.,\n+ 60.], dtype=float) * 1000.,\n+ 2.,\n+ 79. / 39.37,\n+ 3. / 39.37,\n+ 1.0,\n+ np.asarray(\n+ [44, 34, 20, 9, 3, 1, 0, 0, 0, 2, 6, 25], dtype=float)\n+ ),\n+ (np.asarray(\n+ [60., 80., 100., 125., 175., 225., 225., 210., 175., 125., 90.,\n+ 60.], dtype=float) * 1000.,\n+ 5.,\n+ 316 / 39.37,\n+ 120. / 39.37,\n+ 0.75,\n+ np.asarray(\n+ [22, 16, 9, 4, 1, 0, 0, 0, 0, 1, 2, 12], dtype=float)\n+ ),\n+ (np.asarray(\n+ [60., 80., 100., 125., 175., 225., 225., 210., 175., 125., 90.,\n+ 60.], dtype=float) * 1000.,\n+ 23.,\n+ 158 / 39.27,\n+ 12 / 39.37,\n+ 0.75,\n+ np.asarray(\n+ [28, 21, 13, 6, 2, 0, 0, 0, 0, 1, 4, 16], dtype=float)\n+ ),\n+ (np.asarray(\n+ [80., 100., 125., 150., 225., 300., 300., 275., 225., 150., 115.,\n+ 80.], dtype=float) * 1000.,\n+ 52.,\n+ 39.5 / 39.37,\n+ 34. / 39.37,\n+ 0.75,\n+ np.asarray(\n+ [7, 5, 3, 1, 0, 0, 0, 0, 0, 0, 1, 4], dtype=float)\n+ ),\n+ (np.asarray(\n+ [80., 100., 125., 150., 225., 300., 300., 275., 225., 150., 115.,\n+ 80.], dtype=float) * 1000.,\n+ 60.,\n+ 39.5 / 39.37,\n+ 25. / 39.37,\n+ 1.,\n+ np.asarray(\n+ [7, 5, 3, 1, 0, 0, 0, 0, 0, 0, 1, 3], dtype=float)\n+ )\n+ ]\n+)\n+def test_loss_townsend_cases(poa_global, surface_tilt, slant_height,\n+ lower_edge_height, string_factor, expected):\n+ # test cases from Townsend, 1/27/2023, addeed by cwh\n+ # snow_total in inches, convert to cm for pvlib\n+ snow_total = np.asarray(\n+ [20, 15, 10, 4, 1.5, 0, 0, 0, 0, 1.5, 4, 15], dtype=float) * 2.54\n+ # snow events are an average for each month\n+ snow_events = np.asarray(\n+ [5, 4.2, 2.8, 1.3, 0.8, 0, 0, 0, 0, 0.5, 1.5, 4.5], dtype=float)\n+ # air temperature in C\n+ temp_air = np.asarray(\n+ [-6., -2., 1., 4., 7., 10., 13., 16., 14., 12., 7., -3.], dtype=float)\n+ # relative humidity in %\n+ relative_humidity = np.asarray(\n+ [78., 80., 75., 65., 60., 55., 55., 55., 50., 55., 60., 70.],\n+ dtype=float)\n+ actual = snow.loss_townsend(\n+ snow_total, snow_events, surface_tilt, relative_humidity, temp_air,\n+ poa_global, slant_height, lower_edge_height, string_factor)\n+ actual = np.around(actual * 100)\n+ assert np.allclose(expected, actual)\n", "problem_statement": "Corrections to Townsend snow model\nPrivate communications with the model's author have turned up some issues with the pvlib implementation. Chief among the issues is this part of the calculation:\r\n\r\n```\r\n lower_edge_height_clipped = np.maximum(lower_edge_height, 0.01)\r\n gamma = (\r\n slant_height\r\n * effective_snow_weighted_m\r\n * cosd(surface_tilt)\r\n / (lower_edge_height_clipped**2 - effective_snow_weighted_m**2)\r\n * 2\r\n * tand(angle_of_repose)\r\n )\r\n\r\n ground_interference_term = 1 - C2 * np.exp(-gamma)\r\n```\r\n\r\nWhen `lower_edge_height_clipped` < `effective_snow_weighted_m`, `gamma` < 0 and the `ground_interference_term` can become negative. In contrast, the author's intent is that C2 < `ground_interference_terms` < 1. The author recommends clipping the squared difference (lower bound being worked out but will be something like 0.01.).\r\n\r\nOther issues appear to arise from the unit conversions. The published model uses inches for distance and snow depth. The pvlib code uses cm for snow depth (convenience for working with external snow data) and m for distances (for consistency with the rest of pvlib). After several steps, including the `ground_interference_term` calculation, the code converts from cm or m to inches to apply the final formula for loss (since the formula involves some coefficients determined by a regression). It would be easier to trace the pvlib code back to the paper if the internal unit conversions (from cm / m to inches) were done earlier.\r\n\n", "hints_text": "Interestingly, clamping the difference of squares at 0.01 was part of the original PR but got lost along the way: https://github.com/pvlib/pvlib-python/pull/1251#discussion_r830258000\r\n\r\nIt would be great if the communication with the author results in improved tests as well as improved code.\nAfter communications with the author, the pvlib code is missing two items:\r\n\r\n- a lower bound on `lower_edge_height_clipped**2 - effective_snow_weighted_m**2` which the author specifies should be 0.1 in^2.\r\n- a factor that multiplies the monthly loss fraction, to represent the potential for a string of modules at the top of the slanted array to generate power while strings at lower positions are still affected by snow. This factor was brought up in #1625 \r\n\r\nNeither is documented in the 2011 paper but should be added to 1) prevent unreasonably low loss values (item 1) and to better represent the loss for systems with multiple, horizontally-oriented strings.\r\n\r\nAlso, the author recommends advising users to enter 1/2 the total module width as the slant_height for single-axis tracked systems, which makes sense to me, as snow could slide off either surface depending on its rotation. ", "created_at": "2023-01-28T00:30:44Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_snow.py::test_loss_townsend", "pvlib/tests/test_snow.py::test_loss_townsend_cases[poa_global0-2.0-2.0066040132080265-0.07620015240030481-1.0-expected0]", "pvlib/tests/test_snow.py::test_loss_townsend_cases[poa_global1-5.0-8.026416052832106-3.0480060960121924-0.75-expected1]", "pvlib/tests/test_snow.py::test_loss_townsend_cases[poa_global2-23.0-4.023427552839317-0.30480060960121924-0.75-expected2]", "pvlib/tests/test_snow.py::test_loss_townsend_cases[poa_global4-60.0-1.0033020066040133-0.63500127000254-1.0-expected4]"], "PASS_TO_PASS": ["pvlib/tests/test_snow.py::test_fully_covered_nrel", "pvlib/tests/test_snow.py::test_coverage_nrel_hourly", "pvlib/tests/test_snow.py::test_coverage_nrel_subhourly", "pvlib/tests/test_snow.py::test_fully_covered_nrel_irregular", "pvlib/tests/test_snow.py::test_coverage_nrel_initial", "pvlib/tests/test_snow.py::test_dc_loss_nrel", "pvlib/tests/test_snow.py::test__townsend_effective_snow", "pvlib/tests/test_snow.py::test_loss_townsend_cases[poa_global3-52.0-1.0033020066040133-0.8636017272034545-0.75-expected3]"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1854", "base_commit": "27a3a07ebc84b11014d3753e4923902adf9a38c0", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -101,10 +101,11 @@ class PVSystem:\n \n Parameters\n ----------\n- arrays : iterable of Array, optional\n- List of arrays that are part of the system. If not specified\n- a single array is created from the other parameters (e.g.\n- `surface_tilt`, `surface_azimuth`). Must contain at least one Array,\n+ arrays : Array or iterable of Array, optional\n+ An Array or list of arrays that are part of the system. If not\n+ specified a single array is created from the other parameters (e.g.\n+ `surface_tilt`, `surface_azimuth`). If specified as a list, the list\n+ must contain at least one Array;\n if length of arrays is 0 a ValueError is raised. If `arrays` is\n specified the following PVSystem parameters are ignored:\n \n@@ -220,6 +221,8 @@ def __init__(self,\n strings_per_inverter,\n array_losses_parameters,\n ),)\n+ elif isinstance(arrays, Array):\n+ self.arrays = (arrays,)\n elif len(arrays) == 0:\n raise ValueError(\"PVSystem must have at least one Array. \"\n \"If you want to create a PVSystem instance \"\n", "test_patch": "diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -1887,8 +1887,6 @@ def test_PVSystem_multiple_array_creation():\n assert pv_system.arrays[0].module_parameters == {}\n assert pv_system.arrays[1].module_parameters == {'pdc0': 1}\n assert pv_system.arrays == (array_one, array_two)\n- with pytest.raises(TypeError):\n- pvsystem.PVSystem(arrays=array_one)\n \n \n def test_PVSystem_get_aoi():\n@@ -2362,6 +2360,14 @@ def test_PVSystem_at_least_one_array():\n pvsystem.PVSystem(arrays=[])\n \n \n+def test_PVSystem_single_array():\n+ # GH 1831\n+ single_array = pvsystem.Array(pvsystem.FixedMount())\n+ system = pvsystem.PVSystem(arrays=single_array)\n+ assert isinstance(system.arrays, tuple)\n+ assert system.arrays[0] is single_array\n+\n+\n def test_combine_loss_factors():\n test_index = pd.date_range(start='1990/01/01T12:00', periods=365, freq='D')\n loss_1 = pd.Series(.10, index=test_index)\n", "problem_statement": "PVSystem with single Array generates an error\n**Is your feature request related to a problem? Please describe.**\r\n\r\nWhen a PVSystem has a single Array, you can't assign just the Array instance when constructing the PVSystem.\r\n\r\n```\r\nmount = pvlib.pvsystem.FixedMount(surface_tilt=35, surface_azimuth=180)\r\narray = pvlib.pvsystem.Array(mount=mount)\r\npv = pvlib.pvsystem.PVSystem(arrays=array)\r\n\r\n---------------------------------------------------------------------------\r\nTypeError Traceback (most recent call last)\r\n<ipython-input-13-f5424e3db16a> in <module>\r\n 3 mount = pvlib.pvsystem.FixedMount(surface_tilt=35, surface_azimuth=180)\r\n 4 array = pvlib.pvsystem.Array(mount=mount)\r\n----> 5 pv = pvlib.pvsystem.PVSystem(arrays=array)\r\n\r\n~\\anaconda3\\lib\\site-packages\\pvlib\\pvsystem.py in __init__(self, arrays, surface_tilt, surface_azimuth, albedo, surface_type, module, module_type, module_parameters, temperature_model_parameters, modules_per_string, strings_per_inverter, inverter, inverter_parameters, racking_model, losses_parameters, name)\r\n 251 array_losses_parameters,\r\n 252 ),)\r\n--> 253 elif len(arrays) == 0:\r\n 254 raise ValueError(\"PVSystem must have at least one Array. \"\r\n 255 \"If you want to create a PVSystem instance \"\r\n\r\nTypeError: object of type 'Array' has no len()\r\n\r\n```\r\n\r\nNot a bug per se, since the PVSystem docstring requests that `arrays` be iterable. Still, a bit inconvenient to have to do this\r\n\r\n```\r\nmount = pvlib.pvsystem.FixedMount(surface_tilt=35, surface_azimuth=180)\r\narray = pvlib.pvsystem.Array(mount=mount)\r\npv = pvlib.pvsystem.PVSystem(arrays=[array])\r\n```\r\n\r\n**Describe the solution you'd like**\r\nHandle `arrays=array` where `array` is an instance of `Array`\r\n\r\n**Describe alternatives you've considered**\r\nStatus quo - either make the single Array into a list, or use the PVSystem kwargs.\r\n\n", "hints_text": "", "created_at": "2023-09-13T17:25:47Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_single_array"], "PASS_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss_deprecated", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_cell_temperature_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_module_height", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs0]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs1]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs2]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs3]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs4]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs5]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs6]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs7]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs8]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs9]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs10]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs11]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs12]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs13]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs14]", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_returns_correct_Python_type[numeric_type_funcs15]", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst_all_scalars", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_cec_extra_params_propagation", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_recombination", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[lambertw]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[brentq]", "pvlib/tests/test_pvsystem.py::test_singlediode_ivcurvepnts_deprecation_warning[newton]", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_Array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_AbstractMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_constructor", "pvlib/tests/test_pvsystem.py::test_FixedMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_constructor", "pvlib/tests/test_pvsystem.py::test_SingleAxisTrackerMount_get_orientation", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[sapm-keys0]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[fuentes-keys1]", "pvlib/tests/test_pvsystem.py::test_Array_temperature_missing_parameters[noct_sam-keys2]"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1140", "base_commit": "6b92d218653633e366241c31e8836c0072739ece", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -1210,10 +1210,19 @@ def _complete_irradiance(self, weather):\n weather.ghi - weather.dni *\n tools.cosd(self.results.solar_position.zenith))\n \n- def _prep_inputs_solar_pos(self, kwargs={}):\n+ def _prep_inputs_solar_pos(self, weather):\n \"\"\"\n Assign solar position\n \"\"\"\n+ # build weather kwargs for solar position calculation\n+ kwargs = _build_kwargs(['pressure', 'temp_air'],\n+ weather[0] if isinstance(weather, tuple)\n+ else weather)\n+ try:\n+ kwargs['temperature'] = kwargs.pop('temp_air')\n+ except KeyError:\n+ pass\n+\n self.results.solar_position = self.location.get_solarposition(\n self.times, method=self.solar_position_method,\n **kwargs)\n@@ -1363,16 +1372,7 @@ def prepare_inputs(self, weather):\n self._assign_weather(weather)\n self._assign_times()\n \n- # build kwargs for solar position calculation\n- try:\n- press_temp = _build_kwargs(['pressure', 'temp_air'],\n- weather[0] if isinstance(weather, tuple)\n- else weather)\n- press_temp['temperature'] = press_temp.pop('temp_air')\n- except KeyError:\n- pass\n-\n- self._prep_inputs_solar_pos(press_temp)\n+ self._prep_inputs_solar_pos(weather)\n self._prep_inputs_airmass()\n \n # PVSystem.get_irradiance and SingleAxisTracker.get_irradiance\n@@ -1470,7 +1470,7 @@ def prepare_inputs_from_poa(self, data):\n 'poa_diffuse'])\n self._assign_total_irrad(data)\n \n- self._prep_inputs_solar_pos()\n+ self._prep_inputs_solar_pos(data)\n self._prep_inputs_airmass()\n \n if isinstance(self.system, SingleAxisTracker):\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -886,6 +886,20 @@ def test_temperature_models_arrays_multi_weather(\n != mc.results.cell_temperature[1]).all()\n \n \n+def test_run_model_solar_position_weather(\n+ pvwatts_dc_pvwatts_ac_system, location, weather, mocker):\n+ mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location,\n+ aoi_model='no_loss', spectral_model='no_loss')\n+ weather['pressure'] = 90000\n+ weather['temp_air'] = 25\n+ m = mocker.spy(location, 'get_solarposition')\n+ mc.run_model(weather)\n+ # assert_called_once_with cannot be used with series, so need to use\n+ # assert_series_equal on call_args\n+ assert_series_equal(m.call_args[1]['temperature'], weather['temp_air'])\n+ assert_series_equal(m.call_args[1]['pressure'], weather['pressure'])\n+\n+\n def test_run_model_from_poa(sapm_dc_snl_ac_system, location, total_irrad):\n mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss',\n spectral_model='no_loss')\n@@ -909,6 +923,24 @@ def test_run_model_from_poa_arrays(sapm_dc_snl_ac_system_Array, location,\n assert_frame_equal(mc.results.dc[0], mc.results.dc[1])\n \n \n+def test_run_model_from_poa_arrays_solar_position_weather(\n+ sapm_dc_snl_ac_system_Array, location, weather, total_irrad, mocker):\n+ data = weather.copy()\n+ data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad\n+ data['pressure'] = 90000\n+ data['temp_air'] = 25\n+ data2 = data.copy()\n+ data2['pressure'] = 95000\n+ data2['temp_air'] = 30\n+ mc = ModelChain(sapm_dc_snl_ac_system_Array, location, aoi_model='no_loss',\n+ spectral_model='no_loss')\n+ m = mocker.spy(location, 'get_solarposition')\n+ mc.run_model_from_poa((data, data2))\n+ # mc uses only the first weather data for solar position corrections\n+ assert_series_equal(m.call_args[1]['temperature'], data['temp_air'])\n+ assert_series_equal(m.call_args[1]['pressure'], data['pressure'])\n+\n+\n def test_run_model_from_poa_tracking(sapm_dc_snl_ac_system, location,\n total_irrad):\n system = SingleAxisTracker(\n", "problem_statement": "Inconsistent default settings for _prep_inputs_solar_pos in prepare_inputs and prepare_inputs_from_poa\nHi there,\r\n\r\nI find that `_prep_inputs_solar_pos` method has been both called in [`prepare_inputs`](https://pvlib-python.readthedocs.io/en/stable/_modules/pvlib/modelchain.html#ModelChain.prepare_inputs) and [`prepare_inputs_from_poa`](https://pvlib-python.readthedocs.io/en/stable/_modules/pvlib/modelchain.html#ModelChain.prepare_inputs_from_poa). However, the former takes an additional argument, press_temp that contains temperature pulled from the weather data provided outside. For the default `nrel_numpy` algorithm, I further checked its input requirement is [avg. yearly air temperature in degrees C](https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.solarposition.spa_python.html#pvlib.solarposition.spa_python) rather than the instantaneous temperature provided in weather. Hence I would like to ask if the following codes in `prepare_inputs` are redundant at least for the default 'nrel_numpy' algorithm?\r\n```\r\n # build kwargs for solar position calculation\r\n try:\r\n press_temp = _build_kwargs(['pressure', 'temp_air'], weather)\r\n press_temp['temperature'] = press_temp.pop('temp_air')\r\n except KeyError:\r\n pass\r\n```\r\nAnd thereby we change `self._prep_inputs_solar_pos(press_temp)` to `self._prep_inputs_solar_pos()` in `prepare_inputs`?\r\n\r\nMeanwhile, does the temperature really matter? How much uncertainty will it cause in the calculation of the sun's position? Should we provide avg. local temperature data if for a global modelling purpose?\r\n\r\nAny help would be appreciated!\r\n\r\n\n", "hints_text": "> Meanwhile, does the temperature really matter? How much uncertainty will it cause in the calculation of the sun's position? Should we provide avg. local temperature data if for a global modelling purpose?\r\n\r\nTaking [A simple ModelChain example](https://pvlib-python.readthedocs.io/en/stable/modelchain.html#a-simple-modelchain-example) as an illustration, I find the difference caused by temperature argument is very small:\r\n\r\n`mc.solar_position` produced in the tutorial above:\r\n\r\n\r\nwith default temperature=12 `mc.location.get_solarposition(mc.weather.index, method=mc.solar_position_method)`:\r\n\r\n\r\nOnly slight difference in apparent_zenith and thereby apparent_elevation come in being.\r\n\r\nThat said, I would still think we'd better not to use instantaneous temp_air pulled from weather provided outside to calculate solar position? Besides this [documentation](https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.solarposition.spa_python.html#pvlib.solarposition.spa_python), I find the [original paper](https://www.sciencedirect.com/science/article/pii/S0038092X0300450X) also states annual local temperature.\r\n\r\nAny discussion would be appreciated!\r\n\nThanks @FeiYao-Edinburgh. \r\n\r\nThe two `_prep` functions should certainly be consistent. \r\n\r\nI agree that the documentation and original paper state that the appropriate quantity is the average yearly temperature. I don't know why we accepted #936/#893/#523 without discussing this.\r\n\r\nI'm disinclined to expose the average temperature or pressure through `ModelChain` - it would be an awkward API for no practical benefit.\n> I'm disinclined to expose the average temperature or pressure through `ModelChain` - it would be an awkward API for no practical benefit.\r\n\r\nI think so, too. This is simply because avg. yearly temperature or pressure is somewhat a time-invariant variable. Thus if it is pulled from weather data outside, it will cause weather data somewhat redundant containing many repeated values throughout time.\r\n\r\nAlternatively, maybe we can add `temperature` as a new attribute to [Location](https://pvlib-python.readthedocs.io/en/stable/generated/pvlib.location.Location.html) class. Then we can treat temperature as what we do for altitude. More specifically:\r\n\r\n1. Make changes outlined in my initial comment.\r\n2. In [Location.get_solarposition](https://pvlib-python.readthedocs.io/en/stable/_modules/pvlib/location.html#Location.get_solarposition), remove temperature argument:\r\n```\r\n def get_solarposition(self, times, pressure=None,\r\n **kwargs):\r\n```\r\nand use self.temperature instead:\r\n```\r\n return solarposition.get_solarposition(times, latitude=self.latitude,\r\n longitude=self.longitude,\r\n altitude=self.altitude,\r\n pressure=pressure,\r\n temperature=self.temperature,\r\n **kwargs)\r\n```\r\nThen in [pvlib.solarposition.get_solarposition](https://pvlib-python.readthedocs.io/en/stable/_modules/pvlib/solarposition.html#get_solarposition), make the default temperature as None:\r\n```\r\ndef get_solarposition(time, latitude, longitude,\r\n altitude=None, pressure=None,\r\n method='nrel_numpy',\r\n temperature=None, **kwargs):\r\n```\r\nand determine if temperature is None or not just like we do for altitude/pressure:\r\n```\r\nif temperature is None:\r\n temperature=12\r\n# Otherwise use the self.temperature\r\n```\r\nI am not sure whether this small issue is important enough to re-structure the Location class but happy to discuss.\r\n\r\n\nI exchanged email with Ibrahim Reda, the author of the SPA algorithm. His point is that refraction is being corrected by the atmospheric content between the observer and the sun, which cannot be known. They chose to use annual average temperature and pressure (rather than moment in time air temperature and pressure near earth's surface) by consensus, because the refraction correction is small (in terms of sun position), and either temperature gets the refraction close enough. I also suspect that annual data was easier to obtain.\r\n\r\nIMO using the time-dependent air temperature is justified in pvlib, but it is a departure from the SPA algorithm as published. \r\n\r\nI see two options:\r\n\r\n1. leave the calculation as is, change docstrings and add comment about the variation from the SPA publication. Users can still supply annual average temperature as `temp_air` if they want to strictly adhere to the publication.\r\n2. find and include global grids of average annual temperature and pressure, and wire these data into the SPA algorithm in the same way that the Linke turbidity data serve the Ineichen function.\r\n\r\nI favor the first.\r\n\r\n@adriesse would this have affected the comparisons you did a few years back between various PV-related software?\r\n\n> 1. leave the calculation as is, change docstrings and add comment about the variation from the SPA publication. Users can still supply annual average temperature as `temp_air` if they want to strictly adhere to the publication.\r\n\r\nFor this, I think it might be good to make the following changes in [`prepare_inputs_from_poa`](https://pvlib-python.readthedocs.io/en/stable/_modules/pvlib/modelchain.html#ModelChain.prepare_inputs_from_poa) to enable consistent calculations.\r\n```\r\nself._prep_inputs_solar_pos()\r\n```\r\nto\r\n```\r\n # build kwargs for solar position calculation\r\n try:\r\n press_temp = _build_kwargs(['pressure', 'temp_air'], self.weather) # weather => self.weather (TBC)\r\n press_temp['temperature'] = press_temp.pop('temp_air')\r\n except KeyError:\r\n pass\r\n self._prep_inputs_solar_pos(kwargs=press_temp)\r\n```\nThanks for checking on this @cwhanse.\r\n\r\nThe `solarposition.spa_python` temperature/pressure documentation is clear and consistent with the reference, so I think we should leave it alone. We should double check the expectations for the other algorithms and update their documentation if needed. The `solarposition.get_solarposition` documentation will need to be updated. \r\n\r\nUsers are free to obtain their own average annual temperature and pressure data and provide them to `spa_python`. I'm -1 on distributing gridded average temperature/pressure data with pvlib. I suspect the altitude pressure conversion that we already support is plenty accurate for this purpose, so users only need to find their own temperature if they care that much about it.\r\n\r\nWhen it comes to ModelChain, I'm ok with consistently using the temperature time series or removing the correction entirely. @FeiYao-Edinburgh's idea of a `Location.average_temperature` attribute is interesting, but I think I'd want to see more applications of this attribute before considering it worth the API complication.\nI agree that the `prepare_inputs` methods should be consistent whichever course we take on using air temperature for solar position calculations.\n@cwhanse thanks for inviting me to this discussion.\r\n\r\nEarlier this year or last I read the Wikipedia article about atmospheric refraction (highly recommended), did some refraction calculations myself, and started to wonder about the point of SPA. The effect of refraction is huge compared to \"SPA is well within the stated uncertainty of \u00b1 0.0003 deg.\" \r\n\r\nIt is nice for pvlib to provide SPA code corresponding to its published form, but for PV simulations consistency is much more useful than super high accuracy. Using fixed values for temperature and pressure promotes consistency.\r\n\r\nIf it were my code I would separate the sun position and refraction code because they model entirely different things.\r\n\nWhy not implement or use [solpos](https://www.nrel.gov/grid/solar-resource/solpos.html) instead. It's much simpler and faster than spa, includes refraction, and is accurate enough considering uncertainty in irradiance & other parameters. Also it solves @kanderso-nrel issue with implementing spectr2\nMight be worth synchronizing with SAM at least on the default for the sun position calculation. \r\n\nIt looks like [SAM ](https://github.com/NREL/ssc/blob/c6e41d7d946723e3cc4111262abcab081c151621/solarpilot/solpos.cpp) uses that solpos C function. For the refraction calculation (which appears to be different than in SPA) pressure and temperature can be time-dependent, or fixed at defaults (1013mb and 15C, the docstring says 10C but that looks to be a typo).\r\n\r\nI don't have a preference for any of the solar position algorithms. A drawback of SOLPOS is that it does not appear to be published other than as code.\nI had this document in my archives, but it similar to what's already online\r\n[SOLPOS Documentation.pdf](https://github.com/pvlib/pvlib-python/files/5290012/SOLPOS.Documentation.pdf)\r\n\nMore background to my earlier comment:\r\n\r\nLast year I compared simulation output from SAM, PlantPredict, Cassys, PVsyst and pvlib. This was made more difficult because _four_ different sun position algorithms were being used, and this is why I advocated for harmonization. I recommended SPA because I thought it more likely that others would switch to that, as opposed to the other way around. So perhaps we could make a pitch to SAM to adopt SPA instead. But we also need consistency on refraction.\r\n\r\n\n> I had this document in my archives, but it similar to what's already online\r\n\r\nYes. I was hoping for something to cite besides the webpage, if we implement SOLPOS.\r\n\nI have no qualms about adding SOLPOS with only a citation to a webpage. It sounds like it could be a more standard and better documented version of the [`ephemeris`](https://github.com/pvlib/pvlib-python/blob/04a523fafbd61bc2e49420963b84ed8e2bd1b3cf/pvlib/solarposition.py#L683) function. We have a robust set of solar position tests and so it should be easy to have confidence in its results. \nLooks to me like Michalsky 1988 is the one to cite.\nLooks like SAM is changing to SPA? https://github.com/NREL/ssc/pull/450\nGreat, perhaps we can get the same default behavior for refraction too... \n> Looks like SAM is changing to SPA? [NREL/ssc#450](https://github.com/NREL/ssc/pull/450)\r\n\r\nSAM has (in it's [development branch)](https://github.com/NREL/ssc/pull/450#event-3921449470), using time-dependent temperature rather than annual average.", "created_at": "2021-01-22T03:58:56Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_missing_poa", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1296", "base_commit": "bc0f0ff4e8580797af6672ff7c590caa1c78d6ed", "patch": "diff --git a/pvlib/spectrum/__init__.py b/pvlib/spectrum/__init__.py\n--- a/pvlib/spectrum/__init__.py\n+++ b/pvlib/spectrum/__init__.py\n@@ -3,6 +3,7 @@\n calc_spectral_mismatch_field,\n get_am15g,\n get_example_spectral_response,\n+ spectral_factor_caballero,\n spectral_factor_firstsolar,\n spectral_factor_sapm,\n )\ndiff --git a/pvlib/spectrum/mismatch.py b/pvlib/spectrum/mismatch.py\n--- a/pvlib/spectrum/mismatch.py\n+++ b/pvlib/spectrum/mismatch.py\n@@ -450,3 +450,123 @@ def spectral_factor_sapm(airmass_absolute, module):\n spectral_loss = pd.Series(spectral_loss, airmass_absolute.index)\n \n return spectral_loss\n+\n+\n+def spectral_factor_caballero(precipitable_water, airmass_absolute, aod500,\n+ module_type=None, coefficients=None):\n+ r\"\"\"\n+ Estimate a technology-specific spectral mismatch modifier from\n+ airmass, aerosol optical depth, and atmospheric precipitable water,\n+ using the Caballero model.\n+\n+ The model structure was motivated by examining the effect of these three\n+ atmospheric parameters on simulated irradiance spectra and spectral\n+ modifiers. However, the coefficient values reported in [1]_ and\n+ available here via the ``module_type`` parameter were determined\n+ by fitting the model equations to spectral factors calculated from\n+ global tilted spectral irradiance measurements taken in the city of\n+ Ja\u00e9n, Spain. See [1]_ for details.\n+\n+ Parameters\n+ ----------\n+ precipitable_water : numeric\n+ atmospheric precipitable water. [cm]\n+\n+ airmass_absolute : numeric\n+ absolute (pressure-adjusted) airmass. [unitless]\n+\n+ aod500 : numeric\n+ atmospheric aerosol optical depth at 500 nm. [unitless]\n+\n+ module_type : str, optional\n+ One of the following PV technology strings from [1]_:\n+\n+ * ``'cdte'`` - anonymous CdTe module.\n+ * ``'monosi'``, - anonymous sc-si module.\n+ * ``'multisi'``, - anonymous mc-si- module.\n+ * ``'cigs'`` - anonymous copper indium gallium selenide module.\n+ * ``'asi'`` - anonymous amorphous silicon module.\n+ * ``'perovskite'`` - anonymous pervoskite module.\n+\n+ coefficients : array-like, optional\n+ user-defined coefficients, if not using one of the default coefficient\n+ sets via the ``module_type`` parameter.\n+\n+ Returns\n+ -------\n+ modifier: numeric\n+ spectral mismatch factor (unitless) which is multiplied\n+ with broadband irradiance reaching a module's cells to estimate\n+ effective irradiance, i.e., the irradiance that is converted to\n+ electrical current.\n+\n+ References\n+ ----------\n+ .. [1] Caballero, J.A., Fern\u00e1ndez, E., Theristis, M.,\n+ Almonacid, F., and Nofuentes, G. \"Spectral Corrections Based on\n+ Air Mass, Aerosol Optical Depth and Precipitable Water\n+ for PV Performance Modeling.\"\n+ IEEE Journal of Photovoltaics 2018, 8(2), 552-558.\n+ :doi:`10.1109/jphotov.2017.2787019`\n+ \"\"\"\n+\n+ if module_type is None and coefficients is None:\n+ raise ValueError('Must provide either `module_type` or `coefficients`')\n+ if module_type is not None and coefficients is not None:\n+ raise ValueError('Only one of `module_type` and `coefficients` should '\n+ 'be provided')\n+\n+ # Experimental coefficients from [1]_.\n+ # The extra 0/1 coefficients at the end are used to enable/disable\n+ # terms to match the different equation forms in Table 1.\n+ _coefficients = {}\n+ _coefficients['cdte'] = (\n+ 1.0044, 0.0095, -0.0037, 0.0002, 0.0000, -0.0046,\n+ -0.0182, 0, 0.0095, 0.0068, 0, 1)\n+ _coefficients['monosi'] = (\n+ 0.9706, 0.0377, -0.0123, 0.0025, -0.0002, 0.0159,\n+ -0.0165, 0, -0.0016, -0.0027, 1, 0)\n+ _coefficients['multisi'] = (\n+ 0.9836, 0.0254, -0.0085, 0.0016, -0.0001, 0.0094,\n+ -0.0132, 0, -0.0002, -0.0011, 1, 0)\n+ _coefficients['cigs'] = (\n+ 0.9801, 0.0283, -0.0092, 0.0019, -0.0001, 0.0117,\n+ -0.0126, 0, -0.0011, -0.0019, 1, 0)\n+ _coefficients['asi'] = (\n+ 1.1060, -0.0848, 0.0302, -0.0076, 0.0006, -0.1283,\n+ 0.0986, -0.0254, 0.0156, 0.0146, 1, 0)\n+ _coefficients['perovskite'] = (\n+ 1.0637, -0.0491, 0.0180, -0.0047, 0.0004, -0.0773,\n+ 0.0583, -0.0159, 0.01251, 0.0109, 1, 0)\n+\n+ if module_type is not None:\n+ coeff = _coefficients[module_type]\n+ else:\n+ coeff = coefficients\n+\n+ # Evaluate spectral correction factor\n+ ama = airmass_absolute\n+ aod500_ref = 0.084\n+ pw_ref = 1.4164\n+\n+ f_AM = (\n+ coeff[0]\n+ + coeff[1] * ama\n+ + coeff[2] * ama**2\n+ + coeff[3] * ama**3\n+ + coeff[4] * ama**4\n+ )\n+ # Eq 6, with Table 1\n+ f_AOD = (aod500 - aod500_ref) * (\n+ coeff[5]\n+ + coeff[10] * coeff[6] * ama\n+ + coeff[11] * coeff[6] * np.log(ama)\n+ + coeff[7] * ama**2\n+ )\n+ # Eq 7, with Table 1\n+ f_PW = (precipitable_water - pw_ref) * (\n+ coeff[8]\n+ + coeff[9] * np.log(ama)\n+ )\n+ modifier = f_AM + f_AOD + f_PW # Eq 5\n+ return modifier\n", "test_patch": "diff --git a/pvlib/tests/test_spectrum.py b/pvlib/tests/test_spectrum.py\n--- a/pvlib/tests/test_spectrum.py\n+++ b/pvlib/tests/test_spectrum.py\n@@ -271,3 +271,47 @@ def test_spectral_factor_sapm(sapm_module_params, airmass, expected):\n assert_series_equal(out, expected, check_less_precise=4)\n else:\n assert_allclose(out, expected, atol=1e-4)\n+\n+\[email protected](\"module_type,expected\", [\n+ ('asi', np.array([0.9108, 0.9897, 0.9707, 1.0265, 1.0798, 0.9537])),\n+ ('perovskite', np.array([0.9422, 0.9932, 0.9868, 1.0183, 1.0604, 0.9737])),\n+ ('cdte', np.array([0.9824, 1.0000, 1.0065, 1.0117, 1.042, 0.9979])),\n+ ('multisi', np.array([0.9907, 0.9979, 1.0203, 1.0081, 1.0058, 1.019])),\n+ ('monosi', np.array([0.9935, 0.9987, 1.0264, 1.0074, 0.9999, 1.0263])),\n+ ('cigs', np.array([1.0014, 1.0011, 1.0270, 1.0082, 1.0029, 1.026])),\n+])\n+def test_spectral_factor_caballero(module_type, expected):\n+ ams = np.array([3.0, 1.5, 3.0, 1.5, 1.5, 3.0])\n+ aods = np.array([1.0, 1.0, 0.02, 0.02, 0.08, 0.08])\n+ pws = np.array([1.42, 1.42, 1.42, 1.42, 4.0, 1.0])\n+ out = spectrum.spectral_factor_caballero(pws, ams, aods,\n+ module_type=module_type)\n+ assert np.allclose(expected, out, atol=1e-3)\n+\n+\n+def test_spectral_factor_caballero_supplied():\n+ # use the cdte coeffs\n+ coeffs = (\n+ 1.0044, 0.0095, -0.0037, 0.0002, 0.0000, -0.0046,\n+ -0.0182, 0, 0.0095, 0.0068, 0, 1)\n+ out = spectrum.spectral_factor_caballero(1, 1, 1, coefficients=coeffs)\n+ expected = 1.0021964\n+ assert_allclose(out, expected, atol=1e-3)\n+\n+\n+def test_spectral_factor_caballero_supplied_redundant():\n+ # Error when specifying both module_type and coefficients\n+ coeffs = (\n+ 1.0044, 0.0095, -0.0037, 0.0002, 0.0000, -0.0046,\n+ -0.0182, 0, 0.0095, 0.0068, 0, 1)\n+ with pytest.raises(ValueError):\n+ spectrum.spectral_factor_caballero(1, 1, 1, module_type='cdte',\n+ coefficients=coeffs)\n+\n+\n+def test_spectral_factor_caballero_supplied_ambiguous():\n+ # Error when specifying neither module_type nor coefficients\n+ with pytest.raises(ValueError):\n+ spectrum.spectral_factor_caballero(1, 1, 1, module_type=None,\n+ coefficients=None)\n", "problem_statement": "Add a model for spectral corrections\n**Additional context**\r\nFirst of all, I introduce myself, my name is Jose Antonio Caballero, and I have recently finished my PhD in photovoltaic engineering at the University of Ja\u00e9n, Spain.\r\n\r\nI have developed a python script to apply spectral corrections as a function of AM, AOD, PW based on this work (https://doi.org/10.1109/jphotov.2017.2787019).\r\n\r\nWe have found that in pvlib there is already a similar methodology developed by First solar, in which the spectral corrections are based only on the AM and PW parameters, so we intend to include our proposed method in pvlib in a similar way.\r\n\r\nAs an example, I attach the code developed in python (.zip file) to estimate the spectral effects related to different flat photovoltaic technologies from the AM, AOD and PW parameters included in a .csv file.\r\n[PV-MM-AM_AOD_PW_data.csv](https://github.com/pvlib/pvlib-python/files/6970716/PV-MM-AM_AOD_PW_data.csv)\r\n[PV_Spectral_Corrections.zip](https://github.com/pvlib/pvlib-python/files/6970727/PV_Spectral_Corrections.zip)\r\n\r\nKind regards\n", "hints_text": "Hello @Jacc0027 and welcome to this community.\r\n\r\nI would welcome submission of a function implementing that model. It differs from the existing functions by including parameters for perovskite cells.\r\n\r\nIt would need to be coded as a function similar to [first_solar_spectral_correction](https://github.com/pvlib/pvlib-python/blob/f318c1c1527f69d9bf9aed6167ca1f6ce9e9d764/pvlib/atmosphere.py#L324) using the same parameter names, where possible.\r\n\r\nThe script isn't in a function format. The time series in the .csv file appear to be related to the SMARTS simulations used to set up this model, is that correct? If so, then these data don't need to come into pvlib.\nMy pleasure @cwhanse , thank you very much for the welcome.\r\n\r\nNo problem, I can adapt the code in a similar way to the one you attached, and assuming the same variables.\r\n\r\nYes, you are right, the script I attached is not made as a function, it was just a sample to verify the results. And again you are right, the time series in the .csv file are obtained through SMARTS simulations\r\n\r\nTherefore, I will attach in this thread the modified code as we have just agreed.\r\n\r\n\nHi @cwhanse , please find attached the updated script, in which we have tried to meet the requested requirements.\r\n\r\nI look forward to any comments you may have.\r\n\r\n[AM_AOD_PW_spectral_correction.zip](https://github.com/pvlib/pvlib-python/files/6984688/AM_AOD_PW_spectral_correction.zip)\r\n\nHi Jacc0027, I have looked at the code in the attachment. Can you make a pull request? When there are some tests, I think we can start the review process.", "created_at": "2021-08-26T16:50:46Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_spectrum.py::test_spectral_factor_caballero[asi-expected0]", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero[perovskite-expected1]", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero[cdte-expected2]", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero[multisi-expected3]", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero[monosi-expected4]", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero[cigs-expected5]", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero_supplied", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero_supplied_redundant", "pvlib/tests/test_spectrum.py::test_spectral_factor_caballero_supplied_ambiguous"], "PASS_TO_PASS": ["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_spectral_response", "pvlib/tests/test_spectrum.py::test_get_am15g", "pvlib/tests/test_spectrum.py::test_calc_spectral_mismatch_field", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar[cdte-expect0]", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar[monosi-expect1]", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar[polysi-expect2]", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar[cigs-expect3]", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar[asi-expect4]", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar_supplied", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar_ambiguous", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar_ambiguous_both", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar_large_airmass", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar_low_airmass", "pvlib/tests/test_spectrum.py::test_spectral_factor_firstsolar_range", "pvlib/tests/test_spectrum.py::test_spectral_factor_sapm[1.5-1.00028714375]", "pvlib/tests/test_spectrum.py::test_spectral_factor_sapm[airmass1-expected1]", "pvlib/tests/test_spectrum.py::test_spectral_factor_sapm[airmass2-expected2]"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1739", "base_commit": "909f86dc67eddc88154c9e7bff73fd9d6bfe2e4d", "patch": "diff --git a/pvlib/iotools/pvgis.py b/pvlib/iotools/pvgis.py\n--- a/pvlib/iotools/pvgis.py\n+++ b/pvlib/iotools/pvgis.py\n@@ -45,7 +45,7 @@\n \n def get_pvgis_hourly(latitude, longitude, start=None, end=None,\n raddatabase=None, components=True,\n- surface_tilt=0, surface_azimuth=0,\n+ surface_tilt=0, surface_azimuth=180,\n outputformat='json',\n usehorizon=True, userhorizon=None,\n pvcalculation=False,\n@@ -76,9 +76,15 @@ def get_pvgis_hourly(latitude, longitude, start=None, end=None,\n Otherwise only global irradiance is returned.\n surface_tilt: float, default: 0\n Tilt angle from horizontal plane. Ignored for two-axis tracking.\n- surface_azimuth: float, default: 0\n- Orientation (azimuth angle) of the (fixed) plane. 0=south, 90=west,\n- -90: east. Ignored for tracking systems.\n+ surface_azimuth: float, default: 180\n+ Orientation (azimuth angle) of the (fixed) plane. Counter-clockwise\n+ from north (north=0, south=180). This is offset 180 degrees from\n+ the convention used by PVGIS. Ignored for tracking systems.\n+\n+ .. versionchanged:: 0.10.0\n+ The `surface_azimuth` parameter now follows the pvlib convention, which\n+ is counterclockwise from north. However, the convention used by the\n+ PVGIS website and pvlib<=0.9.5 is offset by 180 degrees.\n usehorizon: bool, default: True\n Include effects of horizon\n userhorizon: list of float, default: None\n@@ -144,6 +150,13 @@ def get_pvgis_hourly(latitude, longitude, start=None, end=None,\n time stamp convention, e.g., SARAH and SARAH2 provide instantaneous values,\n whereas values from ERA5 are averages for the hour.\n \n+ Warning\n+ -------\n+ The azimuth orientation specified in the output metadata does not\n+ correspond to the pvlib convention, but is offset 180 degrees. This is\n+ despite the fact that the input parameter `surface_tilt` has to be\n+ specified according to the pvlib convention.\n+\n Notes\n -----\n data includes the following fields:\n@@ -191,7 +204,7 @@ def get_pvgis_hourly(latitude, longitude, start=None, end=None,\n \"\"\" # noqa: E501\n # use requests to format the query string by passing params dictionary\n params = {'lat': latitude, 'lon': longitude, 'outputformat': outputformat,\n- 'angle': surface_tilt, 'aspect': surface_azimuth,\n+ 'angle': surface_tilt, 'aspect': surface_azimuth-180,\n 'pvcalculation': int(pvcalculation),\n 'pvtechchoice': pvtechchoice, 'mountingplace': mountingplace,\n 'trackingtype': trackingtype, 'components': int(components),\n@@ -315,6 +328,11 @@ def read_pvgis_hourly(filename, pvgis_format=None, map_variables=True):\n metadata : dict\n metadata\n \n+ Warning\n+ -------\n+ The azimuth orientation specified in the output metadata does not\n+ correspond to the pvlib convention, but is offset 180 degrees.\n+\n Raises\n ------\n ValueError\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_pvgis.py b/pvlib/tests/iotools/test_pvgis.py\n--- a/pvlib/tests/iotools/test_pvgis.py\n+++ b/pvlib/tests/iotools/test_pvgis.py\n@@ -206,14 +206,14 @@ def test_read_pvgis_hourly_bad_extension():\n \n \n args_radiation_csv = {\n- 'surface_tilt': 30, 'surface_azimuth': 0, 'outputformat': 'csv',\n+ 'surface_tilt': 30, 'surface_azimuth': 180, 'outputformat': 'csv',\n 'usehorizon': False, 'userhorizon': None, 'raddatabase': 'PVGIS-SARAH',\n 'start': 2016, 'end': 2016, 'pvcalculation': False, 'components': True}\n \n url_hourly_radiation_csv = 'https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=csv&angle=30&aspect=0&usehorizon=0&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&raddatabase=PVGIS-SARAH&startyear=2016&endyear=2016' # noqa: E501\n \n args_pv_json = {\n- 'surface_tilt': 30, 'surface_azimuth': 0, 'outputformat': 'json',\n+ 'surface_tilt': 30, 'surface_azimuth': 180, 'outputformat': 'json',\n 'usehorizon': True, 'userhorizon': None, 'raddatabase': 'PVGIS-SARAH2',\n 'start': pd.Timestamp(2013, 1, 1), 'end': pd.Timestamp(2014, 5, 1),\n 'pvcalculation': True, 'peakpower': 10, 'pvtechchoice': 'CIS', 'loss': 5,\n", "problem_statement": "`pvlib.iotools.get_pvgis_hourly`'s `surface_azimuth` parameter doesn't use pvlib's azimuth convention\nNearly everything in pvlib represents azimuth angles as values in [0, 360) clockwise from north, except `pvlib.iotools.get_pvgis_hourly`:\r\n\r\nhttps://github.com/pvlib/pvlib-python/blob/3def7e3375002ee3a5492b7bc609d3fb63a8edb1/pvlib/iotools/pvgis.py#L79-L81\r\n\r\nThis inconsistency is a shame. However, I don't see any way to switch it to pvlib's convention without a hard break, which is also a shame. I wonder how others view the cost/benefit analysis here.\r\n\r\nSee also https://github.com/pvlib/pvlib-python/pull/1395#discussion_r1181853794\r\n\r\n\n", "hints_text": "Since `get_pvgis_hourly` is only using `surface_azimuth` to pass a value to a pvgis keyword `aspect`, we could add `aspect` with the South=0 convention and deprecate `surface_azimuth` as is. Then later, we can deprecate `aspect` and add `surface_azimuth` back with its pvlib meaning. Now that I write that out, seems better just to make the breaking change.\r\n", "created_at": "2023-05-16T23:56:19Z", "version": "0.9", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile0-expected_radiation_csv-args0-False-https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=csv&angle=30&aspect=0&usehorizon=0&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&raddatabase=PVGIS-SARAH&startyear=2016&endyear=2016]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile1-expected_radiation_csv_mapped-args1-True-https://re.jrc.ec.europa.eu/api/seriescalc?lat=45&lon=8&outputformat=csv&angle=30&aspect=0&usehorizon=0&pvtechchoice=crystSi&mountingplace=free&trackingtype=0&components=1&raddatabase=PVGIS-SARAH&startyear=2016&endyear=2016]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile2-expected_pv_json-args2-False-https://re.jrc.ec.europa.eu/api/v5_2/seriescalc?lat=45&lon=8&outputformat=json&angle=30&aspect=0&pvtechchoice=CIS&mountingplace=free&trackingtype=2&components=0&usehorizon=1&raddatabase=PVGIS-SARAH2&startyear=2013&endyear=2014&pvcalculation=1&peakpower=10&loss=5&optimalangles=1]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly[testfile3-expected_pv_json_mapped-args3-True-https://re.jrc.ec.europa.eu/api/v5_2/seriescalc?lat=45&lon=8&outputformat=json&angle=30&aspect=0&pvtechchoice=CIS&mountingplace=free&trackingtype=2&components=0&usehorizon=1&raddatabase=PVGIS-SARAH2&startyear=2013&endyear=2014&pvcalculation=1&peakpower=10&loss=5&optimalangles=1]", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_bad_status_code"], "PASS_TO_PASS": ["pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile0-expected_radiation_csv-metadata_exp0-inputs_exp0-False-None]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile1-expected_radiation_csv_mapped-metadata_exp1-inputs_exp1-True-csv]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile2-expected_pv_json-metadata_exp2-inputs_exp2-False-None]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly[testfile3-expected_pv_json_mapped-metadata_exp3-inputs_exp3-True-json]", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly_bad_extension", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_bad_outputformat", "pvlib/tests/iotools/test_pvgis.py::test_get_pvgis_hourly_additional_inputs", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_hourly_empty_file", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_map_variables", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_json", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_epw", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_csv", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_basic", "pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_exception"], "environment_setup_commit": "6072e0982c3c0236f532ddfa48fbf461180d834e"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1224", "base_commit": "50dcc7fe412d9e27fe06670b8057e3d8e9ce5b19", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -98,8 +98,9 @@ class PVSystem:\n arrays : iterable of Array, optional\n List of arrays that are part of the system. If not specified\n a single array is created from the other parameters (e.g.\n- `surface_tilt`, `surface_azimuth`). If `arrays` is specified\n- the following parameters are ignored:\n+ `surface_tilt`, `surface_azimuth`). Must contain at least one Array,\n+ if length of arrays is 0 a ValueError is raised. If `arrays` is\n+ specified the following parameters are ignored:\n \n - `surface_tilt`\n - `surface_azimuth`\n@@ -173,6 +174,11 @@ class PVSystem:\n Arbitrary keyword arguments.\n Included for compatibility, but not used.\n \n+ Raises\n+ ------\n+ ValueError\n+ If `arrays` is not None and has length 0.\n+\n See also\n --------\n pvlib.location.Location\n@@ -210,6 +216,12 @@ def __init__(self,\n racking_model,\n array_losses_parameters,\n ),)\n+ elif len(arrays) == 0:\n+ raise ValueError(\"PVSystem must have at least one Array. \"\n+ \"If you want to create a PVSystem instance \"\n+ \"with a single Array pass `arrays=None` and pass \"\n+ \"values directly to PVSystem attributes, e.g., \"\n+ \"`surface_tilt=30`\")\n else:\n self.arrays = tuple(arrays)\n \n", "test_patch": "diff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -2084,6 +2084,12 @@ def test_PVSystem_num_arrays():\n assert system_two.num_arrays == 2\n \n \n+def test_PVSystem_at_least_one_array():\n+ with pytest.raises(ValueError,\n+ match=\"PVSystem must have at least one Array\"):\n+ pvsystem.PVSystem(arrays=[])\n+\n+\n def test_combine_loss_factors():\n test_index = pd.date_range(start='1990/01/01T12:00', periods=365, freq='D')\n loss_1 = pd.Series(.10, index=test_index)\n", "problem_statement": "It should be impossible to instantiate a PVSystem with no Arrays\n**Describe the bug**\r\nIt should be impossible to instantiate a `PVSystem` with no `Arrays`. Currently this is possible via `PVSystem(arrays=[])`.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n```python\r\nfrom pvlib import pvsystem\r\npvsystem.PVSystem(arrays=[])\r\n```\r\nresults in this PVSystem:\r\n```\r\nPVSystem:\r\n name: None\r\n inverter: None\r\n```\r\n**Expected behavior**\r\nA `ValueError` should be raised indicating that a PVSystem must have at least one `Array` and suggesting that a system with an arbitrary default array can be constructed by passing `arrays=None` or not passing the `arrays` parameter at all.\r\n\r\n**Versions:**\r\n - ``pvlib.__version__``: 0.8.1+\r\n\r\n\n", "hints_text": "", "created_at": "2021-05-10T15:35:18Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_at_least_one_array"], "PASS_TO_PASS": ["pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp_override", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_change_surface_azimuth", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_modules_per_string", "pvlib/tests/test_pvsystem.py::test_PVSystem_strings_per_inverter", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-763", "base_commit": "0a14b273517a082603cc157faa88a5ab0ac4cac9", "patch": "diff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -2473,7 +2473,8 @@ def singlediode(photocurrent, saturation_current, resistance_series,\n \n \n def max_power_point(photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth, method='brentq'):\n+ resistance_shunt, nNsVth, d2mutau=0, NsVbi=np.Inf,\n+ method='brentq'):\n \"\"\"\n Given the single diode equation coefficients, calculates the maximum power\n point (MPP).\n@@ -2491,6 +2492,17 @@ def max_power_point(photocurrent, saturation_current, resistance_series,\n nNsVth : numeric\n product of thermal voltage ``Vth`` [V], diode ideality factor ``n``,\n and number of serices cells ``Ns``\n+ d2mutau : numeric, default 0\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that accounts for recombination current in the\n+ intrinsic layer. The value is the ratio of intrinsic layer thickness\n+ squared :math:`d^2` to the diffusion length of charge carriers\n+ :math:`\\\\mu \\\\tau`. [V]\n+ NsVbi : numeric, default np.inf\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that is the product of the PV module number of series\n+ cells ``Ns`` and the builtin voltage ``Vbi`` of the intrinsic layer.\n+ [V].\n method : str\n either ``'newton'`` or ``'brentq'``\n \n@@ -2508,7 +2520,8 @@ def max_power_point(photocurrent, saturation_current, resistance_series,\n \"\"\"\n i_mp, v_mp, p_mp = _singlediode.bishop88_mpp(\n photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth, method=method.lower()\n+ resistance_shunt, nNsVth, d2mutau=0, NsVbi=np.Inf,\n+ method=method.lower()\n )\n if isinstance(photocurrent, pd.Series):\n ivp = {'i_mp': i_mp, 'v_mp': v_mp, 'p_mp': p_mp}\ndiff --git a/pvlib/singlediode.py b/pvlib/singlediode.py\n--- a/pvlib/singlediode.py\n+++ b/pvlib/singlediode.py\n@@ -94,14 +94,17 @@ def bishop88(diode_voltage, photocurrent, saturation_current,\n nNsVth : numeric\n product of thermal voltage ``Vth`` [V], diode ideality factor ``n``,\n and number of series cells ``Ns``\n- d2mutau : numeric\n- PVSyst thin-film recombination parameter that is the ratio of thickness\n- of the intrinsic layer squared :math:`d^2` and the diffusion length of\n- charge carriers :math:`\\\\mu \\\\tau`, in volts [V], defaults to 0[V]\n- NsVbi : numeric\n- PVSyst thin-film recombination parameter that is the product of the PV\n- module number of series cells ``Ns`` and the builtin voltage ``Vbi`` of\n- the intrinsic layer, in volts [V], defaults to ``np.inf``\n+ d2mutau : numeric, default 0\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that accounts for recombination current in the\n+ intrinsic layer. The value is the ratio of intrinsic layer thickness\n+ squared :math:`d^2` to the diffusion length of charge carriers\n+ :math:`\\\\mu \\\\tau`. [V]\n+ NsVbi : numeric, default np.inf\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that is the product of the PV module number of series\n+ cells ``Ns`` and the builtin voltage ``Vbi`` of the intrinsic layer.\n+ [V].\n gradients : bool\n False returns only I, V, and P. True also returns gradients\n \n@@ -116,8 +119,8 @@ def bishop88(diode_voltage, photocurrent, saturation_current,\n Notes\n -----\n The PVSyst thin-film recombination losses parameters ``d2mutau`` and\n- ``NsVbi`` are only applied to cadmium-telluride (CdTe) and amorphous-\n- silicon (a:Si) PV modules, [2]_, [3]_. The builtin voltage :math:`V_{bi}`\n+ ``NsVbi`` should only be applied to cadmium-telluride (CdTe) and amorphous-\n+ silicon (a-Si) PV modules, [2]_, [3]_. The builtin voltage :math:`V_{bi}`\n should account for all junctions. For example: tandem and triple junction\n cells would have builtin voltages of 1.8[V] and 2.7[V] respectively, based\n on the default of 0.9[V] for a single junction. The parameter ``NsVbi``\n@@ -173,7 +176,7 @@ def bishop88(diode_voltage, photocurrent, saturation_current,\n \n def bishop88_i_from_v(voltage, photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth,\n- method='newton'):\n+ d2mutau=0, NsVbi=np.Inf, method='newton'):\n \"\"\"\n Find current given any voltage.\n \n@@ -192,6 +195,17 @@ def bishop88_i_from_v(voltage, photocurrent, saturation_current,\n nNsVth : numeric\n product of diode ideality factor (n), number of series cells (Ns), and\n thermal voltage (Vth = k_b * T / q_e) in volts [V]\n+ d2mutau : numeric, default 0\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that accounts for recombination current in the\n+ intrinsic layer. The value is the ratio of intrinsic layer thickness\n+ squared :math:`d^2` to the diffusion length of charge carriers\n+ :math:`\\\\mu \\\\tau`. [V]\n+ NsVbi : numeric, default np.inf\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that is the product of the PV module number of series\n+ cells ``Ns`` and the builtin voltage ``Vbi`` of the intrinsic layer.\n+ [V].\n method : str\n one of two optional search methods: either ``'brentq'``, a reliable and\n bounded method or ``'newton'`` which is the default.\n@@ -203,7 +217,7 @@ def bishop88_i_from_v(voltage, photocurrent, saturation_current,\n \"\"\"\n # collect args\n args = (photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth)\n+ resistance_shunt, nNsVth, d2mutau, NsVbi)\n \n def fv(x, v, *a):\n # calculate voltage residual given diode voltage \"x\"\n@@ -216,8 +230,9 @@ def fv(x, v, *a):\n # brentq only works with scalar inputs, so we need a set up function\n # and np.vectorize to repeatedly call the optimizer with the right\n # arguments for possible array input\n- def vd_from_brent(voc, v, iph, isat, rs, rsh, gamma):\n- return brentq(fv, 0.0, voc, args=(v, iph, isat, rs, rsh, gamma))\n+ def vd_from_brent(voc, v, iph, isat, rs, rsh, gamma, d2mutau, NsVbi):\n+ return brentq(fv, 0.0, voc,\n+ args=(v, iph, isat, rs, rsh, gamma, d2mutau, NsVbi))\n \n vd_from_brent_vectorized = np.vectorize(vd_from_brent)\n vd = vd_from_brent_vectorized(voc_est, voltage, *args)\n@@ -235,7 +250,7 @@ def vd_from_brent(voc, v, iph, isat, rs, rsh, gamma):\n \n def bishop88_v_from_i(current, photocurrent, saturation_current,\n resistance_series, resistance_shunt, nNsVth,\n- method='newton'):\n+ d2mutau=0, NsVbi=np.Inf, method='newton'):\n \"\"\"\n Find voltage given any current.\n \n@@ -254,6 +269,17 @@ def bishop88_v_from_i(current, photocurrent, saturation_current,\n nNsVth : numeric\n product of diode ideality factor (n), number of series cells (Ns), and\n thermal voltage (Vth = k_b * T / q_e) in volts [V]\n+ d2mutau : numeric, default 0\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that accounts for recombination current in the\n+ intrinsic layer. The value is the ratio of intrinsic layer thickness\n+ squared :math:`d^2` to the diffusion length of charge carriers\n+ :math:`\\\\mu \\\\tau`. [V]\n+ NsVbi : numeric, default np.inf\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that is the product of the PV module number of series\n+ cells ``Ns`` and the builtin voltage ``Vbi`` of the intrinsic layer.\n+ [V].\n method : str\n one of two optional search methods: either ``'brentq'``, a reliable and\n bounded method or ``'newton'`` which is the default.\n@@ -265,7 +291,7 @@ def bishop88_v_from_i(current, photocurrent, saturation_current,\n \"\"\"\n # collect args\n args = (photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth)\n+ resistance_shunt, nNsVth, d2mutau, NsVbi)\n # first bound the search using voc\n voc_est = estimate_voc(photocurrent, saturation_current, nNsVth)\n \n@@ -277,8 +303,9 @@ def fi(x, i, *a):\n # brentq only works with scalar inputs, so we need a set up function\n # and np.vectorize to repeatedly call the optimizer with the right\n # arguments for possible array input\n- def vd_from_brent(voc, i, iph, isat, rs, rsh, gamma):\n- return brentq(fi, 0.0, voc, args=(i, iph, isat, rs, rsh, gamma))\n+ def vd_from_brent(voc, i, iph, isat, rs, rsh, gamma, d2mutau, NsVbi):\n+ return brentq(fi, 0.0, voc,\n+ args=(i, iph, isat, rs, rsh, gamma, d2mutau, NsVbi))\n \n vd_from_brent_vectorized = np.vectorize(vd_from_brent)\n vd = vd_from_brent_vectorized(voc_est, current, *args)\n@@ -295,7 +322,8 @@ def vd_from_brent(voc, i, iph, isat, rs, rsh, gamma):\n \n \n def bishop88_mpp(photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth, method='newton'):\n+ resistance_shunt, nNsVth, d2mutau=0, NsVbi=np.Inf,\n+ method='newton'):\n \"\"\"\n Find max power point.\n \n@@ -312,6 +340,17 @@ def bishop88_mpp(photocurrent, saturation_current, resistance_series,\n nNsVth : numeric\n product of diode ideality factor (n), number of series cells (Ns), and\n thermal voltage (Vth = k_b * T / q_e) in volts [V]\n+ d2mutau : numeric, default 0\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that accounts for recombination current in the\n+ intrinsic layer. The value is the ratio of intrinsic layer thickness\n+ squared :math:`d^2` to the diffusion length of charge carriers\n+ :math:`\\\\mu \\\\tau`. [V]\n+ NsVbi : numeric, default np.inf\n+ PVsyst parameter for cadmium-telluride (CdTe) and amorphous-silicon\n+ (a-Si) modules that is the product of the PV module number of series\n+ cells ``Ns`` and the builtin voltage ``Vbi`` of the intrinsic layer.\n+ [V].\n method : str\n one of two optional search methods: either ``'brentq'``, a reliable and\n bounded method or ``'newton'`` which is the default.\n@@ -324,7 +363,7 @@ def bishop88_mpp(photocurrent, saturation_current, resistance_series,\n \"\"\"\n # collect args\n args = (photocurrent, saturation_current, resistance_series,\n- resistance_shunt, nNsVth)\n+ resistance_shunt, nNsVth, d2mutau, NsVbi)\n # first bound the search using voc\n voc_est = estimate_voc(photocurrent, saturation_current, nNsVth)\n \n@@ -334,8 +373,9 @@ def fmpp(x, *a):\n if method.lower() == 'brentq':\n # break out arguments for numpy.vectorize to handle broadcasting\n vec_fun = np.vectorize(\n- lambda voc, iph, isat, rs, rsh, gamma:\n- brentq(fmpp, 0.0, voc, args=(iph, isat, rs, rsh, gamma))\n+ lambda voc, iph, isat, rs, rsh, gamma, d2mutau, NsVbi:\n+ brentq(fmpp, 0.0, voc,\n+ args=(iph, isat, rs, rsh, gamma, d2mutau, NsVbi))\n )\n vd = vec_fun(voc_est, *args)\n elif method.lower() == 'newton':\n", "test_patch": "diff --git a/pvlib/test/test_singlediode.py b/pvlib/test/test_singlediode.py\n--- a/pvlib/test/test_singlediode.py\n+++ b/pvlib/test/test_singlediode.py\n@@ -4,7 +4,8 @@\n \n import numpy as np\n from pvlib import pvsystem\n-from pvlib.singlediode import bishop88, estimate_voc, VOLTAGE_BUILTIN\n+from pvlib.singlediode import (bishop88_mpp, estimate_voc, VOLTAGE_BUILTIN,\n+ bishop88, bishop88_i_from_v, bishop88_v_from_i)\n import pytest\n from conftest import requires_scipy\n \n@@ -153,9 +154,13 @@ def get_pvsyst_fs_495():\n 'temp_ref': 25, 'irrad_ref': 1000, 'I_L_ref': 1.5743233463848496\n }\n \n+# DeSoto @(888[W/m**2], 55[degC]) = {Pmp: 72.71, Isc: 1.402, Voc: 75.42)\n \n+\n+@requires_scipy\n @pytest.mark.parametrize(\n 'poa, temp_cell, expected, tol', [\n+ # reference conditions\n (\n get_pvsyst_fs_495()['irrad_ref'],\n get_pvsyst_fs_495()['temp_ref'],\n@@ -167,9 +172,21 @@ def get_pvsyst_fs_495():\n },\n (5e-4, 0.04)\n ),\n- (POA, TCELL, {'pmp': 76.26, 'isc': 1.387, 'voc': 79.29}, (1e-3, 1e-3))]\n-) # DeSoto @(888[W/m**2], 55[degC]) = {Pmp: 72.71, Isc: 1.402, Voc: 75.42)\n-def test_pvsyst_recombination_loss(poa, temp_cell, expected, tol):\n+ # other conditions\n+ (\n+ POA,\n+ TCELL,\n+ {\n+ 'pmp': 76.262,\n+ 'isc': 1.3868,\n+ 'voc': 79.292\n+ },\n+ (1e-4, 1e-4)\n+ )\n+ ]\n+)\[email protected]('method', ['newton', 'brentq'])\n+def test_pvsyst_recombination_loss(method, poa, temp_cell, expected, tol):\n \"\"\"test PVSst recombination loss\"\"\"\n pvsyst_fs_495 = get_pvsyst_fs_495()\n # first evaluate PVSyst model with thin-film recombination loss current\n@@ -199,9 +216,30 @@ def test_pvsyst_recombination_loss(poa, temp_cell, expected, tol):\n )\n # test max power\n assert np.isclose(max(pvsyst[2]), expected['pmp'], *tol)\n+\n # test short circuit current\n isc_pvsyst = np.interp(0, pvsyst[1], pvsyst[0])\n assert np.isclose(isc_pvsyst, expected['isc'], *tol)\n- # test open circuit current\n+\n+ # test open circuit voltage\n voc_pvsyst = np.interp(0, pvsyst[0][::-1], pvsyst[1][::-1])\n assert np.isclose(voc_pvsyst, expected['voc'], *tol)\n+\n+ # repeat tests as above with specialized bishop88 functions\n+ y = dict(d2mutau=pvsyst_fs_495['d2mutau'],\n+ NsVbi=VOLTAGE_BUILTIN*pvsyst_fs_495['cells_in_series'])\n+\n+ mpp_88 = bishop88_mpp(*x, **y, method=method)\n+ assert np.isclose(mpp_88[2], expected['pmp'], *tol)\n+\n+ isc_88 = bishop88_i_from_v(0, *x, **y, method=method)\n+ assert np.isclose(isc_88, expected['isc'], *tol)\n+\n+ voc_88 = bishop88_v_from_i(0, *x, **y, method=method)\n+ assert np.isclose(voc_88, expected['voc'], *tol)\n+\n+ ioc_88 = bishop88_i_from_v(voc_88, *x, **y, method=method)\n+ assert np.isclose(ioc_88, 0.0, *tol)\n+\n+ vsc_88 = bishop88_v_from_i(isc_88, *x, **y, method=method)\n+ assert np.isclose(vsc_88, 0.0, *tol)\n", "problem_statement": "Add recombination current params to all bishop88 functions\nThe changes made in #163 incorporate recombination current into the `bishop88()` function. Functions that build on the `bishop88()` function should likewise accept these parameters.\r\n\n", "hints_text": "", "created_at": "2019-08-13T20:05:11Z", "version": "0.6", "FAIL_TO_PASS": ["pvlib/test/test_singlediode.py::test_pvsyst_recombination_loss[newton-1000-25-expected0-tol0]", "pvlib/test/test_singlediode.py::test_pvsyst_recombination_loss[newton-888-55-expected1-tol1]", "pvlib/test/test_singlediode.py::test_pvsyst_recombination_loss[brentq-1000-25-expected0-tol0]", "pvlib/test/test_singlediode.py::test_pvsyst_recombination_loss[brentq-888-55-expected1-tol1]"], "PASS_TO_PASS": ["pvlib/test/test_singlediode.py::test_newton_spr_e20_327", "pvlib/test/test_singlediode.py::test_newton_fs_495", "pvlib/test/test_singlediode.py::test_brentq_spr_e20_327", "pvlib/test/test_singlediode.py::test_brentq_fs_495"], "environment_setup_commit": "b91d178868d193afd56f8e3b013661a473d699c3"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-907", "base_commit": "113917b780d4c7a249b09b197c16568f6212c119", "patch": "diff --git a/pvlib/iotools/__init__.py b/pvlib/iotools/__init__.py\n--- a/pvlib/iotools/__init__.py\n+++ b/pvlib/iotools/__init__.py\n@@ -12,4 +12,4 @@\n from pvlib.iotools.psm3 import get_psm3 # noqa: F401\n from pvlib.iotools.psm3 import read_psm3 # noqa: F401\n from pvlib.iotools.psm3 import parse_psm3 # noqa: F401\n-from pvlib.iotools.pvgis import get_pvgis_tmy # noqa: F401\n+from pvlib.iotools.pvgis import get_pvgis_tmy, read_pvgis_tmy # noqa: F401\ndiff --git a/pvlib/iotools/pvgis.py b/pvlib/iotools/pvgis.py\n--- a/pvlib/iotools/pvgis.py\n+++ b/pvlib/iotools/pvgis.py\n@@ -15,9 +15,11 @@\n <https://ec.europa.eu/jrc/en/PVGIS/tools/monthly-radiation>`_\n \"\"\"\n import io\n+import json\n+from pathlib import Path\n import requests\n import pandas as pd\n-from pvlib.iotools import parse_epw\n+from pvlib.iotools import read_epw, parse_epw\n \n URL = 'https://re.jrc.ec.europa.eu/api/'\n \n@@ -72,6 +74,10 @@ def get_pvgis_tmy(lat, lon, outputformat='json', usehorizon=True,\n the error message in the response will be raised as an exception,\n otherwise raise whatever ``HTTP/1.1`` error occurred\n \n+ See also\n+ --------\n+ read_pvgis_tmy\n+\n References\n ----------\n \n@@ -174,3 +180,99 @@ def _parse_pvgis_tmy_basic(src):\n data['time(UTC)'], format='%Y%m%d:%H%M', utc=True)\n data = data.drop('time(UTC)', axis=1)\n return data, None, None, None\n+\n+\n+def read_pvgis_tmy(filename, pvgis_format=None):\n+ \"\"\"\n+ Read a file downloaded from PVGIS.\n+\n+ Parameters\n+ ----------\n+ filename : str, pathlib.Path, or file-like buffer\n+ Name, path, or buffer of file downloaded from PVGIS.\n+ pvgis_format : str, default None\n+ Format of PVGIS file or buffer. Equivalent to the ``outputformat``\n+ parameter in the PVGIS TMY API. If `filename` is a file and\n+ `pvgis_format` is ``None`` then the file extension will be used to\n+ determine the PVGIS format to parse. For PVGIS files from the API with\n+ ``outputformat='basic'``, please set `pvgis_format` to ``'basic'``. If\n+ `filename` is a buffer, then `pvgis_format` is required and must be in\n+ ``['csv', 'epw', 'json', 'basic']``.\n+\n+ Returns\n+ -------\n+ data : pandas.DataFrame\n+ the weather data\n+ months_selected : list\n+ TMY year for each month, ``None`` for basic and EPW\n+ inputs : dict\n+ the inputs, ``None`` for basic and EPW\n+ meta : list or dict\n+ meta data, ``None`` for basic\n+\n+ Raises\n+ ------\n+ ValueError\n+ if `pvgis_format` is ``None`` and the file extension is neither\n+ ``.csv``, ``.json``, nor ``.epw``, or if `pvgis_format` is provided as\n+ input but isn't in ``['csv', 'epw', 'json', 'basic']``\n+ TypeError\n+ if `pvgis_format` is ``None`` and `filename` is a buffer\n+\n+ See also\n+ --------\n+ get_pvgis_tmy\n+ \"\"\"\n+ # get the PVGIS outputformat\n+ if pvgis_format is None:\n+ # get the file extension from suffix, but remove the dot and make sure\n+ # it's lower case to compare with epw, csv, or json\n+ # NOTE: raises TypeError if filename is a buffer\n+ outputformat = Path(filename).suffix[1:].lower()\n+ else:\n+ outputformat = pvgis_format\n+\n+ # parse the pvgis file based on the output format, either 'epw', 'json',\n+ # 'csv', or 'basic'\n+\n+ # EPW: use the EPW parser from the pvlib.iotools epw.py module\n+ if outputformat == 'epw':\n+ try:\n+ data, meta = parse_epw(filename)\n+ except AttributeError: # str/path has no .read() attribute\n+ data, meta = read_epw(filename)\n+ return data, None, None, meta\n+\n+ # NOTE: json, csv, and basic output formats have parsers defined as private\n+ # functions in this module\n+\n+ # JSON: use Python built-in json module to convert file contents to a\n+ # Python dictionary, and pass the dictionary to the _parse_pvgis_tmy_json()\n+ # function from this module\n+ if outputformat == 'json':\n+ try:\n+ src = json.load(filename)\n+ except AttributeError: # str/path has no .read() attribute\n+ with open(str(filename), 'r') as fbuf:\n+ src = json.load(fbuf)\n+ return _parse_pvgis_tmy_json(src)\n+\n+ # CSV or basic: use the correct parser from this module\n+ # eg: _parse_pvgis_tmy_csv() or _parse_pvgist_tmy_basic()\n+ if outputformat in ['csv', 'basic']:\n+ # get the correct parser function for this output format from globals()\n+ pvgis_parser = globals()['_parse_pvgis_tmy_{:s}'.format(outputformat)]\n+ # NOTE: pvgis_parse() is a pvgis parser function from this module,\n+ # either _parse_pvgis_tmy_csv() or _parse_pvgist_tmy_basic()\n+ try:\n+ pvgis_data = pvgis_parser(filename)\n+ except AttributeError: # str/path has no .read() attribute\n+ with open(str(filename), 'rb') as fbuf:\n+ pvgis_data = pvgis_parser(fbuf)\n+ return pvgis_data\n+\n+ # raise exception if pvgis format isn't in ['csv', 'basic', 'epw', 'json']\n+ err_msg = (\n+ \"pvgis format '{:s}' was unknown, must be either 'epw', 'json', 'csv'\"\n+ \", or 'basic'\").format(outputformat)\n+ raise ValueError(err_msg)\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_pvgis.py b/pvlib/tests/iotools/test_pvgis.py\n--- a/pvlib/tests/iotools/test_pvgis.py\n+++ b/pvlib/tests/iotools/test_pvgis.py\n@@ -6,7 +6,7 @@\n import pandas as pd\n import pytest\n import requests\n-from pvlib.iotools import get_pvgis_tmy\n+from pvlib.iotools import get_pvgis_tmy, read_pvgis_tmy\n from conftest import DATA_DIR\n \n \n@@ -70,7 +70,14 @@ def csv_meta(meta_expected):\n @pytest.mark.remote_data\n def test_get_pvgis_tmy(expected, month_year_expected, inputs_expected,\n meta_expected):\n- data, months_selected, inputs, meta = get_pvgis_tmy(45, 8)\n+ pvgis_data = get_pvgis_tmy(45, 8)\n+ _compare_pvgis_tmy_json(expected, month_year_expected, inputs_expected,\n+ meta_expected, pvgis_data)\n+\n+\n+def _compare_pvgis_tmy_json(expected, month_year_expected, inputs_expected,\n+ meta_expected, pvgis_data):\n+ data, months_selected, inputs, meta = pvgis_data\n # check each column of output separately\n for outvar in meta_expected['outputs']['tmy_hourly']['variables'].keys():\n assert np.allclose(data[outvar], expected[outvar])\n@@ -113,7 +120,12 @@ def test_get_pvgis_tmy_kwargs(userhorizon_expected):\n \n @pytest.mark.remote_data\n def test_get_pvgis_tmy_basic(expected, meta_expected):\n- data, _, _, _ = get_pvgis_tmy(45, 8, outputformat='basic')\n+ pvgis_data = get_pvgis_tmy(45, 8, outputformat='basic')\n+ _compare_pvgis_tmy_basic(expected, meta_expected, pvgis_data)\n+\n+\n+def _compare_pvgis_tmy_basic(expected, meta_expected, pvgis_data):\n+ data, _, _, _ = pvgis_data\n # check each column of output separately\n for outvar in meta_expected['outputs']['tmy_hourly']['variables'].keys():\n assert np.allclose(data[outvar], expected[outvar])\n@@ -122,8 +134,14 @@ def test_get_pvgis_tmy_basic(expected, meta_expected):\n @pytest.mark.remote_data\n def test_get_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n meta_expected, csv_meta):\n- data, months_selected, inputs, meta = get_pvgis_tmy(\n- 45, 8, outputformat='csv')\n+ pvgis_data = get_pvgis_tmy(45, 8, outputformat='csv')\n+ _compare_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n+ meta_expected, csv_meta, pvgis_data)\n+\n+\n+def _compare_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n+ meta_expected, csv_meta, pvgis_data):\n+ data, months_selected, inputs, meta = pvgis_data\n # check each column of output separately\n for outvar in meta_expected['outputs']['tmy_hourly']['variables'].keys():\n assert np.allclose(data[outvar], expected[outvar])\n@@ -144,8 +162,12 @@ def test_get_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n \n @pytest.mark.remote_data\n def test_get_pvgis_tmy_epw(expected, epw_meta):\n- data, _, _, meta = get_pvgis_tmy(\n- 45, 8, outputformat='epw')\n+ pvgis_data = get_pvgis_tmy(45, 8, outputformat='epw')\n+ _compare_pvgis_tmy_epw(expected, epw_meta, pvgis_data)\n+\n+\n+def _compare_pvgis_tmy_epw(expected, epw_meta, pvgis_data):\n+ data, _, _, meta = pvgis_data\n assert np.allclose(data.ghi, expected['G(h)'])\n assert np.allclose(data.dni, expected['Gb(n)'])\n assert np.allclose(data.dhi, expected['Gd(h)'])\n@@ -160,3 +182,73 @@ def test_get_pvgis_tmy_error():\n get_pvgis_tmy(45, 8, outputformat='bad')\n with pytest.raises(requests.HTTPError, match='404 Client Error'):\n get_pvgis_tmy(45, 8, url='https://re.jrc.ec.europa.eu/')\n+\n+\n+def test_read_pvgis_tmy_json(expected, month_year_expected, inputs_expected,\n+ meta_expected):\n+ fn = DATA_DIR / 'tmy_45.000_8.000_2005_2016.json'\n+ # infer outputformat from file extensions\n+ pvgis_data = read_pvgis_tmy(fn)\n+ _compare_pvgis_tmy_json(expected, month_year_expected, inputs_expected,\n+ meta_expected, pvgis_data)\n+ # explicit pvgis outputformat\n+ pvgis_data = read_pvgis_tmy(fn, pvgis_format='json')\n+ _compare_pvgis_tmy_json(expected, month_year_expected, inputs_expected,\n+ meta_expected, pvgis_data)\n+ with fn.open('r') as fbuf:\n+ pvgis_data = read_pvgis_tmy(fbuf, pvgis_format='json')\n+ _compare_pvgis_tmy_json(expected, month_year_expected, inputs_expected,\n+ meta_expected, pvgis_data)\n+\n+\n+def test_read_pvgis_tmy_epw(expected, epw_meta):\n+ fn = DATA_DIR / 'tmy_45.000_8.000_2005_2016.epw'\n+ # infer outputformat from file extensions\n+ pvgis_data = read_pvgis_tmy(fn)\n+ _compare_pvgis_tmy_epw(expected, epw_meta, pvgis_data)\n+ # explicit pvgis outputformat\n+ pvgis_data = read_pvgis_tmy(fn, pvgis_format='epw')\n+ _compare_pvgis_tmy_epw(expected, epw_meta, pvgis_data)\n+ with fn.open('r') as fbuf:\n+ pvgis_data = read_pvgis_tmy(fbuf, pvgis_format='epw')\n+ _compare_pvgis_tmy_epw(expected, epw_meta, pvgis_data)\n+\n+\n+def test_read_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n+ meta_expected, csv_meta):\n+ fn = DATA_DIR / 'tmy_45.000_8.000_2005_2016.csv'\n+ # infer outputformat from file extensions\n+ pvgis_data = read_pvgis_tmy(fn)\n+ _compare_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n+ meta_expected, csv_meta, pvgis_data)\n+ # explicit pvgis outputformat\n+ pvgis_data = read_pvgis_tmy(fn, pvgis_format='csv')\n+ _compare_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n+ meta_expected, csv_meta, pvgis_data)\n+ with fn.open('rb') as fbuf:\n+ pvgis_data = read_pvgis_tmy(fbuf, pvgis_format='csv')\n+ _compare_pvgis_tmy_csv(expected, month_year_expected, inputs_expected,\n+ meta_expected, csv_meta, pvgis_data)\n+\n+\n+def test_read_pvgis_tmy_basic(expected, meta_expected):\n+ fn = DATA_DIR / 'tmy_45.000_8.000_2005_2016.txt'\n+ # XXX: can't infer outputformat from file extensions for basic\n+ with pytest.raises(ValueError, match=\"pvgis format 'txt' was unknown\"):\n+ read_pvgis_tmy(fn)\n+ # explicit pvgis outputformat\n+ pvgis_data = read_pvgis_tmy(fn, pvgis_format='basic')\n+ _compare_pvgis_tmy_basic(expected, meta_expected, pvgis_data)\n+ with fn.open('rb') as fbuf:\n+ pvgis_data = read_pvgis_tmy(fbuf, pvgis_format='basic')\n+ _compare_pvgis_tmy_basic(expected, meta_expected, pvgis_data)\n+ # file buffer raises TypeError if passed to pathlib.Path()\n+ with pytest.raises(TypeError):\n+ read_pvgis_tmy(fbuf)\n+\n+\n+def test_read_pvgis_tmy_exception():\n+ bad_outputformat = 'bad'\n+ err_msg = \"pvgis format '{:s}' was unknown\".format(bad_outputformat)\n+ with pytest.raises(ValueError, match=err_msg):\n+ read_pvgis_tmy('filename', pvgis_format=bad_outputformat)\n", "problem_statement": "access private _parse_pvgis_tmy_csv() function as read_pvgis_tmy_csv()\n**Is your feature request related to a problem? Please describe.**\r\nsomeone sent me a csv file they downloaded from pvgis, and I needed to parse it, so I had to call the private methods like this:\r\n\r\n```python\r\n>>> from pvlib.iotools.pvgis import _parse_pvgis_tmy_csv\r\n>>> with (path_to_folder / 'pvgis_tmy_lat_lon_years.csv').open('rb') as f:\r\n pvgis_data = _parse_pvgis_tmy_csv(f)\r\n```\r\n\r\n**Describe the solution you'd like**\r\nIf I need this, others may also. I think a public method that takes either a string or a buffer could be useful? Something called `read_pvgis_tmy_csv()`\r\n\r\n**Describe alternatives you've considered**\r\nI was able to do it by just calling the private function and it worked, so that's an alternative also\r\n\r\n**Additional context**\r\nrelated to #845 and #849 \r\n\naccess private _parse_pvgis_tmy_csv() function as read_pvgis_tmy_csv()\n**Is your feature request related to a problem? Please describe.**\r\nsomeone sent me a csv file they downloaded from pvgis, and I needed to parse it, so I had to call the private methods like this:\r\n\r\n```python\r\n>>> from pvlib.iotools.pvgis import _parse_pvgis_tmy_csv\r\n>>> with (path_to_folder / 'pvgis_tmy_lat_lon_years.csv').open('rb') as f:\r\n pvgis_data = _parse_pvgis_tmy_csv(f)\r\n```\r\n\r\n**Describe the solution you'd like**\r\nIf I need this, others may also. I think a public method that takes either a string or a buffer could be useful? Something called `read_pvgis_tmy_csv()`\r\n\r\n**Describe alternatives you've considered**\r\nI was able to do it by just calling the private function and it worked, so that's an alternative also\r\n\r\n**Additional context**\r\nrelated to #845 and #849 \r\n\n", "hints_text": "OK with me to refactor to the same pattern as #842 in particular the get / read / parse [trio](https://github.com/pvlib/pvlib-python/pull/842#issuecomment-570309454).\nI just started in this, but didn't push it yet, sorry. Kinda important now to have a static/remoteless test that checks parsing, since all of the tests are decorated\nOK with me to refactor to the same pattern as #842 in particular the get / read / parse [trio](https://github.com/pvlib/pvlib-python/pull/842#issuecomment-570309454).\nI just started in this, but didn't push it yet, sorry. Kinda important now to have a static/remoteless test that checks parsing, since all of the tests are decorated", "created_at": "2020-02-23T09:19:00Z", "version": "0.6", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_pvgis.py::test_read_pvgis_tmy_exception"], "PASS_TO_PASS": [], "environment_setup_commit": "b91d178868d193afd56f8e3b013661a473d699c3"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1053", "base_commit": "bc3a9c8efcedd4b686f60ed0e3d3d7548189bb27", "patch": "diff --git a/pvlib/location.py b/pvlib/location.py\n--- a/pvlib/location.py\n+++ b/pvlib/location.py\n@@ -5,11 +5,13 @@\n # Will Holmgren, University of Arizona, 2014-2016.\n \n import datetime\n+import warnings\n \n import pandas as pd\n import pytz\n \n from pvlib import solarposition, clearsky, atmosphere, irradiance\n+from pvlib._deprecation import pvlibDeprecationWarning\n \n \n class Location:\n@@ -48,10 +50,6 @@ class Location:\n name : None or string, default None.\n Sets the name attribute of the Location object.\n \n- **kwargs\n- Arbitrary keyword arguments.\n- Included for compatibility, but not used.\n-\n See also\n --------\n pvlib.pvsystem.PVSystem\n@@ -82,6 +80,12 @@ def __init__(self, latitude, longitude, tz='UTC', altitude=0,\n \n self.name = name\n \n+ if kwargs:\n+ warnings.warn(\n+ 'Arbitrary Location kwargs are deprecated and will be '\n+ 'removed in v0.9', pvlibDeprecationWarning\n+ )\n+\n def __repr__(self):\n attrs = ['name', 'latitude', 'longitude', 'altitude', 'tz']\n return ('Location: \\n ' + '\\n '.join(\ndiff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -333,10 +333,6 @@ class ModelChain:\n \n name: None or str, default None\n Name of ModelChain instance.\n-\n- **kwargs\n- Arbitrary keyword arguments. Included for compatibility, but not\n- used.\n \"\"\"\n \n def __init__(self, system, location,\n@@ -372,6 +368,12 @@ def __init__(self, system, location,\n self.times = None\n self.solar_position = None\n \n+ if kwargs:\n+ warnings.warn(\n+ 'Arbitrary ModelChain kwargs are deprecated and will be '\n+ 'removed in v0.9', pvlibDeprecationWarning\n+ )\n+\n @classmethod\n def with_pvwatts(cls, system, location,\n orientation_strategy=None,\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -79,9 +79,6 @@ class PVSystem:\n :py:class:`~pvlib.modelchain.ModelChain`\n objects.\n \n- See the :py:class:`LocalizedPVSystem` class for an object model that\n- describes an installed PV system.\n-\n The class supports basic system topologies consisting of:\n \n * `N` total modules arranged in series\n@@ -164,7 +161,6 @@ class PVSystem:\n --------\n pvlib.location.Location\n pvlib.tracking.SingleAxisTracker\n- pvlib.pvsystem.LocalizedPVSystem\n \"\"\"\n \n def __init__(self,\n@@ -220,6 +216,12 @@ def __init__(self,\n \n self.name = name\n \n+ if kwargs:\n+ warnings.warn(\n+ 'Arbitrary PVSystem kwargs are deprecated and will be '\n+ 'removed in v0.9', pvlibDeprecationWarning\n+ )\n+\n def __repr__(self):\n attrs = ['name', 'surface_tilt', 'surface_azimuth', 'module',\n 'inverter', 'albedo', 'racking_model', 'module_type',\n@@ -819,9 +821,12 @@ def pvwatts_ac(self, pdc):\n return inverter.pvwatts(pdc, self.inverter_parameters['pdc0'],\n **kwargs)\n \n+ @deprecated('0.8', alternative='PVSystem, Location, and ModelChain',\n+ name='PVSystem.localize', removal='0.9')\n def localize(self, location=None, latitude=None, longitude=None,\n **kwargs):\n- \"\"\"Creates a LocalizedPVSystem object using this object\n+ \"\"\"\n+ Creates a LocalizedPVSystem object using this object\n and location data. Must supply either location object or\n latitude, longitude, and any location kwargs\n \n@@ -843,6 +848,8 @@ def localize(self, location=None, latitude=None, longitude=None,\n return LocalizedPVSystem(pvsystem=self, location=location)\n \n \n+@deprecated('0.8', alternative='PVSystem, Location, and ModelChain',\n+ name='LocalizedPVSystem', removal='0.9')\n class LocalizedPVSystem(PVSystem, Location):\n \"\"\"\n The LocalizedPVSystem class defines a standard set of installed PV\ndiff --git a/pvlib/tracking.py b/pvlib/tracking.py\n--- a/pvlib/tracking.py\n+++ b/pvlib/tracking.py\n@@ -6,6 +6,7 @@\n from pvlib.pvsystem import PVSystem\n from pvlib.location import Location\n from pvlib import irradiance, atmosphere\n+from pvlib._deprecation import deprecated\n \n \n class SingleAxisTracker(PVSystem):\n@@ -55,6 +56,9 @@ class SingleAxisTracker(PVSystem):\n :func:`~pvlib.tracking.calc_cross_axis_tilt` to calculate\n `cross_axis_tilt`. [degrees]\n \n+ **kwargs\n+ Passed to :py:class:`~pvlib.pvsystem.PVSystem`.\n+\n See also\n --------\n pvlib.tracking.singleaxis\n@@ -112,6 +116,9 @@ def singleaxis(self, apparent_zenith, apparent_azimuth):\n \n return tracking_data\n \n+ @deprecated('0.8',\n+ alternative='SingleAxisTracker, Location, and ModelChain',\n+ name='SingleAxisTracker.localize', removal='0.9')\n def localize(self, location=None, latitude=None, longitude=None,\n **kwargs):\n \"\"\"\n@@ -232,6 +239,8 @@ def get_irradiance(self, surface_tilt, surface_azimuth,\n **kwargs)\n \n \n+@deprecated('0.8', alternative='SingleAxisTracker, Location, and ModelChain',\n+ name='LocalizedSingleAxisTracker', removal='0.9')\n class LocalizedSingleAxisTracker(SingleAxisTracker, Location):\n \"\"\"\n The :py:class:`~pvlib.tracking.LocalizedSingleAxisTracker` class defines a\n", "test_patch": "diff --git a/pvlib/tests/test_location.py b/pvlib/tests/test_location.py\n--- a/pvlib/tests/test_location.py\n+++ b/pvlib/tests/test_location.py\n@@ -16,7 +16,8 @@\n from pvlib.solarposition import declination_spencer71\n from pvlib.solarposition import equation_of_time_spencer71\n from test_solarposition import expected_solpos, golden, golden_mst\n-from conftest import requires_ephem, requires_tables\n+from pvlib._deprecation import pvlibDeprecationWarning\n+from conftest import requires_ephem, requires_tables, fail_on_pvlib_version\n \n \n def test_location_required():\n@@ -323,3 +324,10 @@ def test_get_sun_rise_set_transit_valueerror(golden):\n tz='MST')\n with pytest.raises(ValueError):\n golden.get_sun_rise_set_transit(times, method='eyeball')\n+\n+\n+@fail_on_pvlib_version('0.9')\n+def test_deprecated_09():\n+ match = \"Arbitrary Location kwargs\"\n+ with pytest.warns(pvlibDeprecationWarning, match=match):\n+ Location(32.2, -111, arbitrary_kwarg='value')\ndiff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -776,6 +776,13 @@ def test_deprecated_09(sapm_dc_snl_ac_system, cec_dc_adr_ac_system,\n aoi_model='no_loss', spectral_model='no_loss')\n \n \n+@fail_on_pvlib_version('0.9')\n+def test_ModelChain_kwargs_deprecated_09(sapm_dc_snl_ac_system, location):\n+ match = \"Arbitrary ModelChain kwargs\"\n+ with pytest.warns(pvlibDeprecationWarning, match=match):\n+ ModelChain(sapm_dc_snl_ac_system, location, arbitrary_kwarg='value')\n+\n+\n def test_basic_chain_required(sam_data, cec_inverter_parameters,\n sapm_temperature_cs5p_220m):\n times = pd.date_range(start='20160101 1200-0700',\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -1064,10 +1064,12 @@ def test_PVSystem_get_irradiance():\n assert_frame_equal(irradiance, expected, check_less_precise=2)\n \n \n+@fail_on_pvlib_version('0.9')\n def test_PVSystem_localize_with_location():\n system = pvsystem.PVSystem(module='blah', inverter='blarg')\n location = Location(latitude=32, longitude=-111)\n- localized_system = system.localize(location=location)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ localized_system = system.localize(location=location)\n \n assert localized_system.module == 'blah'\n assert localized_system.inverter == 'blarg'\n@@ -1075,9 +1077,11 @@ def test_PVSystem_localize_with_location():\n assert localized_system.longitude == -111\n \n \n+@fail_on_pvlib_version('0.9')\n def test_PVSystem_localize_with_latlon():\n system = pvsystem.PVSystem(module='blah', inverter='blarg')\n- localized_system = system.localize(latitude=32, longitude=-111)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ localized_system = system.localize(latitude=32, longitude=-111)\n \n assert localized_system.module == 'blah'\n assert localized_system.inverter == 'blarg'\n@@ -1103,11 +1107,13 @@ def test_PVSystem___repr__():\n assert system.__repr__() == expected\n \n \n+@fail_on_pvlib_version('0.9')\n def test_PVSystem_localize___repr__():\n system = pvsystem.PVSystem(\n module='blah', inverter='blarg', name='pv ftw',\n temperature_model_parameters={'a': -3.56})\n- localized_system = system.localize(latitude=32, longitude=-111)\n+ with pytest.warns(pvlibDeprecationWarning):\n+ localized_system = system.localize(latitude=32, longitude=-111)\n # apparently name is not preserved when creating a system using localize\n expected = \"\"\"LocalizedPVSystem:\n name: None\n@@ -1131,12 +1137,13 @@ def test_PVSystem_localize___repr__():\n # when they are attached to LocalizedPVSystem, but\n # that's probably not necessary at this point.\n \n-\n+@fail_on_pvlib_version('0.9')\n def test_LocalizedPVSystem_creation():\n- localized_system = pvsystem.LocalizedPVSystem(latitude=32,\n- longitude=-111,\n- module='blah',\n- inverter='blarg')\n+ with pytest.warns(pvlibDeprecationWarning):\n+ localized_system = pvsystem.LocalizedPVSystem(latitude=32,\n+ longitude=-111,\n+ module='blah',\n+ inverter='blarg')\n \n assert localized_system.module == 'blah'\n assert localized_system.inverter == 'blarg'\n@@ -1144,10 +1151,12 @@ def test_LocalizedPVSystem_creation():\n assert localized_system.longitude == -111\n \n \n+@fail_on_pvlib_version('0.9')\n def test_LocalizedPVSystem___repr__():\n- localized_system = pvsystem.LocalizedPVSystem(\n- latitude=32, longitude=-111, module='blah', inverter='blarg',\n- name='my name', temperature_model_parameters={'a': -3.56})\n+ with pytest.warns(pvlibDeprecationWarning):\n+ localized_system = pvsystem.LocalizedPVSystem(\n+ latitude=32, longitude=-111, module='blah', inverter='blarg',\n+ name='my name', temperature_model_parameters={'a': -3.56})\n \n expected = \"\"\"LocalizedPVSystem:\n name: my name\n@@ -1311,3 +1320,6 @@ def test_deprecated_09(cec_inverter_parameters, adr_inverter_parameters):\n system = pvsystem.PVSystem()\n with pytest.warns(pvlibDeprecationWarning, match=match):\n system.sapm_celltemp(1, 2, 3)\n+ match = \"Arbitrary PVSystem kwargs\"\n+ with pytest.warns(pvlibDeprecationWarning, match=match):\n+ system = pvsystem.PVSystem(arbitrary_kwarg='value')\n", "problem_statement": "remove **kwargs from PVSystem, ModelChain, Location\nThese objects accept arbitrary kwargs so that users can be lazy about splatting dictionaries into the object constructors. I guess this is nice in some situations. But it also leads to bugs when users mistype a parameter name because python doesn't raise an exception. I ran into this when working on #1022 and #1027. \r\n\r\nI propose that we remove the kwargs without deprecation in 0.8.\n", "hints_text": "", "created_at": "2020-09-07T17:10:07Z", "version": "0.7", "FAIL_TO_PASS": ["pvlib/tests/test_location.py::test_deprecated_09", "pvlib/tests/test_modelchain.py::test_ModelChain_kwargs_deprecated_09", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_location", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize_with_latlon", "pvlib/tests/test_pvsystem.py::test_PVSystem_localize___repr__", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem_creation", "pvlib/tests/test_pvsystem.py::test_LocalizedPVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_deprecated_09"], "PASS_TO_PASS": ["pvlib/tests/test_location.py::test_location_required", "pvlib/tests/test_location.py::test_location_all", "pvlib/tests/test_location.py::test_location_tz[tz0]", "pvlib/tests/test_location.py::test_location_tz[America/Phoenix]", "pvlib/tests/test_location.py::test_location_tz[-7]", "pvlib/tests/test_location.py::test_location_tz[-7.0]", "pvlib/tests/test_location.py::test_location_tz[tz4]", "pvlib/tests/test_location.py::test_location_invalid_tz", "pvlib/tests/test_location.py::test_location_invalid_tz_type", "pvlib/tests/test_location.py::test_location_print_all", "pvlib/tests/test_location.py::test_location_print_pytz", "pvlib/tests/test_location.py::test_get_clearsky", "pvlib/tests/test_location.py::test_get_clearsky_ineichen_supply_linke", "pvlib/tests/test_location.py::test_get_clearsky_haurwitz", "pvlib/tests/test_location.py::test_get_clearsky_valueerror", "pvlib/tests/test_location.py::test_get_solarposition", "pvlib/tests/test_location.py::test_get_airmass", "pvlib/tests/test_location.py::test_get_airmass_valueerror", "pvlib/tests/test_location.py::test_Location___repr__", "pvlib/tests/test_location.py::test_get_sun_rise_set_transit", "pvlib/tests/test_location.py::test_get_sun_rise_set_transit_valueerror", "pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected0]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[None-expected1]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[flat-expected2]", "pvlib/tests/test_modelchain.py::test_orientation_strategy[south_at_latitude_tilt-expected3]", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_infer_temp_model_no_params", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[snlinverter]", "pvlib/tests/test_modelchain.py::test_ac_models_deprecated[adrinverter]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_deprecated_09[snlinverter]", "pvlib/tests/test_modelchain.py::test_deprecated_09[adrinverter]", "pvlib/tests/test_modelchain.py::test_basic_chain_required", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_strategy", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[south_at_latitude_tilt-south_at_latitude_tilt]", "pvlib/tests/test_modelchain.py::test_ModelChain___repr__[None-None]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors"], "environment_setup_commit": "6e5148f59c5050e8f7a0084b7ae39e93b80f72e6"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1518", "base_commit": "6a94e35ffae279468d59577a1d2fbefdcbf768d9", "patch": "diff --git a/pvlib/clearsky.py b/pvlib/clearsky.py\n--- a/pvlib/clearsky.py\n+++ b/pvlib/clearsky.py\n@@ -14,6 +14,7 @@\n import h5py\n \n from pvlib import atmosphere, tools\n+from pvlib.tools import _degrees_to_index\n \n \n def ineichen(apparent_zenith, airmass_absolute, linke_turbidity,\n@@ -286,67 +287,6 @@ def _calendar_month_middles(year):\n return middles\n \n \n-def _degrees_to_index(degrees, coordinate):\n- \"\"\"Transform input degrees to an output index integer. The Linke\n- turbidity lookup tables have three dimensions, latitude, longitude, and\n- month. Specify a degree value and either 'latitude' or 'longitude' to get\n- the appropriate index number for the first two of these index numbers.\n-\n- Parameters\n- ----------\n- degrees : float or int\n- Degrees of either latitude or longitude.\n- coordinate : string\n- Specify whether degrees arg is latitude or longitude. Must be set to\n- either 'latitude' or 'longitude' or an error will be raised.\n-\n- Returns\n- -------\n- index : np.int16\n- The latitude or longitude index number to use when looking up values\n- in the Linke turbidity lookup table.\n- \"\"\"\n- # Assign inputmin, inputmax, and outputmax based on degree type.\n- if coordinate == 'latitude':\n- inputmin = 90\n- inputmax = -90\n- outputmax = 2160\n- elif coordinate == 'longitude':\n- inputmin = -180\n- inputmax = 180\n- outputmax = 4320\n- else:\n- raise IndexError(\"coordinate must be 'latitude' or 'longitude'.\")\n-\n- inputrange = inputmax - inputmin\n- scale = outputmax/inputrange # number of indices per degree\n- center = inputmin + 1 / scale / 2 # shift to center of index\n- outputmax -= 1 # shift index to zero indexing\n- index = (degrees - center) * scale\n- err = IndexError('Input, %g, is out of range (%g, %g).' %\n- (degrees, inputmin, inputmax))\n-\n- # If the index is still out of bounds after rounding, raise an error.\n- # 0.500001 is used in comparisons instead of 0.5 to allow for a small\n- # margin of error which can occur when dealing with floating point numbers.\n- if index > outputmax:\n- if index - outputmax <= 0.500001:\n- index = outputmax\n- else:\n- raise err\n- elif index < 0:\n- if -index <= 0.500001:\n- index = 0\n- else:\n- raise err\n- # If the index wasn't set to outputmax or 0, round it and cast it as an\n- # integer so it can be used in integer-based indexing.\n- else:\n- index = int(np.around(index))\n-\n- return index\n-\n-\n def haurwitz(apparent_zenith):\n '''\n Determine clear sky GHI using the Haurwitz model.\ndiff --git a/pvlib/location.py b/pvlib/location.py\n--- a/pvlib/location.py\n+++ b/pvlib/location.py\n@@ -4,13 +4,16 @@\n \n # Will Holmgren, University of Arizona, 2014-2016.\n \n+import os\n import datetime\n import warnings\n \n import pandas as pd\n import pytz\n+import h5py\n \n from pvlib import solarposition, clearsky, atmosphere, irradiance\n+from pvlib.tools import _degrees_to_index\n \n class Location:\n \"\"\"\n@@ -356,3 +359,88 @@ def get_sun_rise_set_transit(self, times, method='pyephem', **kwargs):\n 'one of pyephem, spa, geometric'\n .format(method))\n return result\n+\n+\n+def lookup_altitude(latitude, longitude):\n+ \"\"\"\n+ Look up location altitude from low-resolution altitude map\n+ supplied with pvlib. The data for this map comes from multiple open data\n+ sources with varying resolutions aggregated by Mapzen.\n+\n+ More details can be found here\n+ https://github.com/tilezen/joerd/blob/master/docs/data-sources.md\n+\n+ Altitudes from this map are a coarse approximation and can have\n+ significant errors (100+ meters) introduced by downsampling and\n+ source data resolution.\n+\n+ Parameters\n+ ----------\n+ latitude : float.\n+ Positive is north of the equator.\n+ Use decimal degrees notation.\n+\n+ longitude : float.\n+ Positive is east of the prime meridian.\n+ Use decimal degrees notation.\n+\n+ Returns\n+ -------\n+ altitude : float\n+ The altitude of the location in meters.\n+\n+ Notes\n+ -----------\n+ Attributions:\n+\n+ * ArcticDEM terrain data DEM(s) were created from DigitalGlobe, Inc.,\n+ imagery and funded under National Science Foundation awards 1043681,\n+ 1559691, and 1542736;\n+ * Australia terrain data \u00a9 Commonwealth of Australia\n+ (Geoscience Australia) 2017;\n+ * Austria terrain data \u00a9 offene Daten \u00d6sterreichs - Digitales\n+ Gel\u00e4ndemodell (DGM) \u00d6sterreich;\n+ * Canada terrain data contains information licensed under the Open\n+ Government Licence - Canada;\n+ * Europe terrain data produced using Copernicus data and information\n+ funded by the European Union - EU-DEM layers;\n+ * Global ETOPO1 terrain data U.S. National Oceanic and Atmospheric\n+ Administration\n+ * Mexico terrain data source: INEGI, Continental relief, 2016;\n+ * New Zealand terrain data Copyright 2011 Crown copyright (c) Land\n+ Information New Zealand and the New Zealand Government\n+ (All rights reserved);\n+ * Norway terrain data \u00a9 Kartverket;\n+ * United Kingdom terrain data \u00a9 Environment Agency copyright and/or\n+ database right 2015. All rights reserved;\n+ * United States 3DEP (formerly NED) and global GMTED2010 and SRTM\n+ terrain data courtesy of the U.S. Geological Survey.\n+\n+ References\n+ ----------\n+ .. [1] `Mapzen, Linux foundation project for open data maps\n+ <https://www.mapzen.com/>`_\n+ .. [2] `Joerd, tool for downloading and processing DEMs, Used by Mapzen\n+ <https://github.com/tilezen/joerd/>`_\n+ .. [3] `AWS, Open Data Registry Terrain Tiles\n+ <https://registry.opendata.aws/terrain-tiles/>`_\n+\n+ \"\"\"\n+\n+ pvlib_path = os.path.dirname(os.path.abspath(__file__))\n+ filepath = os.path.join(pvlib_path, 'data', 'Altitude.h5')\n+\n+ latitude_index = _degrees_to_index(latitude, coordinate='latitude')\n+ longitude_index = _degrees_to_index(longitude, coordinate='longitude')\n+\n+ with h5py.File(filepath, 'r') as alt_h5_file:\n+ alt = alt_h5_file['Altitude'][latitude_index, longitude_index]\n+\n+ # 255 is a special value that means nodata. Fallback to 0 if nodata.\n+ if alt == 255:\n+ return 0\n+ # Altitude is encoded in 28 meter steps from -450 meters to 6561 meters\n+ # There are 0-254 possible altitudes, with 255 reserved for nodata.\n+ alt *= 28\n+ alt -= 450\n+ return float(alt)\ndiff --git a/pvlib/tools.py b/pvlib/tools.py\n--- a/pvlib/tools.py\n+++ b/pvlib/tools.py\n@@ -412,3 +412,61 @@ def _get_sample_intervals(times, win_length):\n 'periods, leap days, etc.'\n )\n raise NotImplementedError(message)\n+\n+\n+def _degrees_to_index(degrees, coordinate):\n+ \"\"\"Transform input degrees to an output index integer.\n+ Specify a degree value and either 'latitude' or 'longitude' to get\n+ the appropriate index number for these two index numbers.\n+ Parameters\n+ ----------\n+ degrees : float or int\n+ Degrees of either latitude or longitude.\n+ coordinate : string\n+ Specify whether degrees arg is latitude or longitude. Must be set to\n+ either 'latitude' or 'longitude' or an error will be raised.\n+ Returns\n+ -------\n+ index : np.int16\n+ The latitude or longitude index number to use when looking up values\n+ in the Linke turbidity lookup table.\n+ \"\"\"\n+ # Assign inputmin, inputmax, and outputmax based on degree type.\n+ if coordinate == 'latitude':\n+ inputmin = 90\n+ inputmax = -90\n+ outputmax = 2160\n+ elif coordinate == 'longitude':\n+ inputmin = -180\n+ inputmax = 180\n+ outputmax = 4320\n+ else:\n+ raise IndexError(\"coordinate must be 'latitude' or 'longitude'.\")\n+\n+ inputrange = inputmax - inputmin\n+ scale = outputmax/inputrange # number of indices per degree\n+ center = inputmin + 1 / scale / 2 # shift to center of index\n+ outputmax -= 1 # shift index to zero indexing\n+ index = (degrees - center) * scale\n+ err = IndexError('Input, %g, is out of range (%g, %g).' %\n+ (degrees, inputmin, inputmax))\n+\n+ # If the index is still out of bounds after rounding, raise an error.\n+ # 0.500001 is used in comparisons instead of 0.5 to allow for a small\n+ # margin of error which can occur when dealing with floating point numbers.\n+ if index > outputmax:\n+ if index - outputmax <= 0.500001:\n+ index = outputmax\n+ else:\n+ raise err\n+ elif index < 0:\n+ if -index <= 0.500001:\n+ index = 0\n+ else:\n+ raise err\n+ # If the index wasn't set to outputmax or 0, round it and cast it as an\n+ # integer so it can be used in integer-based indexing.\n+ else:\n+ index = int(np.around(index))\n+\n+ return index\n", "test_patch": "diff --git a/pvlib/tests/test_clearsky.py b/pvlib/tests/test_clearsky.py\n--- a/pvlib/tests/test_clearsky.py\n+++ b/pvlib/tests/test_clearsky.py\n@@ -511,13 +511,6 @@ def monthly_lt_nointerp(lat, lon, time=months):\n monthly_lt_nointerp(38.2, -181) # exceeds min longitude\n \n \n-def test_degrees_to_index_1():\n- \"\"\"Test that _degrees_to_index raises an error when something other than\n- 'latitude' or 'longitude' is passed.\"\"\"\n- with pytest.raises(IndexError): # invalid value for coordinate argument\n- clearsky._degrees_to_index(degrees=22.0, coordinate='width')\n-\n-\n @pytest.fixture\n def detect_clearsky_data():\n data_file = DATA_DIR / 'detect_clearsky_data.csv'\ndiff --git a/pvlib/tests/test_location.py b/pvlib/tests/test_location.py\n--- a/pvlib/tests/test_location.py\n+++ b/pvlib/tests/test_location.py\n@@ -12,7 +12,7 @@\n from pytz.exceptions import UnknownTimeZoneError\n \n import pvlib\n-from pvlib.location import Location\n+from pvlib.location import Location, lookup_altitude\n from pvlib.solarposition import declination_spencer71\n from pvlib.solarposition import equation_of_time_spencer71\n from .conftest import requires_ephem\n@@ -326,3 +326,23 @@ def test_get_sun_rise_set_transit_valueerror(golden):\n def test_extra_kwargs():\n with pytest.raises(TypeError, match='arbitrary_kwarg'):\n Location(32.2, -111, arbitrary_kwarg='value')\n+\n+\n+def test_lookup_altitude():\n+ max_alt_error = 125\n+ # location name, latitude, longitude, altitude\n+ test_locations = [\n+ ('Tucson, USA', 32.2540, -110.9742, 724),\n+ ('Lusaka, Zambia', -15.3875, 28.3228, 1253),\n+ ('Tokio, Japan', 35.6762, 139.6503, 40),\n+ ('Canberra, Australia', -35.2802, 149.1310, 566),\n+ ('Bogota, Colombia', 4.7110, -74.0721, 2555),\n+ ('Dead Sea, West Bank', 31.525849, 35.449214, -415),\n+ ('New Delhi, India', 28.6139, 77.2090, 214),\n+ ('Null Island, Atlantic Ocean', 0, 0, 0),\n+ ]\n+\n+ for name, lat, lon, expected_alt in test_locations:\n+ alt_found = lookup_altitude(lat, lon)\n+ assert abs(alt_found - expected_alt) < max_alt_error, \\\n+ f'Max error exceded for {name} - e: {expected_alt} f: {alt_found}'\ndiff --git a/pvlib/tests/test_tools.py b/pvlib/tests/test_tools.py\n--- a/pvlib/tests/test_tools.py\n+++ b/pvlib/tests/test_tools.py\n@@ -72,3 +72,10 @@ def test__golden_sect_DataFrame_nans():\n v, x = tools._golden_sect_DataFrame(params, lower, upper,\n _obj_test_golden_sect)\n assert np.allclose(x, expected, atol=1e-8, equal_nan=True)\n+\n+\n+def test_degrees_to_index_1():\n+ \"\"\"Test that _degrees_to_index raises an error when something other than\n+ 'latitude' or 'longitude' is passed.\"\"\"\n+ with pytest.raises(IndexError): # invalid value for coordinate argument\n+ tools._degrees_to_index(degrees=22.0, coordinate='width')\n", "problem_statement": "Altitude lookup table\nCurrently, altitude for `pvlib.location` based algorithms defaults to zero, but if we include a low-resolution altitude lookup, we can provide better results when altitude is not specified.\r\nWe can make this altitude lookup the same format as [LinkeTurbidities.h5](https://github.com/pvlib/pvlib-python/blob/master/pvlib/data/LinkeTurbidities.h5), so it wouldn't require that much new code or any new dependencies.\r\nI was able to build an altitude map using [open data aggregated by tilezen](https://github.com/tilezen/joerd/blob/master/docs/data-sources.md). My test H5 file is currently `13 mb` using `4320x2160` resolution, `uint16` altitude, and `gzip` compression. We are free to distribute this data, but we do need to do is add [this attribution](https://github.com/tilezen/joerd/blob/master/docs/attribution.md) somewhere in the documentation.\r\nWould you guys be interested in this feature? Should I make a pull request?\r\n\r\nHere is a plot of my sample\r\n\r\n:\n", "hints_text": "Is there an api we can use instead?\nCool idea. I can't really comment on the cost (if any) of distributing another relatively large data file.\r\n\r\nSome thoughts: the technical improvement to modeling would be minor: the only use of 'altitude' is to estimate air pressure for a clear-sky model or for adjusting geometric solar position to apparent position. But there's an intangible benefit from not having to look up a value, or having to explain why the default 0m is good enough. To me the intangible benefit is likely greater than the improvement in model results.\r\n\r\nAs alternatives, several of the weather data sources (PSM3, others), but not all, return altitude. \nCould file size be reduced by omitting the ocean bathymetry data? I'm not really familiar with h5 files. If accuracy is not so important, maybe cutting the values down to 8 bits would be acceptable. \r\n\r\n> Cool idea\r\n\r\nYes! Makes me wonder if there are other such datasets we should consider. \n> Accuracy is not so important\r\n\r\nGood point. Altitude rounded to 100m increments is probably good enough.\nI'm unsure about packaging an elevation map with pvlib. But a higher resolution data set could be useful for shading. I thought there were some PR discussions along those lines.\nI think getting altitude is probably something we can outsource to an API like the Google Maps maybe, ESRI, or MapQuest? Seems a lot easier than adding 10 mb to the package maybe?\nFound these:\r\n* [Google map elevation API](https://developers.google.com/maps/documentation/elevation/start), [guide](https://developers.google.com/maps/documentation/elevation/overview)\r\n* [open elevation api](https://open-elevation.com/)\r\n* [Air Map API](https://developers.airmap.com/docs/elevation-api)\r\n* [open topo data api](https://www.opentopodata.org/)\r\n* [DEM.NET](https://elevationapi.com/faq) EG\r\n\r\n > This URL will give you (quickly!) the elevation near Notre-Dame de Paris (39 meters), using SRTM GL3 dataset : \r\n[`https://api.elevationapi.com/api/Elevation?lat=48.854624&lon=2.3436793&dataSet=SRTM_GL3`](https://api.elevationapi.com/api/Elevation?lat=48.854624&lon=2.3436793&dataSet=SRTM_GL3)\r\n\r\nAnd more\u2026 I googled \u201celevation api lookup\u201d\nI tried the suggestions to reduce the size of the altitude lookup map.\r\nIf I set the oceans data to zero, it compresses much better and goes down to `3.9 mb`.\r\nI also tried encoding the remaining land data as `uint8` in `35m` increments.\r\nThis `uint8` version is `1.2 mb` after gzip compression.\r\n\r\nI agree that an API would be good for high-resolution use cases like shading. \r\nBut I think having a fallback built-in is still valid.\r\nAn external API has more friction; You need API keys, there can be costs or limits, and it adds more latency.\nAlso, where I got the original data can be helpful in high-resolution use-cases. It is hosted for free by aws in their [open data initiative](https://registry.opendata.aws/terrain-tiles/).\r\nYou can fetch terrain tiles using [slippy tilenames](https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames) from this URL template\r\n`https://elevation-tiles-prod.s3.amazonaws.com/v2/terrarium/{zoom}/{x}/{y}.png`.\r\nAnd [here](https://github.com/tilezen/joerd/blob/master/docs/formats.md) are the docs for how to convert RGB -> meters\nI'm -1 to having `Location.get_solarposition()` make web requests, if that's being proposed. I'm cautiously open to bundling a local dataset if it's only a ~1MB expense (our [current dist](https://pypi.org/project/pvlib/#files) is ~30 MB).\r\n\r\nI'm also open to `iotools` functions for elevation data, although I'm not sure I see a lot of value in it if the relevant API calls are as simple as `requests.get(\"url?lon=X&lat=Y\").json()['elevation']`. I think I'd rather see a gallery example showing how to DIY in that case. \nThis discussion suggests there are two, perhaps complementary, enhancements:\r\n- provide a low-resolution, low-accuracy altitude to supplement the current default of 0. for clearsky and solar position calculations.\r\n- via iotools, provide access to an API for high-resolution elevation data for detailed modeling of shading, tracker steering, and (in future pvlib) spatially varying module orientation.\r\n\r\nAccess to an API for detailed elevation data will not relieve those who want a simple alternative to the current default. Similarly, a low-resolution file included with pvlib will not satisfy those looking for high accuracy elevation.\r\n\r\nI'm not opposed to having all three (current default, low-resolution internal lookup, high resolution via API) in pvlib. \nI think it'd be great to have the option of something like this: \r\n\r\n pvlib.location.Location(latitude=55, longitude=10, altitude='SRTM')\r\n\r\nand then have the location object call an API (using a function from iotools) that retrieved the elevation.\nIt looks like the 1.2 mb version might be acceptable. I will make a pull request early next week and you can make the final decision then. I also will play with the encoding a bit, there might be ways to increase accuracy while staying ~1 mb.\nI wonder if folks will start to cannibalize pvlib for elevation data, and then send issues complaining that it's only accurate to 35m :rofl:\n> I wonder if folks will start to cannibalize pvlib for elevation data, and then send issues complaining that it's only accurate to 35m \ud83e\udd23\r\n\r\nAssuredly, yes.", "created_at": "2022-08-09T13:59:09Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_clearsky.py::test_ineichen_series", "pvlib/tests/test_clearsky.py::test_ineichen_series_perez_enhancement", "pvlib/tests/test_clearsky.py::test_ineichen_scalar_input", "pvlib/tests/test_clearsky.py::test_ineichen_nans", "pvlib/tests/test_clearsky.py::test_ineichen_arrays", "pvlib/tests/test_clearsky.py::test_ineichen_dni_extra", "pvlib/tests/test_clearsky.py::test_ineichen_altitude", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_leapyear", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_nointerp", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_months", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_months_leapyear", "pvlib/tests/test_clearsky.py::test_lookup_linke_turbidity_nointerp_months", "pvlib/tests/test_clearsky.py::test_haurwitz", "pvlib/tests/test_clearsky.py::test_simplified_solis_scalar_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_scalar_neg_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_series_elevation", "pvlib/tests/test_clearsky.py::test_simplified_solis_dni_extra", "pvlib/tests/test_clearsky.py::test_simplified_solis_pressure", "pvlib/tests/test_clearsky.py::test_simplified_solis_aod700", "pvlib/tests/test_clearsky.py::test_simplified_solis_precipitable_water", "pvlib/tests/test_clearsky.py::test_simplified_solis_small_scalar_pw", "pvlib/tests/test_clearsky.py::test_simplified_solis_return_arrays", "pvlib/tests/test_clearsky.py::test_simplified_solis_nans_arrays", "pvlib/tests/test_clearsky.py::test_simplified_solis_nans_series", "pvlib/tests/test_clearsky.py::test_linke_turbidity_corners", "pvlib/tests/test_clearsky.py::test_detect_clearsky", "pvlib/tests/test_clearsky.py::test_detect_clearsky_defaults", "pvlib/tests/test_clearsky.py::test_detect_clearsky_components", "pvlib/tests/test_clearsky.py::test_detect_clearsky_iterations", "pvlib/tests/test_clearsky.py::test_detect_clearsky_kwargs", "pvlib/tests/test_clearsky.py::test_detect_clearsky_window", "pvlib/tests/test_clearsky.py::test_detect_clearsky_time_interval", "pvlib/tests/test_clearsky.py::test_detect_clearsky_arrays", "pvlib/tests/test_clearsky.py::test_detect_clearsky_irregular_times", "pvlib/tests/test_clearsky.py::test_detect_clearsky_missing_index", "pvlib/tests/test_clearsky.py::test__line_length_windowed", "pvlib/tests/test_clearsky.py::test__max_diff_windowed", "pvlib/tests/test_clearsky.py::test__calc_stats", "pvlib/tests/test_clearsky.py::test_bird", "pvlib/tests/test_location.py::test_location_required", "pvlib/tests/test_location.py::test_location_all", "pvlib/tests/test_location.py::test_location_tz[tz0]", "pvlib/tests/test_location.py::test_location_tz[America/Phoenix]", "pvlib/tests/test_location.py::test_location_tz[-7]", "pvlib/tests/test_location.py::test_location_tz[-7.0]", "pvlib/tests/test_location.py::test_location_tz[tz4]", "pvlib/tests/test_location.py::test_location_invalid_tz", "pvlib/tests/test_location.py::test_location_invalid_tz_type", "pvlib/tests/test_location.py::test_location_print_all", "pvlib/tests/test_location.py::test_location_print_pytz", "pvlib/tests/test_location.py::test_get_clearsky", "pvlib/tests/test_location.py::test_get_clearsky_ineichen_supply_linke", "pvlib/tests/test_location.py::test_get_clearsky_haurwitz", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_apparent_elevation", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_dni_extra", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_pressure", "pvlib/tests/test_location.py::test_get_clearsky_simplified_solis_aod_pw", "pvlib/tests/test_location.py::test_get_clearsky_valueerror", "pvlib/tests/test_location.py::test_from_tmy_3", "pvlib/tests/test_location.py::test_from_tmy_2", "pvlib/tests/test_location.py::test_from_epw", "pvlib/tests/test_location.py::test_get_solarposition", "pvlib/tests/test_location.py::test_get_airmass", "pvlib/tests/test_location.py::test_get_airmass_valueerror", "pvlib/tests/test_location.py::test_Location___repr__", "pvlib/tests/test_location.py::test_get_sun_rise_set_transit", "pvlib/tests/test_location.py::test_get_sun_rise_set_transit_valueerror", "pvlib/tests/test_location.py::test_extra_kwargs", "pvlib/tests/test_tools.py::test_build_kwargs[keys0-input_dict0-expected0]", "pvlib/tests/test_tools.py::test_build_kwargs[keys1-input_dict1-expected1]", "pvlib/tests/test_tools.py::test_build_kwargs[keys2-input_dict2-expected2]", "pvlib/tests/test_tools.py::test_build_kwargs[keys3-input_dict3-expected3]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params0-0.0-1.0-0.5-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params1-0.0-1.0-0.07230200263994839-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame[params2-0.0-100.0-89.14332727531685-_obj_test_golden_sect]", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_atol", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_vector", "pvlib/tests/test_tools.py::test__golden_sect_DataFrame_nans", "pvlib/tests/test_tools.py::test_degrees_to_index_1"], "PASS_TO_PASS": [], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1239", "base_commit": "276a30de72a392ff59f798b8850229e9527ff03e", "patch": "diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py\n--- a/pvlib/irradiance.py\n+++ b/pvlib/irradiance.py\n@@ -1126,7 +1126,6 @@ def perez(surface_tilt, surface_azimuth, dhi, dni, dni_extra,\n F1 = np.maximum(F1, 0)\n \n F2 = (F2c[ebin, 0] + F2c[ebin, 1] * delta + F2c[ebin, 2] * z)\n- F2 = np.maximum(F2, 0)\n \n A = aoi_projection(surface_tilt, surface_azimuth,\n solar_zenith, solar_azimuth)\n", "test_patch": "diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py\n--- a/pvlib/tests/test_irradiance.py\n+++ b/pvlib/tests/test_irradiance.py\n@@ -248,6 +248,52 @@ def test_perez_components(irrad_data, ephem_data, dni_et, relative_airmass):\n assert_series_equal(sum_components, expected_for_sum, check_less_precise=2)\n \n \n+def test_perez_negative_horizon():\n+ times = pd.date_range(start='20190101 11:30:00', freq='1H',\n+ periods=5, tz='US/Central')\n+\n+ # Avoid test dependencies on functionality not being tested by hard-coding\n+ # the inputs. This data corresponds to Goodwin Creek in the afternoon on\n+ # 1/1/2019.\n+ # dni_e is slightly rounded from irradiance.get_extra_radiation\n+ # airmass from atmosphere.get_relative_airmas\n+ inputs = pd.DataFrame(np.array(\n+ [[ 158, 19, 1, 0, 0],\n+ [ 249, 165, 136, 93, 50],\n+ [ 57.746951, 57.564205, 60.813841, 66.989435, 75.353368],\n+ [ 171.003315, 187.346924, 202.974357, 216.725599, 228.317233],\n+ [1414, 1414, 1414, 1414, 1414],\n+ [ 1.869315, 1.859981, 2.044429, 2.544943, 3.900136]]).T,\n+ columns=['dni', 'dhi', 'solar_zenith',\n+ 'solar_azimuth', 'dni_extra', 'airmass'],\n+ index=times\n+ )\n+\n+ out = irradiance.perez(34, 180, inputs['dhi'], inputs['dni'],\n+ inputs['dni_extra'], inputs['solar_zenith'],\n+ inputs['solar_azimuth'], inputs['airmass'],\n+ model='allsitescomposite1990',\n+ return_components=True)\n+\n+ # sky_diffuse can be less than isotropic under certain conditions as\n+ # horizon goes negative\n+ expected = pd.DataFrame(np.array(\n+ [[281.410185, 152.20879, 123.867898, 82.836412, 43.517015],\n+ [166.785419, 142.24475, 119.173875, 83.525150, 45.725931],\n+ [113.548755, 16.09757, 9.956174, 3.142467, 0],\n+ [ 1.076010, -6.13353, -5.262151, -3.831230, -2.208923]]).T,\n+ columns=['sky_diffuse', 'isotropic', 'circumsolar', 'horizon'],\n+ index=times\n+ )\n+\n+ expected_for_sum = expected['sky_diffuse'].copy()\n+ sum_components = out.iloc[:, 1:].sum(axis=1)\n+ sum_components.name = 'sky_diffuse'\n+\n+ assert_frame_equal(out, expected, check_less_precise=2)\n+ assert_series_equal(sum_components, expected_for_sum, check_less_precise=2)\n+\n+\n def test_perez_arrays(irrad_data, ephem_data, dni_et, relative_airmass):\n dni = irrad_data['dni'].copy()\n dni.iloc[2] = np.nan\n@@ -608,7 +654,7 @@ def test_gti_dirint():\n expected_col_order = ['ghi', 'dni', 'dhi']\n expected = pd.DataFrame(array(\n [[ 21.05796198, 0. , 21.05796198],\n- [ 288.22574368, 60.59964218, 245.37532576],\n+ [ 291.40037163, 63.41290679, 246.56067523],\n [ 931.04078010, 695.94965324, 277.06172442]]),\n columns=expected_col_order, index=times)\n \n@@ -632,7 +678,7 @@ def test_gti_dirint():\n \n expected = pd.DataFrame(array(\n [[ 21.05796198, 0. , 21.05796198],\n- [ 289.81109139, 60.52460392, 247.01373353],\n+ [ 293.21310935, 63.27500913, 248.47092131],\n [ 932.46756378, 648.05001357, 323.49974813]]),\n columns=expected_col_order, index=times)\n \n@@ -646,8 +692,8 @@ def test_gti_dirint():\n \n expected = pd.DataFrame(array(\n [[ 21.3592591, 0. , 21.3592591 ],\n- [ 292.5162373, 64.42628826, 246.95997198],\n- [ 941.6753031, 727.16311901, 258.36548605]]),\n+ [ 294.4985420, 66.25848451, 247.64671830],\n+ [ 941.7943404, 727.50552952, 258.16276278]]),\n columns=expected_col_order, index=times)\n \n assert_frame_equal(output, expected)\n@@ -659,8 +705,8 @@ def test_gti_dirint():\n temp_dew=temp_dew)\n \n expected = pd.DataFrame(array(\n- [[ 21.05796198, 0. , 21.05796198],\n- [ 292.40468994, 36.79559287, 266.3862767 ],\n+ [[ 21.05796198, 0., 21.05796198],\n+ [ 295.06070190, 38.20346345, 268.0467738],\n [ 931.79627208, 689.81549269, 283.5817439]]),\n columns=expected_col_order, index=times)\n \n", "problem_statement": "The Perez diffuse model should not be forcing the horizon coefficient up to zero\nThe perez model in irradiance.py forces F2, and thus the horizon component of diffuse, to be non-negative. This restriction should not happen. F2 and the horizon coefficient should be allowed to be negative and to reduce overall diffuse.\r\n\r\nAccording to the original paper at https://www.osti.gov/servlets/purl/7024029\r\nSection III.2 states this explicitly for the horizon component:\r\n\"(2) The horizon brightening coefficient, F2, is negative for overcast and low E occurrences -- indicative of brightening of the zenithal region of the sky for these conditions. This becomes positive past intermediate conditions and increases substantially with clearness.\"\r\n\r\nWe observed a higher than expected POAI, coming from poa diffuse, on cloudy days at certain sites.\r\nExpected:\r\nHorizon (burgundy) can be less than zero and sky diffuse (green) is less than isotropic (blue)\r\n\r\n\r\nObserved from PVLib:\r\nHorizon is prevented from being negative and sky diffuse ends up higher than isotropic.\r\n\r\n\r\nRepro'd on PVLib 0.8.1\r\n\r\nSee added test case in the PR for this repro case.\r\n\n", "hints_text": "", "created_at": "2021-05-21T17:47:47Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_irradiance.py::test_perez_negative_horizon", "pvlib/tests/test_irradiance.py::test_gti_dirint"], "PASS_TO_PASS": ["pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_float", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_reindl", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_model_invalid", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_airmass", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_airmass", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_aoi_projection_precision", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1458", "base_commit": "a0812b12584cfd5e662fa5aeb8972090763a671f", "patch": "diff --git a/pvlib/iotools/sodapro.py b/pvlib/iotools/sodapro.py\n--- a/pvlib/iotools/sodapro.py\n+++ b/pvlib/iotools/sodapro.py\n@@ -153,11 +153,11 @@ def get_cams(latitude, longitude, start, end, email, identifier='mcclear',\n References\n ----------\n .. [1] `CAMS Radiation Service Info\n- <http://www.soda-pro.com/web-services/radiation/cams-radiation-service/info>`_\n+ <https://www.soda-pro.com/web-services/radiation/cams-radiation-service/info>`_\n .. [2] `CAMS McClear Service Info\n- <http://www.soda-pro.com/web-services/radiation/cams-mcclear/info>`_\n+ <https://www.soda-pro.com/web-services/radiation/cams-mcclear/info>`_\n .. [3] `CAMS McClear Automatic Access\n- <http://www.soda-pro.com/help/cams-services/cams-mcclear-service/automatic-access>`_\n+ <https://www.soda-pro.com/help/cams-services/cams-mcclear-service/automatic-access>`_\n \"\"\"\n try:\n time_step_str = TIME_STEPS_MAP[time_step]\n@@ -185,7 +185,7 @@ def get_cams(latitude, longitude, start, end, email, identifier='mcclear',\n email = email.replace('@', '%2540') # Format email address\n identifier = 'get_{}'.format(identifier.lower()) # Format identifier str\n \n- base_url = f\"http://{server}/service/wps\"\n+ base_url = f\"https://{server}/service/wps\"\n \n data_inputs_dict = {\n 'latitude': latitude,\n@@ -263,9 +263,9 @@ def parse_cams(fbuf, integrated=False, label=None, map_variables=True):\n References\n ----------\n .. [1] `CAMS Radiation Service Info\n- <http://www.soda-pro.com/web-services/radiation/cams-radiation-service/info>`_\n+ <https://www.soda-pro.com/web-services/radiation/cams-radiation-service/info>`_\n .. [2] `CAMS McClear Service Info\n- <http://www.soda-pro.com/web-services/radiation/cams-mcclear/info>`_\n+ <https://www.soda-pro.com/web-services/radiation/cams-mcclear/info>`_\n \"\"\"\n metadata = {}\n # Initial lines starting with # contain metadata\n@@ -366,9 +366,9 @@ def read_cams(filename, integrated=False, label=None, map_variables=True):\n References\n ----------\n .. [1] `CAMS Radiation Service Info\n- <http://www.soda-pro.com/web-services/radiation/cams-radiation-service/info>`_\n+ <https://www.soda-pro.com/web-services/radiation/cams-radiation-service/info>`_\n .. [2] `CAMS McClear Service Info\n- <http://www.soda-pro.com/web-services/radiation/cams-mcclear/info>`_\n+ <https://www.soda-pro.com/web-services/radiation/cams-mcclear/info>`_\n \"\"\"\n with open(str(filename), 'r') as fbuf:\n content = parse_cams(fbuf, integrated, label, map_variables)\n", "test_patch": "diff --git a/pvlib/tests/iotools/test_sodapro.py b/pvlib/tests/iotools/test_sodapro.py\n--- a/pvlib/tests/iotools/test_sodapro.py\n+++ b/pvlib/tests/iotools/test_sodapro.py\n@@ -209,7 +209,7 @@ def test_get_cams(requests_mock, testfile, index, columns, values, dtypes,\n mock_response = test_file.read()\n # Specify the full URI of a specific example, this ensures that all of the\n # inputs are passing on correctly\n- url_test_cams = f'http://www.soda-is.com/service/wps?DataInputs=latitude=55.7906;longitude=12.5251;altitude=80;date_begin=2020-01-01;date_end=2020-05-04;time_ref=UT;summarization=P01M;username=pvlib-admin%2540googlegroups.com;verbose=false&Service=WPS&Request=Execute&Identifier=get_{identifier}&version=1.0.0&RawDataOutput=irradiation' # noqa: E501\n+ url_test_cams = f'https://www.soda-is.com/service/wps?DataInputs=latitude=55.7906;longitude=12.5251;altitude=80;date_begin=2020-01-01;date_end=2020-05-04;time_ref=UT;summarization=P01M;username=pvlib-admin%2540googlegroups.com;verbose=false&Service=WPS&Request=Execute&Identifier=get_{identifier}&version=1.0.0&RawDataOutput=irradiation' # noqa: E501\n \n requests_mock.get(url_test_cams, text=mock_response,\n headers={'Content-Type': 'application/csv'})\n@@ -254,7 +254,7 @@ def test_get_cams_bad_request(requests_mock):\n Please, register yourself at www.soda-pro.com\n </ows:ExceptionText>\"\"\"\n \n- url_cams_bad_request = 'http://pro.soda-is.com/service/wps?DataInputs=latitude=55.7906;longitude=12.5251;altitude=-999;date_begin=2020-01-01;date_end=2020-05-04;time_ref=TST;summarization=PT01H;username=test%2540test.com;verbose=false&Service=WPS&Request=Execute&Identifier=get_mcclear&version=1.0.0&RawDataOutput=irradiation' # noqa: E501\n+ url_cams_bad_request = 'https://pro.soda-is.com/service/wps?DataInputs=latitude=55.7906;longitude=12.5251;altitude=-999;date_begin=2020-01-01;date_end=2020-05-04;time_ref=TST;summarization=PT01H;username=test%2540test.com;verbose=false&Service=WPS&Request=Execute&Identifier=get_mcclear&version=1.0.0&RawDataOutput=irradiation' # noqa: E501\n \n requests_mock.get(url_cams_bad_request, text=mock_response_bad,\n headers={'Content-Type': 'application/xml'})\n", "problem_statement": "Update get_cams protocol to https\nAccording to an email sent out by Transvalor on May 12th 2022, the SoDa websites and services will switch from using \"HTTP\" to only \"HTTPS\". \r\n\r\nThe existing HTTP endpoints will redirect to the correct HTTPS sites, hence without any changes the [`get_cams`](https://pvlib-python.readthedocs.io/en/stable/reference/generated/pvlib.iotools.get_cams.html) function will continue to work correctly (as the request package handles redirects automatically). However, for good practice and to avoid unnecessary redirects, updating the existing URLs and endpoints to HTTPS is surely a good idea:\r\nhttps://github.com/pvlib/pvlib-python/blob/a0812b12584cfd5e662fa5aeb8972090763a671f/pvlib/iotools/sodapro.py#L188\r\n\r\n<br>\r\nFor reference, here's a screen-shot of Transvalor email:\r\n\r\n\r\n\r\nFYI: this is a good first issue to tackle to get familiar with contribution to pvlib :) \n", "hints_text": "", "created_at": "2022-05-16T14:58:05Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/iotools/test_sodapro.py::test_get_cams[testfile0-index0-columns0-values0-dtypes0-mcclear]", "pvlib/tests/iotools/test_sodapro.py::test_get_cams[testfile1-index1-columns1-values1-dtypes1-cams_radiation]", "pvlib/tests/iotools/test_sodapro.py::test_get_cams_bad_request"], "PASS_TO_PASS": ["pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile0-index0-columns0-values0-dtypes0]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile1-index1-columns1-values1-dtypes1]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile2-index2-columns2-values2-dtypes2]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams[testfile3-index3-columns3-values3-dtypes3]", "pvlib/tests/iotools/test_sodapro.py::test_read_cams_integrated_unmapped_label", "pvlib/tests/iotools/test_sodapro.py::test_read_cams_metadata"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1218", "base_commit": "40ba4bd5c8b91754aa73e638ed984ab9657847cd", "patch": "diff --git a/pvlib/modelchain.py b/pvlib/modelchain.py\n--- a/pvlib/modelchain.py\n+++ b/pvlib/modelchain.py\n@@ -977,7 +977,7 @@ def infer_temperature_model(self):\n return self.faiman_temp\n elif {'noct_installed'} <= params:\n return self.fuentes_temp\n- elif {'noct', 'eta_m_ref'} <= params:\n+ elif {'noct', 'module_efficiency'} <= params:\n return self.noct_sam_temp\n else:\n raise ValueError(f'could not infer temperature model from '\ndiff --git a/pvlib/pvsystem.py b/pvlib/pvsystem.py\n--- a/pvlib/pvsystem.py\n+++ b/pvlib/pvsystem.py\n@@ -671,7 +671,9 @@ def pvsyst_celltemp(self, poa_global, temp_air, wind_speed=1.0):\n wind_speed = self._validate_per_array(wind_speed, system_wide=True)\n \n def build_celltemp_kwargs(array):\n- return {**_build_kwargs(['eta_m', 'alpha_absorption'],\n+ # TODO remove 'eta_m' after deprecation of this parameter\n+ return {**_build_kwargs(['eta_m', 'module_efficiency',\n+ 'alpha_absorption'],\n array.module_parameters),\n **_build_kwargs(['u_c', 'u_v'],\n array.temperature_model_parameters)}\n@@ -843,10 +845,10 @@ def _build_kwargs_noct_sam(array):\n # bundled with kwargs for simplicity\n temp_model_kwargs['noct'] = \\\n array.temperature_model_parameters['noct']\n- temp_model_kwargs['eta_m_ref'] = \\\n- array.temperature_model_parameters['eta_m_ref']\n+ temp_model_kwargs['module_efficiency'] = \\\n+ array.temperature_model_parameters['module_efficiency']\n except KeyError:\n- msg = ('Parameters noct and eta_m_ref are required.'\n+ msg = ('Parameters noct and module_efficiency are required.'\n ' Found {} in temperature_model_parameters.'\n .format(array.temperature_model_parameters))\n raise KeyError(msg)\ndiff --git a/pvlib/temperature.py b/pvlib/temperature.py\n--- a/pvlib/temperature.py\n+++ b/pvlib/temperature.py\n@@ -6,6 +6,7 @@\n import numpy as np\n import pandas as pd\n from pvlib.tools import sind\n+from pvlib._deprecation import warn_deprecated\n \n TEMPERATURE_MODEL_PARAMETERS = {\n 'sapm': {\n@@ -285,7 +286,7 @@ def sapm_cell_from_module(module_temperature, poa_global, deltaT,\n \n \n def pvsyst_cell(poa_global, temp_air, wind_speed=1.0, u_c=29.0, u_v=0.0,\n- eta_m=0.1, alpha_absorption=0.9):\n+ eta_m=None, module_efficiency=0.1, alpha_absorption=0.9):\n r\"\"\"\n Calculate cell temperature using an empirical heat loss factor model\n as implemented in PVsyst.\n@@ -313,12 +314,14 @@ def pvsyst_cell(poa_global, temp_air, wind_speed=1.0, u_c=29.0, u_v=0.0,\n u_v : float, default 0.0\n Combined heat loss factor influenced by wind. Parameter :math:`U_{v}`\n in :eq:`pvsyst`.\n- :math:`\\left[ \\frac{\\text{W}/\\text{m}^2}{\\text{C}\\ \\left( \\text{m/s} \\right)} \\right]`\n+ :math:`\\left[ \\frac{\\text{W}/\\text{m}^2}{\\text{C}\\ \\left( \\text{m/s} \\right)} \\right]` # noQA: E501\n+\n+ eta_m : numeric, default None (deprecated, use module_efficiency instead)\n \n- eta_m : numeric, default 0.1\n- Module external efficiency as a fraction, i.e.,\n- :math:`DC\\ power / (POA\\ irradiance \\times module\\ area)`.\n- Parameter :math:`\\eta_{m}` in :eq:`pvsyst`.\n+ module_efficiency : numeric, default 0.1\n+ Module external efficiency as a fraction. Parameter :math:`\\eta_{m}`\n+ in :eq:`pvsyst`. Calculate as\n+ :math:`\\eta_{m} = DC\\ power / (POA\\ irradiance \\times module\\ area)`.\n \n alpha_absorption : numeric, default 0.9\n Absorption coefficient. Parameter :math:`\\alpha` in :eq:`pvsyst`.\n@@ -370,8 +373,13 @@ def pvsyst_cell(poa_global, temp_air, wind_speed=1.0, u_c=29.0, u_v=0.0,\n 37.93103448275862\n \"\"\"\n \n+ if eta_m:\n+ warn_deprecated(\n+ since='v0.9', message='eta_m overwriting module_efficiency',\n+ name='eta_m', alternative='module_efficiency', removal='v0.10')\n+ module_efficiency = eta_m\n total_loss_factor = u_c + u_v * wind_speed\n- heat_input = poa_global * alpha_absorption * (1 - eta_m)\n+ heat_input = poa_global * alpha_absorption * (1 - module_efficiency)\n temp_difference = heat_input / total_loss_factor\n return temp_air + temp_difference\n \n@@ -719,7 +727,7 @@ def _adj_for_mounting_standoff(x):\n [0., 18., 11., 6., 2., 0.])\n \n \n-def noct_sam(poa_global, temp_air, wind_speed, noct, eta_m_ref,\n+def noct_sam(poa_global, temp_air, wind_speed, noct, module_efficiency,\n effective_irradiance=None, transmittance_absorptance=0.9,\n array_height=1, mount_standoff=4):\n r'''\n@@ -744,9 +752,9 @@ def noct_sam(poa_global, temp_air, wind_speed, noct, eta_m_ref,\n Nominal operating cell temperature [C], determined at conditions of\n 800 W/m^2 irradiance, 20 C ambient air temperature and 1 m/s wind.\n \n- eta_m_ref : float\n+ module_efficiency : float\n Module external efficiency [unitless] at reference conditions of\n- 1000 W/m^2 and 20C. Calculate as\n+ 1000 W/m^2 and 20C. Denoted as :math:`eta_{m}` in [1]_. Calculate as\n :math:`\\eta_{m} = \\frac{V_{mp} I_{mp}}{A \\times 1000 W/m^2}`\n where A is module area [m^2].\n \n@@ -810,6 +818,6 @@ def noct_sam(poa_global, temp_air, wind_speed, noct, eta_m_ref,\n # [1] Eq. 10.37 isn't clear on exactly what \"G\" is. SAM SSC code uses\n # poa_global where G appears\n cell_temp_init = poa_global / 800. * (noct_adj - 20.)\n- heat_loss = 1 - eta_m_ref / tau_alpha\n+ heat_loss = 1 - module_efficiency / tau_alpha\n wind_loss = 9.5 / (5.7 + 3.8 * wind_adj)\n return temp_air + cell_temp_init * heat_loss * wind_loss\n", "test_patch": "diff --git a/pvlib/tests/test_modelchain.py b/pvlib/tests/test_modelchain.py\n--- a/pvlib/tests/test_modelchain.py\n+++ b/pvlib/tests/test_modelchain.py\n@@ -201,7 +201,7 @@ def pvwatts_dc_pvwatts_ac_faiman_temp_system():\n @pytest.fixture(scope=\"function\")\n def pvwatts_dc_pvwatts_ac_pvsyst_temp_system():\n module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003}\n- temp_model_params = {'u_c': 29.0, 'u_v': 0.0, 'eta_m': 0.1,\n+ temp_model_params = {'u_c': 29.0, 'u_v': 0.0, 'module_efficiency': 0.1,\n 'alpha_absorption': 0.9}\n inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95}\n system = PVSystem(surface_tilt=32.2, surface_azimuth=180,\n@@ -226,7 +226,7 @@ def pvwatts_dc_pvwatts_ac_fuentes_temp_system():\n @pytest.fixture(scope=\"function\")\n def pvwatts_dc_pvwatts_ac_noct_sam_temp_system():\n module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003}\n- temp_model_params = {'noct': 45, 'eta_m_ref': 0.2}\n+ temp_model_params = {'noct': 45, 'module_efficiency': 0.2}\n inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95}\n system = PVSystem(surface_tilt=32.2, surface_azimuth=180,\n module_parameters=module_parameters,\n@@ -710,7 +710,7 @@ def test_run_model_with_weather_noct_sam_temp(sapm_dc_snl_ac_system, location,\n weather['wind_speed'] = 5\n weather['temp_air'] = 10\n sapm_dc_snl_ac_system.temperature_model_parameters = {\n- 'noct': 45, 'eta_m_ref': 0.2\n+ 'noct': 45, 'module_efficiency': 0.2\n }\n mc = ModelChain(sapm_dc_snl_ac_system, location)\n mc.temperature_model = 'noct_sam'\n@@ -941,7 +941,7 @@ def test__prepare_temperature_arrays_weather(sapm_dc_snl_ac_system_same_arrays,\n ModelChain.faiman_temp),\n ({'noct_installed': 45},\n ModelChain.fuentes_temp),\n- ({'noct': 45, 'eta_m_ref': 0.2},\n+ ({'noct': 45, 'module_efficiency': 0.2},\n ModelChain.noct_sam_temp)])\n def test_temperature_models_arrays_multi_weather(\n temp_params, temp_model,\ndiff --git a/pvlib/tests/test_pvsystem.py b/pvlib/tests/test_pvsystem.py\n--- a/pvlib/tests/test_pvsystem.py\n+++ b/pvlib/tests/test_pvsystem.py\n@@ -392,7 +392,7 @@ def two_array_system(pvsyst_module_params, cec_module_params):\n temperature_model['noct_installed'] = 45\n # parameters for noct_sam temperature model\n temperature_model['noct'] = 45.\n- temperature_model['eta_m_ref'] = 0.2\n+ temperature_model['module_efficiency'] = 0.2\n module_params = {**pvsyst_module_params, **cec_module_params}\n return pvsystem.PVSystem(\n arrays=[\n@@ -471,8 +471,9 @@ def test_PVSystem_pvsyst_celltemp(mocker):\n temp_model_params = temperature.TEMPERATURE_MODEL_PARAMETERS['pvsyst'][\n parameter_set]\n alpha_absorption = 0.85\n- eta_m = 0.17\n- module_parameters = {'alpha_absorption': alpha_absorption, 'eta_m': eta_m}\n+ module_efficiency = 0.17\n+ module_parameters = {'alpha_absorption': alpha_absorption,\n+ 'module_efficiency': module_efficiency}\n system = pvsystem.PVSystem(module_parameters=module_parameters,\n temperature_model_parameters=temp_model_params)\n mocker.spy(temperature, 'pvsyst_cell')\n@@ -481,8 +482,9 @@ def test_PVSystem_pvsyst_celltemp(mocker):\n wind = 0.5\n out = system.pvsyst_celltemp(irrad, temp, wind_speed=wind)\n temperature.pvsyst_cell.assert_called_once_with(\n- irrad, temp, wind, temp_model_params['u_c'], temp_model_params['u_v'],\n- eta_m, alpha_absorption)\n+ irrad, temp, wind_speed=wind, u_c=temp_model_params['u_c'],\n+ u_v=temp_model_params['u_v'], module_efficiency=module_efficiency,\n+ alpha_absorption=alpha_absorption)\n assert (out < 90) and (out > 70)\n \n \n@@ -500,16 +502,16 @@ def test_PVSystem_faiman_celltemp(mocker):\n \n \n def test_PVSystem_noct_celltemp(mocker):\n- poa_global, temp_air, wind_speed, noct, eta_m_ref = (1000., 25., 1., 45.,\n- 0.2)\n+ poa_global, temp_air, wind_speed, noct, module_efficiency = (\n+ 1000., 25., 1., 45., 0.2)\n expected = 55.230790492\n- temp_model_params = {'noct': noct, 'eta_m_ref': eta_m_ref}\n+ temp_model_params = {'noct': noct, 'module_efficiency': module_efficiency}\n system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params)\n mocker.spy(temperature, 'noct_sam')\n out = system.noct_sam_celltemp(poa_global, temp_air, wind_speed)\n temperature.noct_sam.assert_called_once_with(\n poa_global, temp_air, wind_speed, effective_irradiance=None, noct=noct,\n- eta_m_ref=eta_m_ref)\n+ module_efficiency=module_efficiency)\n assert_allclose(out, expected)\n # dufferent types\n out = system.noct_sam_celltemp(np.array(poa_global), np.array(temp_air),\n@@ -533,8 +535,8 @@ def test_PVSystem_noct_celltemp(mocker):\n \n \n def test_PVSystem_noct_celltemp_error():\n- poa_global, temp_air, wind_speed, eta_m_ref = (1000., 25., 1., 0.2)\n- temp_model_params = {'eta_m_ref': eta_m_ref}\n+ poa_global, temp_air, wind_speed, module_efficiency = (1000., 25., 1., 0.2)\n+ temp_model_params = {'module_efficiency': module_efficiency}\n system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params)\n with pytest.raises(KeyError):\n system.noct_sam_celltemp(poa_global, temp_air, wind_speed)\ndiff --git a/pvlib/tests/test_temperature.py b/pvlib/tests/test_temperature.py\n--- a/pvlib/tests/test_temperature.py\n+++ b/pvlib/tests/test_temperature.py\n@@ -6,6 +6,7 @@\n from numpy.testing import assert_allclose\n \n from pvlib import temperature, tools\n+from pvlib._deprecation import pvlibDeprecationWarning\n \n \n @pytest.fixture\n@@ -72,7 +73,7 @@ def test_pvsyst_cell_default():\n \n def test_pvsyst_cell_kwargs():\n result = temperature.pvsyst_cell(900, 20, wind_speed=5.0, u_c=23.5,\n- u_v=6.25, eta_m=0.1)\n+ u_v=6.25, module_efficiency=0.1)\n assert_allclose(result, 33.315, 0.001)\n \n \n@@ -96,6 +97,13 @@ def test_pvsyst_cell_series():\n assert_series_equal(expected, result)\n \n \n+def test_pvsyst_cell_eta_m_deprecated():\n+ with pytest.warns(pvlibDeprecationWarning):\n+ result = temperature.pvsyst_cell(900, 20, wind_speed=5.0, u_c=23.5,\n+ u_v=6.25, eta_m=0.1)\n+ assert_allclose(result, 33.315, 0.001)\n+\n+\n def test_faiman_default():\n result = temperature.faiman(900, 20, 5)\n assert_allclose(result, 35.203, 0.001)\n@@ -215,16 +223,16 @@ def test_fuentes_timezone(tz):\n \n \n def test_noct_sam():\n- poa_global, temp_air, wind_speed, noct, eta_m_ref = (1000., 25., 1., 45.,\n- 0.2)\n+ poa_global, temp_air, wind_speed, noct, module_efficiency = (\n+ 1000., 25., 1., 45., 0.2)\n expected = 55.230790492\n result = temperature.noct_sam(poa_global, temp_air, wind_speed, noct,\n- eta_m_ref)\n+ module_efficiency)\n assert_allclose(result, expected)\n # test with different types\n result = temperature.noct_sam(np.array(poa_global), np.array(temp_air),\n np.array(wind_speed), np.array(noct),\n- np.array(eta_m_ref))\n+ np.array(module_efficiency))\n assert_allclose(result, expected)\n dr = pd.date_range(start='2020-01-01 12:00:00', end='2020-01-01 13:00:00',\n freq='1H')\n@@ -232,7 +240,7 @@ def test_noct_sam():\n pd.Series(index=dr, data=temp_air),\n pd.Series(index=dr, data=wind_speed),\n pd.Series(index=dr, data=noct),\n- eta_m_ref)\n+ module_efficiency)\n assert_series_equal(result, pd.Series(index=dr, data=expected))\n \n \n@@ -242,7 +250,7 @@ def test_noct_sam_against_sam():\n # NOCT cell temperature model), with the only change being the soiling\n # loss is set to 0. Weather input is TMY3 for Phoenix AZ.\n # Values are taken from the Jan 1 12:00:00 timestamp.\n- poa_total, temp_air, wind_speed, noct, eta_m_ref = (\n+ poa_total, temp_air, wind_speed, noct, module_efficiency = (\n 860.673, 25, 3, 46.4, 0.20551)\n poa_total_after_refl = 851.458 # from SAM output\n # compute effective irradiance\n@@ -259,7 +267,7 @@ def test_noct_sam_against_sam():\n array_height = 1\n mount_standoff = 4.0\n result = temperature.noct_sam(poa_total, temp_air, wind_speed, noct,\n- eta_m_ref, effective_irradiance,\n+ module_efficiency, effective_irradiance,\n transmittance_absorptance, array_height,\n mount_standoff)\n expected = 43.0655\n@@ -268,14 +276,14 @@ def test_noct_sam_against_sam():\n \n \n def test_noct_sam_options():\n- poa_global, temp_air, wind_speed, noct, eta_m_ref = (1000., 25., 1., 45.,\n- 0.2)\n+ poa_global, temp_air, wind_speed, noct, module_efficiency = (\n+ 1000., 25., 1., 45., 0.2)\n effective_irradiance = 1100.\n transmittance_absorptance = 0.8\n array_height = 2\n mount_standoff = 2.0\n result = temperature.noct_sam(poa_global, temp_air, wind_speed, noct,\n- eta_m_ref, effective_irradiance,\n+ module_efficiency, effective_irradiance,\n transmittance_absorptance, array_height,\n mount_standoff)\n expected = 60.477703576\n", "problem_statement": "change eta_m to module_efficiency\n`temperature.noct_sam` uses `eta_m_ref` to describe the module efficiency at reference conditions and `temperature.pvsyst_cell` uses `eta_m` to describe the module efficiency generically.\r\n\r\nJust calling both of these `module_efficiency` would make the function signatures easily understandable by many more people. I'd be ok with `module_efficiency_ref` but I don't think that precision is very important.\r\n\r\nI skimmed [pvterms](https://duramat.github.io/pv-terms/) and didn't see a suggestion for this quantity.\r\n\r\n`temperature.noct_sam` has not yet been released and it's just a positional argument, so changing the name is trivial. `temperature.pvsyst_cell` would need a deprecation cycle.\r\n\r\nOriginally discussed in https://github.com/pvlib/pvlib-python/pull/1177#discussion_r589081257\r\n\r\nAssignment of milestone indicates that we will act on this or close it forever before 0.9 is released.\r\n\n", "hints_text": "I support this change.", "created_at": "2021-05-06T16:02:38Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_modelchain.py::test_run_model_with_weather_noct_sam_temp", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params4-noct_sam_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[noct_sam_temp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvsyst_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[noct_sam_celltemp]", "pvlib/tests/test_temperature.py::test_pvsyst_cell_kwargs", "pvlib/tests/test_temperature.py::test_pvsyst_cell_eta_m_deprecated"], "PASS_TO_PASS": ["pvlib/tests/test_modelchain.py::test_ModelChain_creation", "pvlib/tests/test_modelchain.py::test_with_sapm", "pvlib/tests/test_modelchain.py::test_with_pvwatts", "pvlib/tests/test_modelchain.py::test_run_model_with_irradiance", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_irradiance_arrays_no_loss_input_type[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_invalid_inverter_params_arrays[adr]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_multi_weather[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_no_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_arrays_one_missing_irradiance", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_weather_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_ModelChain_times_error_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_times_arrays", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dhi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[ghi]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_missing_irrad_component[dni]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[tuple-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-sandia]", "pvlib/tests/test_modelchain.py::test_run_model_arrays_weather[list-pvwatts]", "pvlib/tests/test_modelchain.py::test_run_model_perez", "pvlib/tests/test_modelchain.py::test_run_model_gueymard_perez", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_sapm_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_pvsyst_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_faiman_temp", "pvlib/tests/test_modelchain.py::test_run_model_with_weather_fuentes_temp", "pvlib/tests/test_modelchain.py::test_run_model_tracker", "pvlib/tests/test_modelchain.py::test_run_model_tracker_list", "pvlib/tests/test_modelchain.py::test__assign_total_irrad", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_multi_data[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_wrong_number_arrays[list]", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_different_indices", "pvlib/tests/test_modelchain.py::test_prepare_inputs_from_poa_arrays_missing_column", "pvlib/tests/test_modelchain.py::test__prepare_temperature", "pvlib/tests/test_modelchain.py::test__prepare_temperature_len1_weather_tuple", "pvlib/tests/test_modelchain.py::test__prepare_temperature_arrays_weather", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params0-sapm_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params1-pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params2-faiman_temp]", "pvlib/tests/test_modelchain.py::test_temperature_models_arrays_multi_weather[temp_params3-fuentes_temp]", "pvlib/tests/test_modelchain.py::test_run_model_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_arrays_solar_position_weather", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_tracking", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_multi_array[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[<lambda>]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_no_poa_global[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_poa_global_differs", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays_error[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_minimal_input", "pvlib/tests/test_modelchain.py::test_run_model_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_poa_singleton_weather_single_array", "pvlib/tests/test_modelchain.py::test_run_model_from_effective_irradiance_weather_single_array", "pvlib/tests/test_modelchain.py::test_infer_dc_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[desoto]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[singlediode]", "pvlib/tests/test_modelchain.py::test_infer_dc_model[pvwatts_dc]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[cec]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[desoto]", "pvlib/tests/test_modelchain.py::test_singlediode_dc_arrays[pvsyst]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec]", "pvlib/tests/test_modelchain.py::test_infer_spectral_model[cec_native]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[sapm_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[faiman_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[pvsyst_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model[fuentes_temp]", "pvlib/tests/test_modelchain.py::test_infer_temp_model_invalid", "pvlib/tests/test_modelchain.py::test_temperature_model_inconsistent", "pvlib/tests/test_modelchain.py::test_dc_model_user_func", "pvlib/tests/test_modelchain.py::test_pvwatts_dc_multiple_strings", "pvlib/tests/test_modelchain.py::test_ac_models[sandia]", "pvlib/tests/test_modelchain.py::test_ac_models[adr]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts]", "pvlib/tests/test_modelchain.py::test_ac_models[sandia_multi]", "pvlib/tests/test_modelchain.py::test_ac_models[pvwatts_multi]", "pvlib/tests/test_modelchain.py::test_ac_model_user_func", "pvlib/tests/test_modelchain.py::test_ac_model_not_a_model", "pvlib/tests/test_modelchain.py::test_infer_ac_model_invalid_params", "pvlib/tests/test_modelchain.py::test_aoi_models[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[ashrae]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[physical]", "pvlib/tests/test_modelchain.py::test_aoi_models_singleon_weather_single_array[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_aoi_model_no_loss", "pvlib/tests/test_modelchain.py::test_aoi_model_user_func", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[sapm]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[ashrae]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[physical]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model[martin_ruiz]", "pvlib/tests/test_modelchain.py::test_infer_aoi_model_invalid", "pvlib/tests/test_modelchain.py::test_spectral_models[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[sapm]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[first_solar]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[no_loss]", "pvlib/tests/test_modelchain.py::test_spectral_models_singleton_weather_single_array[constant_spectral_loss]", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_ohms_from_percent", "pvlib/tests/test_modelchain.py::test_dc_ohmic_model_no_dc_ohmic_loss", "pvlib/tests/test_modelchain.py::test_dc_ohmic_ext_def", "pvlib/tests/test_modelchain.py::test_dc_ohmic_not_a_model", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts", "pvlib/tests/test_modelchain.py::test_losses_models_pvwatts_arrays", "pvlib/tests/test_modelchain.py::test_losses_models_ext_def", "pvlib/tests/test_modelchain.py::test_losses_models_no_loss", "pvlib/tests/test_modelchain.py::test_invalid_dc_model_params", "pvlib/tests/test_modelchain.py::test_invalid_models[dc_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[ac_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[aoi_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[spectral_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[temperature_model]", "pvlib/tests/test_modelchain.py::test_invalid_models[losses_model]", "pvlib/tests/test_modelchain.py::test_bad_get_orientation", "pvlib/tests/test_modelchain.py::test_with_sapm_pvsystem_arrays", "pvlib/tests/test_modelchain.py::test_ModelChain_no_extra_kwargs", "pvlib/tests/test_modelchain.py::test_ModelChain_attributes_deprecated_10", "pvlib/tests/test_modelchain.py::test_basic_chain_alt_az", "pvlib/tests/test_modelchain.py::test_basic_chain_altitude_pressure", "pvlib/tests/test_modelchain.py::test_complete_irradiance_clean_run", "pvlib/tests/test_modelchain.py::test_complete_irradiance", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays[list]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[tuple]", "pvlib/tests/test_modelchain.py::test_complete_irradiance_arrays_wrong_length[list]", "pvlib/tests/test_modelchain.py::test_unknown_attribute", "pvlib/tests/test_modelchain.py::test_inconsistent_array_params", "pvlib/tests/test_modelchain.py::test_modelchain__common_keys", "pvlib/tests/test_modelchain.py::test__irrad_for_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[ashrae-model_params0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[physical-model_params1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam[martin_ruiz-model_params2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_iam", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_interp", "pvlib/tests/test_pvsystem.py::test__normalize_sam_product_names", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_iam_invalid", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_raise_no_parameters", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecmod", "pvlib/tests/test_pvsystem.py::test_retrieve_sam_cecinverter", "pvlib/tests/test_pvsystem.py::test_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[1.5-1.00028714375]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_spectral_loss[airmass2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_spectral_loss", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters0-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters1-multisi-None]", "pvlib/tests/test_pvsystem.py::test_PVSystem_first_solar_spectral_loss[module_parameters2-None-coefficients2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_first_solar_spectral_loss", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input0-1140.0510967821876]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input1-expected1]", "pvlib/tests/test_pvsystem.py::test_sapm_effective_irradiance[test_input2-expected2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_effective_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[20-poa_diffuse0-aoi0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct1-poa_diffuse1-aoi1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_effective_irradiance_value_error[poa_direct2-poa_diffuse2-20]", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_sapm_celltemp_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_sapm_celltemp_different_arrays", "pvlib/tests/test_pvsystem.py::test_PVSystem_faiman_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_noct_celltemp_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_functions[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_temp[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_multi_wind[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_short[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_temp_too_long[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_short[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_wind_too_long[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[faiman_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[pvsyst_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[sapm_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[fuentes_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_celltemp_poa_length_mismatch[noct_sam_celltemp]", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp", "pvlib/tests/test_pvsystem.py::test_PVSystem_fuentes_celltemp_override", "pvlib/tests/test_pvsystem.py::test_Array__infer_temperature_model_params", "pvlib/tests/test_pvsystem.py::test_Array__infer_cell_type", "pvlib/tests/test_pvsystem.py::test_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_calcparams_cec", "pvlib/tests/test_pvsystem.py::test_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_desoto", "pvlib/tests/test_pvsystem.py::test_PVSystem_calcparams_pvsyst", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_pvsyst]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_desoto]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams[calcparams_cec]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-1-celltemp0]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_desoto-irrad1-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-1-celltemp2]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_cec-irrad3-1]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-1-celltemp4]", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_calcparams_value_error[calcparams_pvsyst-irrad5-1]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i0-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i1-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i2-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i3-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i4-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i5-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i6-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i7-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i8-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i9-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_v_from_i[fixture_v_from_i10-newton-1e-08]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i0]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i1]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i2]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i3]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i4]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i5]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i6]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i7]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i8]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i9]", "pvlib/tests/test_pvsystem.py::test_i_from_v_from_i[fixture_v_from_i10]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v0-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v1-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v2-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v3-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v4-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v5-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-lambertw-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-brentq-1e-11]", "pvlib/tests/test_pvsystem.py::test_i_from_v[fixture_i_from_v6-newton-1e-11]", "pvlib/tests/test_pvsystem.py::test_PVSystem_i_from_v", "pvlib/tests/test_pvsystem.py::test_i_from_v_size", "pvlib/tests/test_pvsystem.py::test_v_from_i_size", "pvlib/tests/test_pvsystem.py::test_mpp_floats", "pvlib/tests/test_pvsystem.py::test_mpp_array", "pvlib/tests/test_pvsystem.py::test_mpp_series", "pvlib/tests/test_pvsystem.py::test_singlediode_series", "pvlib/tests/test_pvsystem.py::test_singlediode_array", "pvlib/tests/test_pvsystem.py::test_singlediode_floats", "pvlib/tests/test_pvsystem.py::test_singlediode_floats_ivcurve", "pvlib/tests/test_pvsystem.py::test_singlediode_series_ivcurve", "pvlib/tests/test_pvsystem.py::test_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_scale_voltage_current_power", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia", "pvlib/tests/test_pvsystem.py::test_PVSystem_snlinverter", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_sandia_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_pvwatts_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[sandia]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[adr]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_single_array_tuple_input[pvwatts]", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_adr_multi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_ac_invalid", "pvlib/tests/test_pvsystem.py::test_PVSystem_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_creation", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_get_aoi", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_irradiance_model", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array_get_irradiance_multi_irrad", "pvlib/tests/test_pvsystem.py::test_PVSystem_change_surface_azimuth", "pvlib/tests/test_pvsystem.py::test_PVSystem_get_albedo", "pvlib/tests/test_pvsystem.py::test_PVSystem_modules_per_string", "pvlib/tests/test_pvsystem.py::test_PVSystem_strings_per_inverter", "pvlib/tests/test_pvsystem.py::test_PVSystem___repr__", "pvlib/tests/test_pvsystem.py::test_PVSystem_multi_array___repr__", "pvlib/tests/test_pvsystem.py::test_Array___repr__", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_scalars", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_dc_series", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_default", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_arrays", "pvlib/tests/test_pvsystem.py::test_pvwatts_losses_series", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_dc_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc", "pvlib/tests/test_pvsystem.py::test_PVSystem_multiple_array_pvwatts_dc_value_error", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_losses", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac", "pvlib/tests/test_pvsystem.py::test_PVSystem_pvwatts_ac_kwargs", "pvlib/tests/test_pvsystem.py::test_PVSystem_num_arrays", "pvlib/tests/test_pvsystem.py::test_combine_loss_factors", "pvlib/tests/test_pvsystem.py::test_no_extra_kwargs", "pvlib/tests/test_pvsystem.py::test_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_PVSystem_dc_ohms_from_percent", "pvlib/tests/test_pvsystem.py::test_dc_ohmic_losses", "pvlib/tests/test_pvsystem.py::test_Array_dc_ohms_from_percent", "pvlib/tests/test_temperature.py::test_sapm_cell", "pvlib/tests/test_temperature.py::test_sapm_module", "pvlib/tests/test_temperature.py::test_sapm_cell_from_module", "pvlib/tests/test_temperature.py::test_sapm_ndarray", "pvlib/tests/test_temperature.py::test_sapm_series", "pvlib/tests/test_temperature.py::test_pvsyst_cell_default", "pvlib/tests/test_temperature.py::test_pvsyst_cell_ndarray", "pvlib/tests/test_temperature.py::test_pvsyst_cell_series", "pvlib/tests/test_temperature.py::test_faiman_default", "pvlib/tests/test_temperature.py::test_faiman_kwargs", "pvlib/tests/test_temperature.py::test_faiman_list", "pvlib/tests/test_temperature.py::test_faiman_ndarray", "pvlib/tests/test_temperature.py::test_ross", "pvlib/tests/test_temperature.py::test_faiman_series", "pvlib/tests/test_temperature.py::test__temperature_model_params", "pvlib/tests/test_temperature.py::test_fuentes[pvwatts_8760_rackmount.csv-45]", "pvlib/tests/test_temperature.py::test_fuentes[pvwatts_8760_roofmount.csv-49]", "pvlib/tests/test_temperature.py::test_fuentes_timezone[None]", "pvlib/tests/test_temperature.py::test_fuentes_timezone[Etc/GMT+5]", "pvlib/tests/test_temperature.py::test_noct_sam", "pvlib/tests/test_temperature.py::test_noct_sam_against_sam", "pvlib/tests/test_temperature.py::test_noct_sam_options", "pvlib/tests/test_temperature.py::test_noct_sam_errors"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pvlib/pvlib-python", "instance_id": "pvlib__pvlib-python-1154", "base_commit": "0b8f24c265d76320067a5ee908a57d475cd1bb24", "patch": "diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py\n--- a/pvlib/irradiance.py\n+++ b/pvlib/irradiance.py\n@@ -886,8 +886,9 @@ def reindl(surface_tilt, surface_azimuth, dhi, dni, ghi, dni_extra,\n # these are the () and [] sub-terms of the second term of eqn 8\n term1 = 1 - AI\n term2 = 0.5 * (1 + tools.cosd(surface_tilt))\n- term3 = 1 + np.sqrt(HB / ghi) * (tools.sind(0.5 * surface_tilt) ** 3)\n-\n+ with np.errstate(invalid='ignore', divide='ignore'):\n+ hb_to_ghi = np.where(ghi == 0, 0, np.divide(HB, ghi))\n+ term3 = 1 + np.sqrt(hb_to_ghi) * (tools.sind(0.5 * surface_tilt)**3)\n sky_diffuse = dhi * (AI * Rb + term1 * term2 * term3)\n sky_diffuse = np.maximum(sky_diffuse, 0)\n \n", "test_patch": "diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py\n--- a/pvlib/tests/test_irradiance.py\n+++ b/pvlib/tests/test_irradiance.py\n@@ -203,7 +203,7 @@ def test_reindl(irrad_data, ephem_data, dni_et):\n 40, 180, irrad_data['dhi'], irrad_data['dni'], irrad_data['ghi'],\n dni_et, ephem_data['apparent_zenith'], ephem_data['azimuth'])\n # values from matlab 1.4 code\n- assert_allclose(result, [np.nan, 27.9412, 104.1317, 34.1663], atol=1e-4)\n+ assert_allclose(result, [0., 27.9412, 104.1317, 34.1663], atol=1e-4)\n \n \n def test_king(irrad_data, ephem_data):\n", "problem_statement": "pvlib.irradiance.reindl() model generates NaNs when GHI = 0\n**Describe the bug**\r\nThe reindl function should give zero sky diffuse when GHI is zero. Instead it generates NaN or Inf values due to \"term3\" having a quotient that divides by GHI. \r\n\r\n**Expected behavior**\r\nThe reindl function should result in zero sky diffuse when GHI is zero.\r\n\r\n\npvlib.irradiance.reindl() model generates NaNs when GHI = 0\n**Describe the bug**\r\nThe reindl function should give zero sky diffuse when GHI is zero. Instead it generates NaN or Inf values due to \"term3\" having a quotient that divides by GHI. \r\n\r\n**Expected behavior**\r\nThe reindl function should result in zero sky diffuse when GHI is zero.\r\n\r\n\n", "hints_text": "Verified. Looks like an easy fix.\nVerified. Looks like an easy fix.", "created_at": "2021-01-29T20:53:24Z", "version": "0.8", "FAIL_TO_PASS": ["pvlib/tests/test_irradiance.py::test_reindl"], "PASS_TO_PASS": ["pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_float", "pvlib/tests/test_irradiance.py::test_grounddiffuse_simple_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_invalid", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent"], "environment_setup_commit": "ef8ad2fee9840a77d14b0dfd17fc489dd85c9b91"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1741", "base_commit": "bcaecce5634a30313e574deae101ee017ffeff17", "patch": "diff --git a/astroid/arguments.py b/astroid/arguments.py\n--- a/astroid/arguments.py\n+++ b/astroid/arguments.py\n@@ -8,7 +8,7 @@\n from astroid.bases import Instance\n from astroid.context import CallContext, InferenceContext\n from astroid.exceptions import InferenceError, NoDefault\n-from astroid.util import Uninferable\n+from astroid.util import Uninferable, UninferableBase\n \n \n class CallSite:\n@@ -44,12 +44,12 @@ def __init__(\n self._unpacked_kwargs = self._unpack_keywords(keywords, context=context)\n \n self.positional_arguments = [\n- arg for arg in self._unpacked_args if arg is not Uninferable\n+ arg for arg in self._unpacked_args if not isinstance(arg, UninferableBase)\n ]\n self.keyword_arguments = {\n key: value\n for key, value in self._unpacked_kwargs.items()\n- if value is not Uninferable\n+ if not isinstance(value, UninferableBase)\n }\n \n @classmethod\n@@ -142,7 +142,7 @@ def _unpack_args(self, args, context: InferenceContext | None = None):\n except StopIteration:\n continue\n \n- if inferred is Uninferable:\n+ if isinstance(inferred, UninferableBase):\n values.append(Uninferable)\n continue\n if not hasattr(inferred, \"elts\"):\ndiff --git a/astroid/bases.py b/astroid/bases.py\n--- a/astroid/bases.py\n+++ b/astroid/bases.py\n@@ -28,7 +28,7 @@\n NameInferenceError,\n )\n from astroid.typing import InferBinaryOp, InferenceErrorInfo, InferenceResult\n-from astroid.util import Uninferable, lazy_descriptor, lazy_import\n+from astroid.util import Uninferable, UninferableBase, lazy_descriptor, lazy_import\n \n if sys.version_info >= (3, 8):\n from typing import Literal\n@@ -79,7 +79,9 @@ def _is_property(meth, context: InferenceContext | None = None) -> bool:\n if PROPERTIES.intersection(decoratornames):\n return True\n stripped = {\n- name.split(\".\")[-1] for name in decoratornames if name is not Uninferable\n+ name.split(\".\")[-1]\n+ for name in decoratornames\n+ if not isinstance(name, UninferableBase)\n }\n if any(name in stripped for name in POSSIBLE_PROPERTIES):\n return True\n@@ -89,7 +91,7 @@ def _is_property(meth, context: InferenceContext | None = None) -> bool:\n return False\n for decorator in meth.decorators.nodes or ():\n inferred = helpers.safe_infer(decorator, context=context)\n- if inferred is None or inferred is Uninferable:\n+ if inferred is None or isinstance(inferred, UninferableBase):\n continue\n if inferred.__class__.__name__ == \"ClassDef\":\n for base_class in inferred.bases:\n@@ -144,7 +146,7 @@ def infer( # type: ignore[return]\n \n \n def _infer_stmts(\n- stmts: Sequence[nodes.NodeNG | type[Uninferable] | Instance],\n+ stmts: Sequence[nodes.NodeNG | UninferableBase | Instance],\n context: InferenceContext | None,\n frame: nodes.NodeNG | Instance | None = None,\n ) -> collections.abc.Generator[InferenceResult, None, None]:\n@@ -161,7 +163,7 @@ def _infer_stmts(\n context = InferenceContext()\n \n for stmt in stmts:\n- if stmt is Uninferable:\n+ if isinstance(stmt, UninferableBase):\n yield stmt\n inferred = True\n continue\n@@ -172,8 +174,7 @@ def _infer_stmts(\n for constraint_stmt, potential_constraints in constraints.items():\n if not constraint_stmt.parent_of(stmt):\n stmt_constraints.update(potential_constraints)\n- # Mypy doesn't recognize that 'stmt' can't be Uninferable\n- for inf in stmt.infer(context=context): # type: ignore[union-attr]\n+ for inf in stmt.infer(context=context):\n if all(constraint.satisfied_by(inf) for constraint in stmt_constraints):\n yield inf\n inferred = True\n@@ -206,7 +207,7 @@ def _infer_method_result_truth(instance, method_name, context):\n try:\n context.callcontext = CallContext(args=[], callee=meth)\n for value in meth.infer_call_result(instance, context=context):\n- if value is Uninferable:\n+ if isinstance(value, UninferableBase):\n return value\n try:\n inferred = next(value.infer(context=context))\n@@ -316,7 +317,7 @@ def infer_call_result(\n \n # Otherwise we infer the call to the __call__ dunder normally\n for node in self._proxied.igetattr(\"__call__\", context):\n- if node is Uninferable or not node.callable():\n+ if isinstance(node, UninferableBase) or not node.callable():\n continue\n for res in node.infer_call_result(caller, context):\n inferred = True\n@@ -458,7 +459,7 @@ def _infer_builtin_new(\n caller: nodes.Call,\n context: InferenceContext,\n ) -> collections.abc.Generator[\n- nodes.Const | Instance | type[Uninferable], None, None\n+ nodes.Const | Instance | UninferableBase, None, None\n ]:\n if not caller.args:\n return\n@@ -477,7 +478,7 @@ def _infer_builtin_new(\n \n node_context = context.extra_context.get(caller.args[0])\n for inferred in caller.args[0].infer(context=node_context):\n- if inferred is Uninferable:\n+ if isinstance(inferred, UninferableBase):\n yield inferred\n if isinstance(inferred, nodes.ClassDef):\n yield Instance(inferred)\ndiff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py\n--- a/astroid/brain/brain_builtin_inference.py\n+++ b/astroid/brain/brain_builtin_inference.py\n@@ -209,10 +209,10 @@ def _container_generic_inference(node, context, node_type, transform):\n inferred = next(arg.infer(context=context))\n except (InferenceError, StopIteration) as exc:\n raise UseInferenceDefault from exc\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n raise UseInferenceDefault\n transformed = transform(inferred)\n- if not transformed or transformed is util.Uninferable:\n+ if not transformed or isinstance(transformed, util.UninferableBase):\n raise UseInferenceDefault\n return transformed\n \n@@ -423,7 +423,9 @@ def infer_super(node, context: InferenceContext | None = None):\n except (InferenceError, StopIteration) as exc:\n raise UseInferenceDefault from exc\n \n- if mro_pointer is util.Uninferable or mro_type is util.Uninferable:\n+ if isinstance(mro_pointer, util.UninferableBase) or isinstance(\n+ mro_type, util.UninferableBase\n+ ):\n # No way we could understand this.\n raise UseInferenceDefault\n \n@@ -445,7 +447,7 @@ def _infer_getattr_args(node, context):\n except (InferenceError, StopIteration) as exc:\n raise UseInferenceDefault from exc\n \n- if obj is util.Uninferable or attr is util.Uninferable:\n+ if isinstance(obj, util.UninferableBase) or isinstance(attr, util.UninferableBase):\n # If one of the arguments is something we can't infer,\n # then also make the result of the getattr call something\n # which is unknown.\n@@ -467,8 +469,8 @@ def infer_getattr(node, context: InferenceContext | None = None):\n \"\"\"\n obj, attr = _infer_getattr_args(node, context)\n if (\n- obj is util.Uninferable\n- or attr is util.Uninferable\n+ isinstance(obj, util.UninferableBase)\n+ or isinstance(attr, util.UninferableBase)\n or not hasattr(obj, \"igetattr\")\n ):\n return util.Uninferable\n@@ -498,8 +500,8 @@ def infer_hasattr(node, context: InferenceContext | None = None):\n try:\n obj, attr = _infer_getattr_args(node, context)\n if (\n- obj is util.Uninferable\n- or attr is util.Uninferable\n+ isinstance(obj, util.UninferableBase)\n+ or isinstance(attr, util.UninferableBase)\n or not hasattr(obj, \"getattr\")\n ):\n return util.Uninferable\n@@ -530,7 +532,7 @@ def infer_callable(node, context: InferenceContext | None = None):\n inferred = next(argument.infer(context=context))\n except (InferenceError, StopIteration):\n return util.Uninferable\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n return util.Uninferable\n return nodes.Const(inferred.callable())\n \n@@ -585,11 +587,11 @@ def infer_bool(node, context: InferenceContext | None = None):\n inferred = next(argument.infer(context=context))\n except (InferenceError, StopIteration):\n return util.Uninferable\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n return util.Uninferable\n \n bool_value = inferred.bool_value(context=context)\n- if bool_value is util.Uninferable:\n+ if isinstance(bool_value, util.UninferableBase):\n return util.Uninferable\n return nodes.Const(bool_value)\n \n@@ -611,7 +613,7 @@ def infer_slice(node, context: InferenceContext | None = None):\n infer_func = partial(helpers.safe_infer, context=context)\n args = [infer_func(arg) for arg in args]\n for arg in args:\n- if not arg or arg is util.Uninferable:\n+ if not arg or isinstance(arg, util.UninferableBase):\n raise UseInferenceDefault\n if not isinstance(arg, nodes.Const):\n raise UseInferenceDefault\n@@ -725,7 +727,7 @@ def infer_isinstance(callnode, context: InferenceContext | None = None):\n raise UseInferenceDefault(\"TypeError: \" + str(exc)) from exc\n except MroError as exc:\n raise UseInferenceDefault from exc\n- if isinstance_bool is util.Uninferable:\n+ if isinstance(isinstance_bool, util.UninferableBase):\n raise UseInferenceDefault\n return nodes.Const(isinstance_bool)\n \n@@ -811,7 +813,7 @@ def infer_int(node, context: InferenceContext | None = None):\n except (InferenceError, StopIteration) as exc:\n raise UseInferenceDefault(str(exc)) from exc\n \n- if first_value is util.Uninferable:\n+ if isinstance(first_value, util.UninferableBase):\n raise UseInferenceDefault\n \n if isinstance(first_value, nodes.Const) and isinstance(\n@@ -924,7 +926,7 @@ def _is_str_format_call(node: nodes.Call) -> bool:\n \n def _infer_str_format_call(\n node: nodes.Call, context: InferenceContext | None = None\n-) -> Iterator[nodes.Const | type[util.Uninferable]]:\n+) -> Iterator[nodes.Const | util.UninferableBase]:\n \"\"\"Return a Const node based on the template and passed arguments.\"\"\"\n call = arguments.CallSite.from_call(node, context=context)\n if isinstance(node.func.expr, nodes.Name):\ndiff --git a/astroid/brain/brain_dataclasses.py b/astroid/brain/brain_dataclasses.py\n--- a/astroid/brain/brain_dataclasses.py\n+++ b/astroid/brain/brain_dataclasses.py\n@@ -25,7 +25,7 @@\n from astroid.inference_tip import inference_tip\n from astroid.manager import AstroidManager\n from astroid.typing import InferenceResult\n-from astroid.util import Uninferable\n+from astroid.util import Uninferable, UninferableBase\n \n if sys.version_info >= (3, 8):\n from typing import Literal\n@@ -446,7 +446,7 @@ def _looks_like_dataclass_decorator(\n except (InferenceError, StopIteration):\n inferred = Uninferable\n \n- if inferred is Uninferable:\n+ if isinstance(inferred, UninferableBase):\n if isinstance(node, nodes.Name):\n return node.name in decorator_names\n if isinstance(node, nodes.Attribute):\n@@ -594,7 +594,7 @@ def _is_init_var(node: nodes.NodeNG) -> bool:\n \n def _infer_instance_from_annotation(\n node: nodes.NodeNG, ctx: context.InferenceContext | None = None\n-) -> Iterator[type[Uninferable] | bases.Instance]:\n+) -> Iterator[UninferableBase | bases.Instance]:\n \"\"\"Infer an instance corresponding to the type annotation represented by node.\n \n Currently has limited support for the typing module.\ndiff --git a/astroid/brain/brain_functools.py b/astroid/brain/brain_functools.py\n--- a/astroid/brain/brain_functools.py\n+++ b/astroid/brain/brain_functools.py\n@@ -18,7 +18,7 @@\n from astroid.manager import AstroidManager\n from astroid.nodes.node_classes import AssignName, Attribute, Call, Name\n from astroid.nodes.scoped_nodes import FunctionDef\n-from astroid.util import Uninferable\n+from astroid.util import UninferableBase\n \n LRU_CACHE = \"functools.lru_cache\"\n \n@@ -84,7 +84,7 @@ def _functools_partial_inference(\n inferred_wrapped_function = next(partial_function.infer(context=context))\n except (InferenceError, StopIteration) as exc:\n raise UseInferenceDefault from exc\n- if inferred_wrapped_function is Uninferable:\n+ if isinstance(inferred_wrapped_function, UninferableBase):\n raise UseInferenceDefault(\"Cannot infer the wrapped function\")\n if not isinstance(inferred_wrapped_function, FunctionDef):\n raise UseInferenceDefault(\"The wrapped function is not a function\")\ndiff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py\n--- a/astroid/brain/brain_namedtuple_enum.py\n+++ b/astroid/brain/brain_namedtuple_enum.py\n@@ -52,13 +52,13 @@\n \n \n def _infer_first(node, context):\n- if node is util.Uninferable:\n+ if isinstance(node, util.UninferableBase):\n raise UseInferenceDefault\n try:\n value = next(node.infer(context=context))\n except StopIteration as exc:\n raise InferenceError from exc\n- if value is util.Uninferable:\n+ if isinstance(value, util.UninferableBase):\n raise UseInferenceDefault()\n return value\n \ndiff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py\n--- a/astroid/brain/brain_typing.py\n+++ b/astroid/brain/brain_typing.py\n@@ -33,7 +33,6 @@\n Tuple,\n )\n from astroid.nodes.scoped_nodes import ClassDef, FunctionDef\n-from astroid.util import Uninferable\n \n if sys.version_info >= (3, 8):\n from typing import Final\n@@ -297,7 +296,7 @@ def infer_typing_alias(\n col_offset=assign_name.col_offset,\n parent=node.parent,\n )\n- if res != Uninferable and isinstance(res, ClassDef):\n+ if isinstance(res, ClassDef):\n # Only add `res` as base if it's a `ClassDef`\n # This isn't the case for `typing.Pattern` and `typing.Match`\n class_def.postinit(bases=[res], body=[], decorators=None)\ndiff --git a/astroid/builder.py b/astroid/builder.py\n--- a/astroid/builder.py\n+++ b/astroid/builder.py\n@@ -238,7 +238,7 @@ def delayed_assattr(self, node: nodes.AssignAttr) -> None:\n try:\n frame = node.frame(future=True)\n for inferred in node.expr.infer():\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n continue\n try:\n # pylint: disable=unidiomatic-typecheck # We want a narrow check on the\n@@ -255,10 +255,7 @@ def delayed_assattr(self, node: nodes.AssignAttr) -> None:\n # Const, Tuple or other containers that inherit from\n # `Instance`\n continue\n- elif (\n- isinstance(inferred, bases.Proxy)\n- or inferred is util.Uninferable\n- ):\n+ elif isinstance(inferred, (bases.Proxy, util.UninferableBase)):\n continue\n elif inferred.is_function:\n iattrs = inferred.instance_attrs\ndiff --git a/astroid/constraint.py b/astroid/constraint.py\n--- a/astroid/constraint.py\n+++ b/astroid/constraint.py\n@@ -74,7 +74,7 @@ def match(\n def satisfied_by(self, inferred: InferenceResult) -> bool:\n \"\"\"Return True if this constraint is satisfied by the given inferred value.\"\"\"\n # Assume true if uninferable\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n return True\n \n # Return the XOR of self.negate and matches(inferred, self.CONST_NONE)\ndiff --git a/astroid/helpers.py b/astroid/helpers.py\n--- a/astroid/helpers.py\n+++ b/astroid/helpers.py\n@@ -63,7 +63,7 @@ def _object_type(\n yield _build_proxy_class(\"module\", builtins)\n elif isinstance(inferred, nodes.Unknown):\n raise InferenceError\n- elif inferred is util.Uninferable:\n+ elif isinstance(inferred, util.UninferableBase):\n yield inferred\n elif isinstance(inferred, (bases.Proxy, nodes.Slice)):\n yield inferred._proxied\n@@ -100,7 +100,7 @@ def _object_type_is_subclass(\n else:\n class_seq = class_or_seq\n \n- if obj_type is util.Uninferable:\n+ if isinstance(obj_type, util.UninferableBase):\n return util.Uninferable\n \n # Instances are not types\n@@ -112,7 +112,7 @@ def _object_type_is_subclass(\n # issubclass(type, (object, 1)) evaluates to true\n # issubclass(object, (1, type)) raises TypeError\n for klass in class_seq:\n- if klass is util.Uninferable:\n+ if isinstance(klass, util.UninferableBase):\n raise AstroidTypeError(\"arg 2 must be a type or tuple of types\")\n \n for obj_subclass in obj_type.mro():\n@@ -131,7 +131,7 @@ def object_isinstance(node, class_or_seq, context: InferenceContext | None = Non\n :raises AstroidTypeError: if the given ``classes_or_seq`` are not types\n \"\"\"\n obj_type = object_type(node, context)\n- if obj_type is util.Uninferable:\n+ if isinstance(obj_type, util.UninferableBase):\n return util.Uninferable\n return _object_type_is_subclass(obj_type, class_or_seq, context=context)\n \n@@ -275,7 +275,7 @@ def object_len(node, context: InferenceContext | None = None):\n )\n raise InferenceError(message)\n \n- if inferred_node is None or inferred_node is util.Uninferable:\n+ if inferred_node is None or isinstance(inferred_node, util.UninferableBase):\n raise InferenceError(node=node)\n if isinstance(inferred_node, nodes.Const) and isinstance(\n inferred_node.value, (bytes, str)\n@@ -300,7 +300,7 @@ def object_len(node, context: InferenceContext | None = None):\n ) from e\n \n inferred = len_call.infer_call_result(node, context)\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n raise InferenceError(node=node, context=context)\n result_of_len = next(inferred, None)\n if (\ndiff --git a/astroid/inference.py b/astroid/inference.py\n--- a/astroid/inference.py\n+++ b/astroid/inference.py\n@@ -268,7 +268,7 @@ def infer_call(\n callcontext.extra_context = _populate_context_lookup(self, context.clone())\n \n for callee in self.func.infer(context):\n- if callee is util.Uninferable:\n+ if isinstance(callee, util.UninferableBase):\n yield callee\n continue\n try:\n@@ -356,7 +356,7 @@ def infer_attribute(\n ) -> Generator[InferenceResult, None, InferenceErrorInfo]:\n \"\"\"Infer an Attribute node by using getattr on the associated object.\"\"\"\n for owner in self.expr.infer(context):\n- if owner is util.Uninferable:\n+ if isinstance(owner, util.UninferableBase):\n yield owner\n continue\n \n@@ -424,11 +424,11 @@ def infer_subscript(\n \n found_one = False\n for value in self.value.infer(context):\n- if value is util.Uninferable:\n+ if isinstance(value, util.UninferableBase):\n yield util.Uninferable\n return None\n for index in self.slice.infer(context):\n- if index is util.Uninferable:\n+ if isinstance(index, util.UninferableBase):\n yield util.Uninferable\n return None\n \n@@ -459,7 +459,7 @@ def infer_subscript(\n \n # Prevent inferring if the inferred subscript\n # is the same as the original subscripted object.\n- if self is assigned or assigned is util.Uninferable:\n+ if self is assigned or isinstance(assigned, util.UninferableBase):\n yield util.Uninferable\n return None\n yield from assigned.infer(context)\n@@ -502,13 +502,13 @@ def _infer_boolop(\n return None\n \n for pair in itertools.product(*inferred_values):\n- if any(item is util.Uninferable for item in pair):\n+ if any(isinstance(item, util.UninferableBase) for item in pair):\n # Can't infer the final result, just yield Uninferable.\n yield util.Uninferable\n continue\n \n bool_values = [item.bool_value() for item in pair]\n- if any(item is util.Uninferable for item in bool_values):\n+ if any(isinstance(item, util.UninferableBase) for item in bool_values):\n # Can't infer the final result, just yield Uninferable.\n yield util.Uninferable\n continue\n@@ -575,7 +575,7 @@ def _infer_unaryop(\n # value and negate its result, unless it is\n # Uninferable, which will be returned as is.\n bool_value = operand.bool_value()\n- if bool_value is not util.Uninferable:\n+ if not isinstance(bool_value, util.UninferableBase):\n yield nodes.const_factory(not bool_value)\n else:\n yield util.Uninferable\n@@ -595,7 +595,10 @@ def _infer_unaryop(\n \n meth = methods[0]\n inferred = next(meth.infer(context=context), None)\n- if inferred is util.Uninferable or not inferred.callable():\n+ if (\n+ isinstance(inferred, util.UninferableBase)\n+ or not inferred.callable()\n+ ):\n continue\n \n context = copy_context(context)\n@@ -639,7 +642,7 @@ def _is_not_implemented(const) -> bool:\n \n def _infer_old_style_string_formatting(\n instance: nodes.Const, other: nodes.NodeNG, context: InferenceContext\n-) -> tuple[type[util.Uninferable] | nodes.Const]:\n+) -> tuple[util.UninferableBase | nodes.Const]:\n \"\"\"Infer the result of '\"string\" % ...'.\n \n TODO: Instead of returning Uninferable we should rely\n@@ -699,7 +702,7 @@ def _invoke_binop_inference(\n inferred = next(method.infer(context=context))\n except StopIteration as e:\n raise InferenceError(node=method, context=context) from e\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n raise InferenceError\n if not isinstance(\n instance, (nodes.Const, nodes.Tuple, nodes.List, nodes.ClassDef, bases.Instance)\n@@ -923,7 +926,7 @@ def _infer_binary_operation(\n yield util.Uninferable\n return\n else:\n- if any(result is util.Uninferable for result in results):\n+ if any(isinstance(result, util.UninferableBase) for result in results):\n yield util.Uninferable\n return\n \n@@ -959,7 +962,7 @@ def _infer_binop(\n lhs_iter = left.infer(context=lhs_context)\n rhs_iter = right.infer(context=rhs_context)\n for lhs, rhs in itertools.product(lhs_iter, rhs_iter):\n- if any(value is util.Uninferable for value in (rhs, lhs)):\n+ if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):\n # Don't know how to process this.\n yield util.Uninferable\n return\n@@ -1008,7 +1011,7 @@ def _to_literal(node: nodes.NodeNG) -> Any:\n \n def _do_compare(\n left_iter: Iterable[nodes.NodeNG], op: str, right_iter: Iterable[nodes.NodeNG]\n-) -> bool | type[util.Uninferable]:\n+) -> bool | util.UninferableBase:\n \"\"\"\n If all possible combinations are either True or False, return that:\n >>> _do_compare([1, 2], '<=', [3, 4])\n@@ -1027,7 +1030,9 @@ def _do_compare(\n op_func = COMPARE_OPS[op]\n \n for left, right in itertools.product(left_iter, right_iter):\n- if left is util.Uninferable or right is util.Uninferable:\n+ if isinstance(left, util.UninferableBase) or isinstance(\n+ right, util.UninferableBase\n+ ):\n return util.Uninferable\n \n try:\n@@ -1052,9 +1057,9 @@ def _do_compare(\n \n def _infer_compare(\n self: nodes.Compare, context: InferenceContext | None = None, **kwargs: Any\n-) -> Generator[nodes.Const | type[util.Uninferable], None, None]:\n+) -> Generator[nodes.Const | util.UninferableBase, None, None]:\n \"\"\"Chained comparison inference logic.\"\"\"\n- retval: bool | type[util.Uninferable] = True\n+ retval: bool | util.UninferableBase = True\n \n ops = self.ops\n left_node = self.left\n@@ -1091,7 +1096,7 @@ def _infer_augassign(\n lhs_iter = self.target.infer_lhs(context=context)\n rhs_iter = self.value.infer(context=rhs_context)\n for lhs, rhs in itertools.product(lhs_iter, rhs_iter):\n- if any(value is util.Uninferable for value in (rhs, lhs)):\n+ if any(isinstance(value, util.UninferableBase) for value in (rhs, lhs)):\n # Don't know how to process this.\n yield util.Uninferable\n return\n@@ -1216,7 +1221,7 @@ def infer_ifexp(\n except (InferenceError, StopIteration):\n both_branches = True\n else:\n- if test is not util.Uninferable:\n+ if not isinstance(test, util.UninferableBase):\n if test.bool_value():\n yield from self.body.infer(context=lhs_context)\n else:\ndiff --git a/astroid/inference_tip.py b/astroid/inference_tip.py\n--- a/astroid/inference_tip.py\n+++ b/astroid/inference_tip.py\n@@ -11,16 +11,11 @@\n \n import wrapt\n \n-from astroid import bases, util\n from astroid.exceptions import InferenceOverwriteError, UseInferenceDefault\n from astroid.nodes import NodeNG\n-from astroid.typing import InferFn\n+from astroid.typing import InferenceResult, InferFn\n \n-InferOptions = typing.Union[\n- NodeNG, bases.Instance, bases.UnboundMethod, typing.Type[util.Uninferable]\n-]\n-\n-_cache: dict[tuple[InferFn, NodeNG], list[InferOptions] | None] = {}\n+_cache: dict[tuple[InferFn, NodeNG], list[InferenceResult] | None] = {}\n \n \n def clear_inference_tip_cache() -> None:\n@@ -31,7 +26,7 @@ def clear_inference_tip_cache() -> None:\n @wrapt.decorator\n def _inference_tip_cached(\n func: InferFn, instance: None, args: typing.Any, kwargs: typing.Any\n-) -> Iterator[InferOptions]:\n+) -> Iterator[InferenceResult]:\n \"\"\"Cache decorator used for inference tips.\"\"\"\n node = args[0]\n try:\ndiff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py\n--- a/astroid/interpreter/objectmodel.py\n+++ b/astroid/interpreter/objectmodel.py\n@@ -358,7 +358,7 @@ def infer_call_result(\n except StopIteration as e:\n raise InferenceError(context=context, node=caller.args[0]) from e\n \n- if cls is astroid.Uninferable:\n+ if isinstance(cls, util.UninferableBase):\n raise InferenceError(\n \"Invalid class inferred\", target=self, context=context\n )\ndiff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py\n--- a/astroid/nodes/node_classes.py\n+++ b/astroid/nodes/node_classes.py\n@@ -101,7 +101,7 @@ def unpack_infer(stmt, context: InferenceContext | None = None):\n return {\"node\": stmt, \"context\": context}\n # else, infer recursively, except Uninferable object that should be returned as is\n for inferred in stmt.infer(context):\n- if inferred is util.Uninferable:\n+ if isinstance(inferred, util.UninferableBase):\n yield inferred\n else:\n yield from unpack_infer(inferred, context)\n@@ -2457,7 +2457,7 @@ def getitem(\n continue\n \n for inferredkey in key.infer(context):\n- if inferredkey is util.Uninferable:\n+ if isinstance(inferredkey, util.UninferableBase):\n continue\n if isinstance(inferredkey, Const) and isinstance(index, Const):\n if inferredkey.value == index.value:\n@@ -4951,13 +4951,11 @@ class EvaluatedObject(NodeNG):\n _astroid_fields = (\"original\",)\n _other_fields = (\"value\",)\n \n- def __init__(\n- self, original: NodeNG, value: NodeNG | type[util.Uninferable]\n- ) -> None:\n+ def __init__(self, original: NodeNG, value: NodeNG | util.UninferableBase) -> None:\n self.original: NodeNG = original\n \"\"\"The original node that has already been evaluated\"\"\"\n \n- self.value: NodeNG | type[util.Uninferable] = value\n+ self.value: NodeNG | util.UninferableBase = value\n \"\"\"The inferred value\"\"\"\n \n super().__init__(\n@@ -4968,7 +4966,7 @@ def __init__(\n \n def _infer(\n self, context: InferenceContext | None = None, **kwargs: Any\n- ) -> Generator[NodeNG | type[util.Uninferable], None, None]:\n+ ) -> Generator[NodeNG | util.UninferableBase, None, None]:\n yield self.value\n \n \ndiff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py\n--- a/astroid/nodes/scoped_nodes/scoped_nodes.py\n+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py\n@@ -1705,7 +1705,11 @@ def infer_call_result(self, caller=None, context: InferenceContext | None = None\n new_class.hide = True\n new_class.parent = self\n new_class.postinit(\n- bases=[base for base in class_bases if base != util.Uninferable],\n+ bases=[\n+ base\n+ for base in class_bases\n+ if not isinstance(base, util.UninferableBase)\n+ ],\n body=[],\n decorators=[],\n metaclass=metaclass,\n@@ -1826,8 +1830,6 @@ def _is_metaclass(klass, seen=None) -> bool:\n if isinstance(baseobj, bases.Instance):\n # not abstract\n return False\n- if baseobj is util.Uninferable:\n- continue\n if baseobj is klass:\n continue\n if not isinstance(baseobj, ClassDef):\n@@ -2817,7 +2819,7 @@ def declared_metaclass(\n return next(\n node\n for node in self._metaclass.infer(context=context)\n- if node is not util.Uninferable\n+ if not isinstance(node, util.UninferableBase)\n )\n except (InferenceError, StopIteration):\n return None\n@@ -2883,7 +2885,7 @@ def _islots(self):\n values = [item[0] for item in slots.items]\n else:\n values = slots.itered()\n- if values is util.Uninferable:\n+ if isinstance(values, util.UninferableBase):\n continue\n if not values:\n # Stop the iteration, because the class\n@@ -2893,8 +2895,6 @@ def _islots(self):\n for elt in values:\n try:\n for inferred in elt.infer():\n- if inferred is util.Uninferable:\n- continue\n if not isinstance(\n inferred, node_classes.Const\n ) or not isinstance(inferred.value, str):\ndiff --git a/astroid/protocols.py b/astroid/protocols.py\n--- a/astroid/protocols.py\n+++ b/astroid/protocols.py\n@@ -132,7 +132,7 @@ def const_infer_binary_op(\n other: InferenceResult,\n context: InferenceContext,\n _: SuccessfulInferenceResult,\n-) -> Generator[ConstFactoryResult | type[util.Uninferable], None, None]:\n+) -> Generator[ConstFactoryResult | util.UninferableBase, None, None]:\n not_implemented = nodes.Const(NotImplemented)\n if isinstance(other, nodes.Const):\n if (\n@@ -174,7 +174,7 @@ def _multiply_seq_by_int(\n filtered_elts = (\n helpers.safe_infer(elt, context) or util.Uninferable\n for elt in self.elts\n- if elt is not util.Uninferable\n+ if not isinstance(elt, util.UninferableBase)\n )\n node.elts = list(filtered_elts) * other.value\n return node\n@@ -184,11 +184,11 @@ def _filter_uninferable_nodes(\n elts: Sequence[InferenceResult], context: InferenceContext\n ) -> Iterator[SuccessfulInferenceResult]:\n for elt in elts:\n- if elt is util.Uninferable:\n+ if isinstance(elt, util.UninferableBase):\n yield nodes.Unknown()\n else:\n for inferred in elt.infer(context):\n- if inferred is not util.Uninferable:\n+ if not isinstance(inferred, util.UninferableBase):\n yield inferred\n else:\n yield nodes.Unknown()\n@@ -202,7 +202,7 @@ def tl_infer_binary_op(\n other: InferenceResult,\n context: InferenceContext,\n method: SuccessfulInferenceResult,\n-) -> Generator[_TupleListNodeT | nodes.Const | type[util.Uninferable], None, None]:\n+) -> Generator[_TupleListNodeT | nodes.Const | util.UninferableBase, None, None]:\n \"\"\"Infer a binary operation on a tuple or list.\n \n The instance on which the binary operation is performed is a tuple\n@@ -276,7 +276,7 @@ def _resolve_looppart(parts, assign_path, context):\n assign_path = assign_path[:]\n index = assign_path.pop(0)\n for part in parts:\n- if part is util.Uninferable:\n+ if isinstance(part, util.UninferableBase):\n continue\n if not hasattr(part, \"itered\"):\n continue\n@@ -299,7 +299,7 @@ def _resolve_looppart(parts, assign_path, context):\n # we achieved to resolved the assignment path,\n # don't infer the last part\n yield assigned\n- elif assigned is util.Uninferable:\n+ elif isinstance(assigned, util.UninferableBase):\n break\n else:\n # we are not yet on the last part of the path\n@@ -546,7 +546,7 @@ def _resolve_assignment_parts(parts, assign_path, context):\n # we achieved to resolved the assignment path, don't infer the\n # last part\n yield assigned\n- elif assigned is util.Uninferable:\n+ elif isinstance(assigned, util.UninferableBase):\n return\n else:\n # we are not yet on the last part of the path search on each\n@@ -793,7 +793,7 @@ def _determine_starred_iteration_lookups(\n except (InferenceError, StopIteration):\n yield util.Uninferable\n return\n- if rhs is util.Uninferable or not hasattr(rhs, \"itered\"):\n+ if isinstance(rhs, util.UninferableBase) or not hasattr(rhs, \"itered\"):\n yield util.Uninferable\n return\n \n@@ -841,7 +841,7 @@ def _determine_starred_iteration_lookups(\n except (InferenceError, StopIteration):\n yield util.Uninferable\n return\n- if inferred_iterable is util.Uninferable or not hasattr(\n+ if isinstance(inferred_iterable, util.UninferableBase) or not hasattr(\n inferred_iterable, \"itered\"\n ):\n yield util.Uninferable\ndiff --git a/astroid/typing.py b/astroid/typing.py\n--- a/astroid/typing.py\n+++ b/astroid/typing.py\n@@ -46,7 +46,7 @@ class AstroidManagerBrain(TypedDict):\n _transform: transforms.TransformVisitor\n \n \n-InferenceResult = Union[\"nodes.NodeNG\", \"type[util.Uninferable]\", \"bases.Proxy\"]\n+InferenceResult = Union[\"nodes.NodeNG\", \"util.UninferableBase\", \"bases.Proxy\"]\n SuccessfulInferenceResult = Union[\"nodes.NodeNG\", \"bases.Proxy\"]\n \n ConstFactoryResult = Union[\ndiff --git a/astroid/util.py b/astroid/util.py\n--- a/astroid/util.py\n+++ b/astroid/util.py\n@@ -2,6 +2,9 @@\n # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE\n # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt\n \n+\n+from __future__ import annotations\n+\n import importlib\n import sys\n import warnings\n@@ -10,9 +13,9 @@\n import lazy_object_proxy\n \n if sys.version_info >= (3, 8):\n- from typing import Literal\n+ from typing import Final, Literal\n else:\n- from typing_extensions import Literal\n+ from typing_extensions import Final, Literal\n \n \n def lazy_descriptor(obj):\n@@ -29,11 +32,13 @@ def lazy_import(module_name: str) -> lazy_object_proxy.Proxy:\n )\n \n \n-@object.__new__\n-class Uninferable:\n- \"\"\"Special inference object, which is returned when inference fails.\"\"\"\n+class UninferableBase:\n+ \"\"\"Special inference object, which is returned when inference fails.\n+\n+ This is meant to be used as a singleton. Use astroid.util.Uninferable to access it.\n+ \"\"\"\n \n- def __repr__(self) -> str:\n+ def __repr__(self) -> Literal[\"Uninferable\"]:\n return \"Uninferable\"\n \n __str__ = __repr__\n@@ -47,7 +52,7 @@ def __getattribute__(self, name: str) -> Any:\n return object.__getattribute__(self, name)\n return self\n \n- def __call__(self, *args, **kwargs):\n+ def __call__(self, *args: Any, **kwargs: Any) -> UninferableBase:\n return self\n \n def __bool__(self) -> Literal[False]:\n@@ -59,6 +64,9 @@ def accept(self, visitor):\n return visitor.visit_uninferable(self)\n \n \n+Uninferable: Final = UninferableBase()\n+\n+\n class BadOperationMessage:\n \"\"\"Object which describes a TypeError occurred somewhere in the inference chain.\n \n@@ -82,7 +90,7 @@ def _object_type_helper(self):\n \n def _object_type(self, obj):\n objtype = self._object_type_helper(obj)\n- if objtype is Uninferable:\n+ if isinstance(objtype, UninferableBase):\n return None\n \n return objtype\n", "test_patch": "diff --git a/tests/unittest_protocols.py b/tests/unittest_protocols.py\n--- a/tests/unittest_protocols.py\n+++ b/tests/unittest_protocols.py\n@@ -16,7 +16,7 @@\n from astroid.const import PY38_PLUS, PY310_PLUS\n from astroid.exceptions import InferenceError\n from astroid.manager import AstroidManager\n-from astroid.util import Uninferable\n+from astroid.util import Uninferable, UninferableBase\n \n \n @contextlib.contextmanager\n@@ -125,7 +125,7 @@ def test_assigned_stmts_starred_for(self) -> None:\n assert isinstance(assigned, astroid.List)\n assert assigned.as_string() == \"[1, 2]\"\n \n- def _get_starred_stmts(self, code: str) -> list | Uninferable:\n+ def _get_starred_stmts(self, code: str) -> list | UninferableBase:\n assign_stmt = extract_node(f\"{code} #@\")\n starred = next(assign_stmt.nodes_of_class(nodes.Starred))\n return next(starred.assigned_stmts())\n@@ -136,7 +136,7 @@ def _helper_starred_expected_const(self, code: str, expected: list[int]) -> None\n stmts = stmts.elts\n self.assertConstNodesEqual(expected, stmts)\n \n- def _helper_starred_expected(self, code: str, expected: Uninferable) -> None:\n+ def _helper_starred_expected(self, code: str, expected: UninferableBase) -> None:\n stmts = self._get_starred_stmts(code)\n self.assertEqual(expected, stmts)\n \n", "problem_statement": "Consider creating a ``UninferableType`` or ``_Uninferable`` class\nI opened https://github.com/microsoft/pyright/issues/3641 as I wondered why `pyright` didn't recognise how we type `Uninferable`. Normally they are a little bit more up to date than `mypy` so I wondered if this was intentional.\r\n\r\nTurns out it is. According to them, the way we currently handle the typing of `Uninferable` is incorrect and should ideally be refactored.\r\nAs we're stille early days into the typing of `astroid` I think there is still chance to do this.\r\n\r\nTheir suggestion is to create a private class (`_Uninferable`) which `Uninferable` can then instantiate. One of the issues with this is that we tend to require `Uninferable` as a type in `pylint` as well and so we would need to import that private class as well.\r\nWe could also create a public class, perhaps suffixed with `Type`, which we document as only being useful for typing.\r\n\r\nLet me know if you guys thinks this is something we should do and what approach is best.\r\n\r\n/CC @cdce8p As you're likely interested in this.\n", "hints_text": "@jacobtylerwalls Do you have a preference for either of the two solutions?\nI think `UninferableType` is more clear. I wish [PEP 661](https://peps.python.org/pep-0661/) had an implementation.", "created_at": "2022-08-15T18:02:09Z", "version": "2.15", "FAIL_TO_PASS": ["tests/unittest_protocols.py::ProtocolTests::test_assign_stmts_starred_fails", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_annassignments", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_assignments", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_nested_for_dict", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_nested_for_tuple", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_simple_for", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_assnames", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_for", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_inside_call", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_yes", "tests/unittest_protocols.py::ProtocolTests::test_not_passing_uninferable_in_seq_inference", "tests/unittest_protocols.py::ProtocolTests::test_sequence_assigned_stmts_not_accepting_empty_node", "tests/unittest_protocols.py::ProtocolTests::test_uninferable_exponents", "tests/unittest_protocols.py::test_named_expr_inference"], "PASS_TO_PASS": [], "environment_setup_commit": "29b42e5e9745b172d5980511d14efeac745a5a82"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1616", "base_commit": "6280a758733434cba32b719519908314a5c2955b", "patch": "diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py\n--- a/astroid/brain/brain_builtin_inference.py\n+++ b/astroid/brain/brain_builtin_inference.py\n@@ -913,12 +913,15 @@ def _infer_copy_method(\n \n def _is_str_format_call(node: nodes.Call) -> bool:\n \"\"\"Catch calls to str.format().\"\"\"\n- return (\n- isinstance(node.func, nodes.Attribute)\n- and node.func.attrname == \"format\"\n- and isinstance(node.func.expr, nodes.Const)\n- and isinstance(node.func.expr.value, str)\n- )\n+ if not isinstance(node.func, nodes.Attribute) or not node.func.attrname == \"format\":\n+ return False\n+\n+ if isinstance(node.func.expr, nodes.Name):\n+ value = helpers.safe_infer(node.func.expr)\n+ else:\n+ value = node.func.expr\n+\n+ return isinstance(value, nodes.Const) and isinstance(value.value, str)\n \n \n def _infer_str_format_call(\n@@ -926,7 +929,12 @@ def _infer_str_format_call(\n ) -> Iterator[nodes.Const | type[util.Uninferable]]:\n \"\"\"Return a Const node based on the template and passed arguments.\"\"\"\n call = arguments.CallSite.from_call(node, context=context)\n- format_template: str = node.func.expr.value\n+ if isinstance(node.func.expr, nodes.Name):\n+ value: nodes.Const = helpers.safe_infer(node.func.expr)\n+ else:\n+ value = node.func.expr\n+\n+ format_template = value.value\n \n # Get the positional arguments passed\n inferred_positional = [\n", "test_patch": "diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py\n--- a/tests/unittest_brain_builtin.py\n+++ b/tests/unittest_brain_builtin.py\n@@ -66,6 +66,13 @@ class TestStringNodes:\n \"\"\",\n id=\"mixed-indexes-from-mixed\",\n ),\n+ pytest.param(\n+ \"\"\"\n+ string = \"My name is {}, I'm {}\"\n+ string.format(\"Daniel\", 12)\n+ \"\"\",\n+ id=\"empty-indexes-on-variable\",\n+ ),\n ],\n )\n def test_string_format(self, format_string: str) -> None:\n", "problem_statement": "Infer calls to str.format() on names\nFuture enhancement could infer this value instead of giving an empty string:\r\n\r\n```python\r\nfrom astroid import extract_node\r\ncall = extract_node(\"\"\"\r\nx = 'python is {}'\r\nx.format('helpful sometimes')\r\n\"\"\")\r\ncall.inferred()[0].value # gives \"\"\r\n```\r\n\r\n_Originally posted by @jacobtylerwalls in https://github.com/PyCQA/astroid/pull/1602#discussion_r893423433_\n", "hints_text": "", "created_at": "2022-06-12T11:50:45Z", "version": "2.12", "FAIL_TO_PASS": ["tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes-on-variable]"], "PASS_TO_PASS": ["tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs"], "environment_setup_commit": "52f6d2d7722db383af035be929f18af5e9fe8cd5"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1978", "base_commit": "0c9ab0fe56703fa83c73e514a1020d398d23fa7f", "patch": "diff --git a/astroid/raw_building.py b/astroid/raw_building.py\n--- a/astroid/raw_building.py\n+++ b/astroid/raw_building.py\n@@ -10,11 +10,14 @@\n \n import builtins\n import inspect\n+import io\n+import logging\n import os\n import sys\n import types\n import warnings\n from collections.abc import Iterable\n+from contextlib import redirect_stderr, redirect_stdout\n from typing import Any, Union\n \n from astroid import bases, nodes\n@@ -22,6 +25,9 @@\n from astroid.manager import AstroidManager\n from astroid.nodes import node_classes\n \n+logger = logging.getLogger(__name__)\n+\n+\n _FunctionTypes = Union[\n types.FunctionType,\n types.MethodType,\n@@ -471,7 +477,26 @@ def imported_member(self, node, member, name: str) -> bool:\n # check if it sounds valid and then add an import node, else use a\n # dummy node\n try:\n- getattr(sys.modules[modname], name)\n+ with redirect_stderr(io.StringIO()) as stderr, redirect_stdout(\n+ io.StringIO()\n+ ) as stdout:\n+ getattr(sys.modules[modname], name)\n+ stderr_value = stderr.getvalue()\n+ if stderr_value:\n+ logger.error(\n+ \"Captured stderr while getting %s from %s:\\n%s\",\n+ name,\n+ sys.modules[modname],\n+ stderr_value,\n+ )\n+ stdout_value = stdout.getvalue()\n+ if stdout_value:\n+ logger.info(\n+ \"Captured stdout while getting %s from %s:\\n%s\",\n+ name,\n+ sys.modules[modname],\n+ stdout_value,\n+ )\n except (KeyError, AttributeError):\n attach_dummy_node(node, name, member)\n else:\n", "test_patch": "diff --git a/tests/unittest_raw_building.py b/tests/unittest_raw_building.py\n--- a/tests/unittest_raw_building.py\n+++ b/tests/unittest_raw_building.py\n@@ -8,8 +8,15 @@\n # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE\n # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt\n \n+from __future__ import annotations\n+\n+import logging\n+import os\n+import sys\n import types\n import unittest\n+from typing import Any\n+from unittest import mock\n \n import _io\n import pytest\n@@ -117,5 +124,45 @@ def test_module_object_with_broken_getattr(self) -> None:\n AstroidBuilder().inspect_build(fm_getattr, \"test\")\n \n \[email protected](\n+ \"posix\" not in sys.builtin_module_names, reason=\"Platform doesn't support posix\"\n+)\n+def test_build_module_getattr_catch_output(\n+ capsys: pytest.CaptureFixture[str],\n+ caplog: pytest.LogCaptureFixture,\n+) -> None:\n+ \"\"\"Catch stdout and stderr in module __getattr__ calls when building a module.\n+\n+ Usually raised by DeprecationWarning or FutureWarning.\n+ \"\"\"\n+ caplog.set_level(logging.INFO)\n+ original_sys = sys.modules\n+ original_module = sys.modules[\"posix\"]\n+ expected_out = \"INFO (TEST): Welcome to posix!\"\n+ expected_err = \"WARNING (TEST): Monkey-patched version of posix - module getattr\"\n+\n+ class CustomGetattr:\n+ def __getattr__(self, name: str) -> Any:\n+ print(f\"{expected_out}\")\n+ print(expected_err, file=sys.stderr)\n+ return getattr(original_module, name)\n+\n+ def mocked_sys_modules_getitem(name: str) -> types.ModuleType | CustomGetattr:\n+ if name != \"posix\":\n+ return original_sys[name]\n+ return CustomGetattr()\n+\n+ with mock.patch(\"astroid.raw_building.sys.modules\") as sys_mock:\n+ sys_mock.__getitem__.side_effect = mocked_sys_modules_getitem\n+ builder = AstroidBuilder()\n+ builder.inspect_build(os)\n+\n+ out, err = capsys.readouterr()\n+ assert expected_out in caplog.text\n+ assert expected_err in caplog.text\n+ assert not out\n+ assert not err\n+\n+\n if __name__ == \"__main__\":\n unittest.main()\n", "problem_statement": "Deprecation warnings from numpy\n### Steps to reproduce\r\n\r\n1. Run pylint over the following test case:\r\n\r\n```\r\n\"\"\"Test case\"\"\"\r\n\r\nimport numpy as np\r\nvalue = np.random.seed(1234)\r\n```\r\n\r\n### Current behavior\r\n```\r\n/home/bje/source/nemo/myenv/lib/python3.10/site-packages/astroid/raw_building.py:470: FutureWarning: In the future `np.long` will be defined as the corresponding NumPy scalar. (This may have returned Python scalars in past versions.\r\n getattr(sys.modules[modname], name)\r\n/home/bje/source/nemo/myenv/lib/python3.10/site-packages/astroid/raw_building.py:470: FutureWarning: In the future `np.long` will be defined as the corresponding NumPy scalar. (This may have returned Python scalars in past versions.\r\n getattr(sys.modules[modname], name)\r\n```\r\n\r\n### Expected behavior\r\nThere should be no future warnings.\r\n\r\n### python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\" output\r\n2.12.13\n", "hints_text": "This seems very similar to https://github.com/PyCQA/astroid/pull/1514 that was fixed in 2.12.0.\nI'm running 2.12.13 (> 2.12.0), so the fix isn't working in this case?\nI don't know why #1514 did not fix this, I think we were capturing both stdout and stderr, so this will need some investigation. My guess would be that there's somewhere else to apply the same method to.\nHello, \r\nI see the same error with pylint on our tool [demcompare](https://github.com/CNES/demcompare). Pylint version:\r\n```\r\npylint --version\r\npylint 2.15.9\r\nastroid 2.12.13\r\nPython 3.8.10 (default, Nov 14 2022, 12:59:47) \r\n[GCC 9.4.0]\r\n```\r\nI confirm the weird astroid lower warning and I don't know how to bypass it with pylint checking. \r\n\r\n```\r\npylint demcompare \r\n/home/duboise/work/src/demcompare/venv/lib/python3.8/site-packages/astroid/raw_building.py:470: FutureWarning: In the future `np.long` will be defined as the corresponding NumPy scalar. (This may have returned Python scalars in past versions.\r\n getattr(sys.modules[modname], name)\r\n... (four times)\r\n```\r\n\r\nThanks in advance if there is a solution\r\nCordially\r\n\n> Thanks in advance if there is a solution\r\n\r\nwhile annoying the warning does not make pylint fail. Just ignore it. In a CI you can just check pylint return code. It will return 0 as expected\nI agree, even if annoying because it feels our code as a problem somewhere, the CI with pylint doesn't fail indeed. Thanks for the answer that confirm to not bother for now. \nThat might be fine in a CI environment, but for users, ultimately, ignoring warnings becomes difficult when there are too many such warnings. I would like to see this fixed.\nOh, it was not an argument in favour of not fixing it. It was just to point out that it is not a breaking problem. It is \"just\" a lot of quite annoying warnings. I am following the issue because it annoys me too. So I am in the same \"I hope they will fix it\" boat\n> I don't know why https://github.com/PyCQA/astroid/pull/1514 did not fix this, I think we were capturing both stdout and stderr, so this will need some investigation. My guess would be that there's somewhere else to apply the same method to.\r\n\r\nThat PR only addressed import-time. This `FutureWarning` is emitted by numpy's package-level `__getattr__` method, not during import.", "created_at": "2023-01-28T06:14:39Z", "version": "2.14", "FAIL_TO_PASS": ["tests/unittest_raw_building.py::test_build_module_getattr_catch_output"], "PASS_TO_PASS": ["tests/unittest_raw_building.py::RawBuildingTC::test_attach_dummy_node", "tests/unittest_raw_building.py::RawBuildingTC::test_build_class", "tests/unittest_raw_building.py::RawBuildingTC::test_build_from_import", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_args", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_deepinspect_deprecation", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_defaults", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_kwonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_posonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_module", "tests/unittest_raw_building.py::RawBuildingTC::test_io_is__io", "tests/unittest_raw_building.py::RawBuildingTC::test_module_object_with_broken_getattr"], "environment_setup_commit": "0c9ab0fe56703fa83c73e514a1020d398d23fa7f"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-934", "base_commit": "4cfd9b6d1003b9912ab94538e1dfa5d734f55251", "patch": "diff --git a/astroid/inference.py b/astroid/inference.py\n--- a/astroid/inference.py\n+++ b/astroid/inference.py\n@@ -309,6 +309,7 @@ def infer_attribute(self, context=None):\n elif not context:\n context = contextmod.InferenceContext()\n \n+ old_boundnode = context.boundnode\n try:\n context.boundnode = owner\n yield from owner.igetattr(self.attrname, context)\n@@ -319,7 +320,7 @@ def infer_attribute(self, context=None):\n ):\n pass\n finally:\n- context.boundnode = None\n+ context.boundnode = old_boundnode\n return dict(node=self, context=context)\n \n \n", "test_patch": "diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py\n--- a/tests/unittest_inference.py\n+++ b/tests/unittest_inference.py\n@@ -3894,6 +3894,65 @@ class Clazz(metaclass=_Meta):\n ).inferred()[0]\n assert isinstance(cls, nodes.ClassDef) and cls.name == \"Clazz\"\n \n+ def test_infer_subclass_attr_outer_class(self):\n+ node = extract_node(\n+ \"\"\"\n+ class Outer:\n+ data = 123\n+\n+ class Test(Outer):\n+ pass\n+ Test.data\n+ \"\"\"\n+ )\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.Const)\n+ assert inferred.value == 123\n+\n+ def test_infer_subclass_attr_inner_class_works_indirectly(self):\n+ node = extract_node(\n+ \"\"\"\n+ class Outer:\n+ class Inner:\n+ data = 123\n+ Inner = Outer.Inner\n+\n+ class Test(Inner):\n+ pass\n+ Test.data\n+ \"\"\"\n+ )\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.Const)\n+ assert inferred.value == 123\n+\n+ def test_infer_subclass_attr_inner_class(self):\n+ clsdef_node, attr_node = extract_node(\n+ \"\"\"\n+ class Outer:\n+ class Inner:\n+ data = 123\n+\n+ class Test(Outer.Inner):\n+ pass\n+ Test #@\n+ Test.data #@\n+ \"\"\"\n+ )\n+ clsdef = next(clsdef_node.infer())\n+ assert isinstance(clsdef, nodes.ClassDef)\n+ inferred = next(clsdef.igetattr(\"data\"))\n+ assert isinstance(inferred, nodes.Const)\n+ assert inferred.value == 123\n+ # Inferring the value of .data via igetattr() worked before the\n+ # old_boundnode fixes in infer_subscript, so it should have been\n+ # possible to infer the subscript directly. It is the difference\n+ # between these two cases that led to the discovery of the cause of the\n+ # bug in https://github.com/PyCQA/astroid/issues/904\n+ inferred = next(attr_node.infer())\n+ assert isinstance(inferred, nodes.Const)\n+ assert inferred.value == 123\n+\n def test_delayed_attributes_without_slots(self):\n ast_node = extract_node(\n \"\"\"\n", "problem_statement": "error during inference of class inheriting from another with `mod.Type` format\nConsider package a `level` with a class `Model` defined in `level`'s `__init__.py` file.\r\n\r\n```\r\nclass Model:\r\n data: int = 1\r\n```\r\n\r\nIf a class `Test` inherits from `Model` as `class Test(Model)`, and `Model` comes from `from level import Model`, then inferring `Test.data` works fine (below, A is an alias for astroid).\r\n\r\n<img width=\"248\" alt=\"Screen Shot 2021-02-19 at 09 41 09\" src=\"https://user-images.githubusercontent.com/2905588/108505730-9b3c1900-7296-11eb-8bb8-5b66b7253cf4.png\">\r\n\r\nHowever, if a `Test` inherits from `Model` as `class Test(level.Model)` and `level` comes from `import level`, then inference triggers an exception.\r\n\r\n<img width=\"784\" alt=\"Screen Shot 2021-02-19 at 09 42 09\" src=\"https://user-images.githubusercontent.com/2905588/108505815-beff5f00-7296-11eb-92a2-641be827e1f0.png\">\r\n\r\n\r\n\r\n\r\n\n", "hints_text": "", "created_at": "2021-04-07T23:44:25Z", "version": "2.5", "FAIL_TO_PASS": ["tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class"], "PASS_TO_PASS": ["tests/unittest_inference.py::InferenceUtilsTest::test_path_wrapper", "tests/unittest_inference.py::InferenceTest::test__new__", "tests/unittest_inference.py::InferenceTest::test__new__bound_methods", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference1", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference2", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference2", "tests/unittest_inference.py::InferenceTest::test_args_default_inference1", "tests/unittest_inference.py::InferenceTest::test_args_default_inference2", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented_rop_fallback", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_not_implemented_normal_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_aug_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_normal_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_augassign", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_none_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_normal_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_not_implemented_returned_for_all", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_reflected_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_bin_op_classes", "tests/unittest_inference.py::InferenceTest::test_bin_op_supertype_more_complicated_example", "tests/unittest_inference.py::InferenceTest::test_binary_op_custom_class", "tests/unittest_inference.py::InferenceTest::test_binary_op_float_div", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitand", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitxor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftleft", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftright", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_sub", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_int", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_none", "tests/unittest_inference.py::InferenceTest::test_binary_op_on_self", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type_using_reflected_operands", "tests/unittest_inference.py::InferenceTest::test_binary_op_reflected_and_not_implemented_is_type_error", "tests/unittest_inference.py::InferenceTest::test_binary_op_str_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_tuple_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_type_errors", "tests/unittest_inference.py::InferenceTest::test_binop_ambiguity", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_normal_not_implemented_and_reflected", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_and_normal_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_only", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_unknown_bases", "tests/unittest_inference.py::InferenceTest::test_binop_inference_errors", "tests/unittest_inference.py::InferenceTest::test_binop_list_with_elts", "tests/unittest_inference.py::InferenceTest::test_binop_same_types", "tests/unittest_inference.py::InferenceTest::test_binop_subtype", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_implemented_in_parent", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_rop_not_implemented", "tests/unittest_inference.py::InferenceTest::test_bool_value", "tests/unittest_inference.py::InferenceTest::test_bool_value_instances", "tests/unittest_inference.py::InferenceTest::test_bool_value_recursive", "tests/unittest_inference.py::InferenceTest::test_bool_value_variable", "tests/unittest_inference.py::InferenceTest::test_bound_method_inference", "tests/unittest_inference.py::InferenceTest::test_bt_ancestor_crash", "tests/unittest_inference.py::InferenceTest::test_builtin_help", "tests/unittest_inference.py::InferenceTest::test_builtin_inference_py3k", "tests/unittest_inference.py::InferenceTest::test_builtin_name_inference", "tests/unittest_inference.py::InferenceTest::test_builtin_open", "tests/unittest_inference.py::InferenceTest::test_builtin_types", "tests/unittest_inference.py::InferenceTest::test_bytes_subscript", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_func", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_lambda", "tests/unittest_inference.py::InferenceTest::test_callfunc_inference", "tests/unittest_inference.py::InferenceTest::test_class_inference", "tests/unittest_inference.py::InferenceTest::test_classmethod_inferred_by_context", "tests/unittest_inference.py::InferenceTest::test_context_call_for_context_managers", "tests/unittest_inference.py::InferenceTest::test_conversion_of_dict_methods", "tests/unittest_inference.py::InferenceTest::test_del1", "tests/unittest_inference.py::InferenceTest::test_del2", "tests/unittest_inference.py::InferenceTest::test_delayed_attributes_without_slots", "tests/unittest_inference.py::InferenceTest::test_dict_inference", "tests/unittest_inference.py::InferenceTest::test_dict_inference_for_multiple_starred", "tests/unittest_inference.py::InferenceTest::test_dict_inference_kwargs", "tests/unittest_inference.py::InferenceTest::test_dict_inference_unpack_repeated_key", "tests/unittest_inference.py::InferenceTest::test_dict_invalid_args", "tests/unittest_inference.py::InferenceTest::test_exc_ancestors", "tests/unittest_inference.py::InferenceTest::test_except_inference", "tests/unittest_inference.py::InferenceTest::test_f_arg_f", "tests/unittest_inference.py::InferenceTest::test_factory_method", "tests/unittest_inference.py::InferenceTest::test_factory_methods_cls_call", "tests/unittest_inference.py::InferenceTest::test_factory_methods_object_new_call", "tests/unittest_inference.py::InferenceTest::test_float_complex_ambiguity", "tests/unittest_inference.py::InferenceTest::test_frozenset_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_function_inference", "tests/unittest_inference.py::InferenceTest::test_genexpr_bool_value", "tests/unittest_inference.py::InferenceTest::test_getattr_inference1", "tests/unittest_inference.py::InferenceTest::test_getattr_inference2", "tests/unittest_inference.py::InferenceTest::test_getattr_inference3", "tests/unittest_inference.py::InferenceTest::test_getattr_inference4", "tests/unittest_inference.py::InferenceTest::test_getitem_of_class_raised_type_error", "tests/unittest_inference.py::InferenceTest::test_im_func_unwrap", "tests/unittest_inference.py::InferenceTest::test_import_as", "tests/unittest_inference.py::InferenceTest::test_infer_abstract_property_return_values", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_object_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_defined_in_outer_scope_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_subscript_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arguments", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_crash", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_invalid_dunder_call_on_instance", "tests/unittest_inference.py::InferenceTest::test_infer_cls_in_class_methods", "tests/unittest_inference.py::InferenceTest::test_infer_coercion_rules_for_floats_complex", "tests/unittest_inference.py::InferenceTest::test_infer_empty_nodes", "tests/unittest_inference.py::InferenceTest::test_infer_nested", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class_works_indirectly", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr_indirect", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_outer_class", "tests/unittest_inference.py::InferenceTest::test_infer_variable_arguments", "tests/unittest_inference.py::InferenceTest::test_inference_restrictions", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_skip_index_error", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_unpacking_inference_error", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager_failures", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement_failures", "tests/unittest_inference.py::InferenceTest::test_infinite_loop_for_decorators", "tests/unittest_inference.py::InferenceTest::test_inner_value_redefined_by_subclass", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_multiple_methods", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_parent", "tests/unittest_inference.py::InferenceTest::test_instance_slicing", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_fails", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_slices", "tests/unittest_inference.py::InferenceTest::test_invalid_slicing_primaries", "tests/unittest_inference.py::InferenceTest::test_invalid_subscripts", "tests/unittest_inference.py::InferenceTest::test_lambda_as_methods", "tests/unittest_inference.py::InferenceTest::test_list_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_list_inference", "tests/unittest_inference.py::InferenceTest::test_listassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_lookup_cond_branches", "tests/unittest_inference.py::InferenceTest::test_matmul", "tests/unittest_inference.py::InferenceTest::test_metaclass__getitem__", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call_boundnode", "tests/unittest_inference.py::InferenceTest::test_metaclass_subclasses_arguments_are_classes_not_instances", "tests/unittest_inference.py::InferenceTest::test_metaclass_with_keyword_args", "tests/unittest_inference.py::InferenceTest::test_method_argument", "tests/unittest_inference.py::InferenceTest::test_module_inference", "tests/unittest_inference.py::InferenceTest::test_mul_list_supports__index__", "tests/unittest_inference.py::InferenceTest::test_mulassign_inference", "tests/unittest_inference.py::InferenceTest::test_name_bool_value", "tests/unittest_inference.py::InferenceTest::test_nested_contextmanager", "tests/unittest_inference.py::InferenceTest::test_no_infinite_ancestor_loop", "tests/unittest_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference", "tests/unittest_inference.py::InferenceTest::test_nonregr_absolute_import", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_arg", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_global", "tests/unittest_inference.py::InferenceTest::test_nonregr_getitem_empty_tuple", "tests/unittest_inference.py::InferenceTest::test_nonregr_inference_modifying_col_offset", "tests/unittest_inference.py::InferenceTest::test_nonregr_instance_attrs", "tests/unittest_inference.py::InferenceTest::test_nonregr_lambda_arg", "tests/unittest_inference.py::InferenceTest::test_nonregr_layed_dictunpack", "tests/unittest_inference.py::InferenceTest::test_nonregr_multi_referential_addition", "tests/unittest_inference.py::InferenceTest::test_pluggable_inference", "tests/unittest_inference.py::InferenceTest::test_property", "tests/unittest_inference.py::InferenceTest::test_python25_no_relative_import", "tests/unittest_inference.py::InferenceTest::test_scope_lookup_same_attributes", "tests/unittest_inference.py::InferenceTest::test_set_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_simple_for", "tests/unittest_inference.py::InferenceTest::test_simple_for_genexpr", "tests/unittest_inference.py::InferenceTest::test_simple_subscript", "tests/unittest_inference.py::InferenceTest::test_simple_tuple", "tests/unittest_inference.py::InferenceTest::test_slicing_list", "tests/unittest_inference.py::InferenceTest::test_slicing_str", "tests/unittest_inference.py::InferenceTest::test_slicing_tuple", "tests/unittest_inference.py::InferenceTest::test_special_method_masquerading_as_another", "tests/unittest_inference.py::InferenceTest::test_starred_in_list_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_literals_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_no_inference_possible", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_non_const_keys_values", "tests/unittest_inference.py::InferenceTest::test_starred_in_set_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_tuple_literal", "tests/unittest_inference.py::InferenceTest::test_stop_iteration_leak", "tests/unittest_inference.py::InferenceTest::test_str_methods", "tests/unittest_inference.py::InferenceTest::test_subscript_inference_error", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_slice", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_value", "tests/unittest_inference.py::InferenceTest::test_subscript_supports__index__", "tests/unittest_inference.py::InferenceTest::test_swap_assign_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_then_list", "tests/unittest_inference.py::InferenceTest::test_tupleassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_two_parents_from_same_module", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_attrs", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_bases", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_mcs_argument", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_name", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_and_ancestors_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__not_enough_arguments", "tests/unittest_inference.py::InferenceTest::test_type__new__with_metaclass", "tests/unittest_inference.py::InferenceTest::test_unary_empty_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_not", "tests/unittest_inference.py::InferenceTest::test_unary_op_assignment", "tests/unittest_inference.py::InferenceTest::test_unary_op_classes", "tests/unittest_inference.py::InferenceTest::test_unary_op_instance_method_not_callable", "tests/unittest_inference.py::InferenceTest::test_unary_op_leaks_stop_iteration", "tests/unittest_inference.py::InferenceTest::test_unary_op_numbers", "tests/unittest_inference.py::InferenceTest::test_unary_operands", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors_for_non_instance_objects", "tests/unittest_inference.py::InferenceTest::test_unbound_method_inference", "tests/unittest_inference.py::InferenceTest::test_unicode_methods", "tests/unittest_inference.py::GetattrTest::test_attribute_missing", "tests/unittest_inference.py::GetattrTest::test_attrname_not_string", "tests/unittest_inference.py::GetattrTest::test_default", "tests/unittest_inference.py::GetattrTest::test_lambda", "tests/unittest_inference.py::GetattrTest::test_lookup", "tests/unittest_inference.py::GetattrTest::test_yes_when_unknown", "tests/unittest_inference.py::HasattrTest::test_attribute_is_missing", "tests/unittest_inference.py::HasattrTest::test_attribute_is_not_missing", "tests/unittest_inference.py::HasattrTest::test_inference_errors", "tests/unittest_inference.py::HasattrTest::test_lambda", "tests/unittest_inference.py::BoolOpTest::test_bool_ops", "tests/unittest_inference.py::BoolOpTest::test_other_nodes", "tests/unittest_inference.py::BoolOpTest::test_yes_when_unknown", "tests/unittest_inference.py::TestCallable::test_callable", "tests/unittest_inference.py::TestCallable::test_callable_methods", "tests/unittest_inference.py::TestCallable::test_inference_errors", "tests/unittest_inference.py::TestCallable::test_not_callable", "tests/unittest_inference.py::TestBool::test_bool", "tests/unittest_inference.py::TestBool::test_bool_bool_special_method", "tests/unittest_inference.py::TestBool::test_bool_instance_not_callable", "tests/unittest_inference.py::TestType::test_type", "tests/unittest_inference.py::ArgumentsTest::test_args", "tests/unittest_inference.py::ArgumentsTest::test_defaults", "tests/unittest_inference.py::ArgumentsTest::test_fail_to_infer_args", "tests/unittest_inference.py::ArgumentsTest::test_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_access_by_name", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_and_other_named_parameters", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_are_overridden", "tests/unittest_inference.py::ArgumentsTest::test_kwonly_args", "tests/unittest_inference.py::ArgumentsTest::test_multiple_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_multiple_starred_args", "tests/unittest_inference.py::SliceTest::test_slice", "tests/unittest_inference.py::SliceTest::test_slice_attributes", "tests/unittest_inference.py::SliceTest::test_slice_inference_error", "tests/unittest_inference.py::SliceTest::test_slice_type", "tests/unittest_inference.py::CallSiteTest::test_call_site", "tests/unittest_inference.py::CallSiteTest::test_call_site_starred_args", "tests/unittest_inference.py::CallSiteTest::test_call_site_valid_arguments", "tests/unittest_inference.py::CallSiteTest::test_duplicated_keyword_arguments", "tests/unittest_inference.py::ObjectDunderNewTest::test_object_dunder_new_is_inferred_if_decorator", "tests/unittest_inference.py::test_augassign_recursion", "tests/unittest_inference.py::test_infer_custom_inherit_from_property", "tests/unittest_inference.py::test_cannot_infer_call_result_for_builtin_methods", "tests/unittest_inference.py::test_unpack_dicts_in_assignment", "tests/unittest_inference.py::test_slice_inference_in_for_loops", "tests/unittest_inference.py::test_slice_inference_in_for_loops_not_working", "tests/unittest_inference.py::test_unpacking_starred_and_dicts_in_assignment", "tests/unittest_inference.py::test_unpacking_starred_empty_list_in_assignment", "tests/unittest_inference.py::test_regression_infinite_loop_decorator", "tests/unittest_inference.py::test_stop_iteration_in_int", "tests/unittest_inference.py::test_call_on_instance_with_inherited_dunder_call_method", "tests/unittest_inference.py::TestInferencePropagation::test_call_starargs_propagation", "tests/unittest_inference.py::TestInferencePropagation::test_call_kwargs_propagation", "tests/unittest_inference.py::test_limit_inference_result_amount", "tests/unittest_inference.py::test_attribute_inference_should_not_access_base_classes", "tests/unittest_inference.py::test_attribute_mro_object_inference", "tests/unittest_inference.py::test_inferred_sequence_unpacking_works", "tests/unittest_inference.py::test_recursion_error_inferring_slice", "tests/unittest_inference.py::test_exception_lookup_last_except_handler_wins", "tests/unittest_inference.py::test_exception_lookup_name_bound_in_except_handler", "tests/unittest_inference.py::test_builtin_inference_list_of_exceptions", "tests/unittest_inference.py::test_cannot_getattr_ann_assigns", "tests/unittest_inference.py::test_prevent_recursion_error_in_igetattr_and_context_manager_inference", "tests/unittest_inference.py::test_infer_context_manager_with_unknown_args", "tests/unittest_inference.py::test_subclass_of_exception[\\n", "tests/unittest_inference.py::test_ifexp_inference", "tests/unittest_inference.py::test_assert_last_function_returns_none_on_inference", "tests/unittest_inference.py::test_posonlyargs_inference", "tests/unittest_inference.py::test_infer_args_unpacking_of_self", "tests/unittest_inference.py::test_infer_exception_instance_attributes", "tests/unittest_inference.py::test_inference_is_limited_to_the_boundnode[\\n", "tests/unittest_inference.py::test_property_inference", "tests/unittest_inference.py::test_property_as_string", "tests/unittest_inference.py::test_property_callable_inference", "tests/unittest_inference.py::test_recursion_error_inferring_builtin_containers", "tests/unittest_inference.py::test_inferaugassign_picking_parent_instead_of_stmt", "tests/unittest_inference.py::test_classmethod_from_builtins_inferred_as_bound", "tests/unittest_inference.py::test_infer_dict_passes_context", "tests/unittest_inference.py::test_custom_decorators_for_classmethod_and_staticmethods[\\n", "tests/unittest_inference.py::test_dataclasses_subscript_inference_recursion_error_39", "tests/unittest_inference.py::test_self_reference_infer_does_not_trigger_recursion_error", "tests/unittest_inference.py::test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_times", "tests/unittest_inference.py::test_getattr_fails_on_empty_values", "tests/unittest_inference.py::test_infer_first_argument_of_static_method_in_metaclass", "tests/unittest_inference.py::test_recursion_error_metaclass_monkeypatching", "tests/unittest_inference.py::test_allow_retrieving_instance_attrs_and_special_attrs_for_functions", "tests/unittest_inference.py::test_implicit_parameters_bound_method", "tests/unittest_inference.py::test_super_inference_of_abstract_property", "tests/unittest_inference.py::test_infer_generated_setter", "tests/unittest_inference.py::test_infer_list_of_uninferables_does_not_crash", "tests/unittest_inference.py::test_issue926_infer_stmts_referencing_same_name_is_not_uninferable", "tests/unittest_inference.py::test_issue926_binop_referencing_same_name_is_not_uninferable"], "environment_setup_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1962", "base_commit": "fe058bff95745371df5796286d33677c21137847", "patch": "diff --git a/astroid/raw_building.py b/astroid/raw_building.py\n--- a/astroid/raw_building.py\n+++ b/astroid/raw_building.py\n@@ -324,6 +324,17 @@ def _build_from_function(\n object_build_function(node, member, name)\n \n \n+def _safe_has_attribute(obj, member: str) -> bool:\n+ \"\"\"Required because unexpected RunTimeError can be raised.\n+\n+ See https://github.com/PyCQA/astroid/issues/1958\n+ \"\"\"\n+ try:\n+ return hasattr(obj, member)\n+ except Exception: # pylint: disable=broad-except\n+ return False\n+\n+\n class InspectBuilder:\n \"\"\"class for building nodes from living object\n \n@@ -419,7 +430,7 @@ def object_build(\n # This should be called for Jython, where some builtin\n # methods aren't caught by isbuiltin branch.\n _build_from_function(node, name, member, self._module)\n- elif hasattr(member, \"__all__\"):\n+ elif _safe_has_attribute(member, \"__all__\"):\n module = build_module(name)\n _attach_local_node(node, module, name)\n # recursion\n", "test_patch": "diff --git a/tests/testdata/python3/data/fake_module_with_broken_getattr.py b/tests/testdata/python3/data/fake_module_with_broken_getattr.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/testdata/python3/data/fake_module_with_broken_getattr.py\n@@ -0,0 +1,7 @@\n+class Broken:\n+\n+ def __getattr__(self, name):\n+ raise Exception(\"boom\")\n+\n+\n+broken = Broken()\ndiff --git a/tests/unittest_raw_building.py b/tests/unittest_raw_building.py\n--- a/tests/unittest_raw_building.py\n+++ b/tests/unittest_raw_building.py\n@@ -1,3 +1,9 @@\n+\"\"\"\n+'tests.testdata.python3.data.fake_module_with_warnings' and\n+'tests.testdata.python3.data.fake_module_with_warnings' are fake modules\n+to simulate issues in unittest below\n+\"\"\"\n+\n # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE\n # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt\n@@ -8,7 +14,7 @@\n import _io\n import pytest\n \n-# A fake module to simulate pandas in unittest below\n+import tests.testdata.python3.data.fake_module_with_broken_getattr as fm_getattr\n import tests.testdata.python3.data.fake_module_with_warnings as fm\n from astroid.builder import AstroidBuilder\n from astroid.const import IS_PYPY\n@@ -102,6 +108,14 @@ def test_build_function_deepinspect_deprecation(self) -> None:\n # This should not raise an exception\n AstroidBuilder().module_build(m, \"test\")\n \n+ def test_module_object_with_broken_getattr(self) -> None:\n+ # Tests https://github.com/PyCQA/astroid/issues/1958\n+ # When astroid deep inspection of modules raises\n+ # errors when using hasattr().\n+\n+ # This should not raise an exception\n+ AstroidBuilder().inspect_build(fm_getattr, \"test\")\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "problem_statement": "v2.13.x regression: Crash when inspecting `PyQt5.QtWidgets` due to `RuntimeError` during `hasattr`\n### Steps to reproduce\r\n\r\nInstall PyQt5, run `pylint --extension-pkg-whitelist=PyQt5 x.py` over a file containing `from PyQt5 import QtWidgets`\r\n\r\n### Current behavior\r\n\r\nWith astroid 2.12.13 and pylint 2.15.10, this works fine. With astroid 2.13.2, this happens:\r\n\r\n```pytb\r\nException on node <ImportFrom l.1 at 0x7fc5a3c47d00> in file '/home/florian/tmp/pylintbug/x.py'\r\nTraceback (most recent call last):\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/utils/ast_walker.py\", line 90, in walk\r\n callback(astroid)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 1726, in visit_importfrom\r\n self._check_module_attrs(node, module, name.split(\".\"))\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 2701, in _check_module_attrs\r\n module = next(module.getattr(name)[0].infer())\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 412, in getattr\r\n result = [self.import_module(name, relative_only=True)]\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 527, in import_module\r\n return AstroidManager().ast_from_module_name(\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 205, in ast_from_module_name\r\n return self.ast_from_module(named_module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 312, in ast_from_module\r\n return AstroidBuilder(self).module_build(module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/builder.py\", line 101, in module_build\r\n node = self.inspect_build(module, modname=modname, path=path)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 366, in inspect_build\r\n self.object_build(node, module)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 422, in object_build\r\n elif hasattr(member, \"__all__\"):\r\nRuntimeError: wrapped C/C++ object of type QApplication has been deleted\r\nx.py:1:0: F0002: x.py: Fatal error while checking 'x.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/home/florian/.cache/pylint/pylint-crash-2023-01-10-11-06-17.txt'. (astroid-error)\r\n```\r\n\r\nIt looks like it happens when `member` is `QtWidgets.qApp`, which is a kind of \"magic\" object referring to the QApplication singleton. Since none exists, it looks like PyQt doesn't like trying to access an attribute on that.\r\n\r\nBisected to:\r\n\r\n- #1885 \r\n\r\nIt looks like 974f26f75eb3eccb4bcd8ea143901baf60a685ff is the exact culprit.\r\n\r\ncc @nickdrozd \r\n\r\n(took the freedom to add appropriate labels already, hope that's fine)\r\n\n", "hints_text": "Thank you for the investigation @The-Compiler ! I'm going to revert the offending commit seeing it's only a cleanup. Let's do something more elegant later on if required.\nThe commit you linked is from a fork, so I tried to reproduce locally to bisect on pylint main repo but I cannot\r\n```\r\npip3 install PyQt5\r\nCollecting PyQt5\r\n Collecting PyQt5-sip<13,>=12.11\r\nCollecting PyQt5-Qt5>=5.15.0\r\nInstalling collected packages: PyQt5-Qt5, PyQt5-sip, PyQt5\r\nSuccessfully installed PyQt5-5.15.7 PyQt5-Qt5-5.15.2 PyQt5-sip-12.11.0\r\n(venv) fix-crash-regression-2.13.2: pylint --extension-pkg-whitelist=PyQt5 x.py \r\n************* Module x\r\nx.py:1:0: W0611: Unused QtWidgets imported from PyQt5 (unused-import)\r\n---------------------------------------------------------------------\r\n\r\nYour code has been rated at 0.00/10 (previous run: -50.00/10, +50.00)\r\n```\r\nCould you provide your other dependencies maybe ?\r\n\n> The commit you linked is from a fork, so I tried to reproduce locally to bisect on pylint main repo but I cannot\r\n\r\nThe main astroid repo bisects to the merge of #1885 (f26dbe419ac15a87ed65e9b55ed15d3d8100b608) - that was a squash merge, 974f26f75eb3eccb4bcd8ea143901baf60a685ff is my guess at what in the PR is the problem.\r\n\r\n> Could you provide your other dependencies maybe ?\r\n\r\nNothing else really:\r\n\r\n```\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ python3 --version\r\nPython 3.10.8\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ python3 -m venv .venv\r\npython3 -m venv .venv 2.87s user 0.26s system 98% cpu 3.170 total\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ .venv/bin/pip install pylint PyQt5\r\nCollecting pylint\r\n Using cached pylint-2.15.10-py3-none-any.whl (509 kB)\r\nCollecting PyQt5\r\n Using cached PyQt5-5.15.7-cp37-abi3-manylinux1_x86_64.whl (8.4 MB)\r\nCollecting tomli>=1.1.0\r\n Using cached tomli-2.0.1-py3-none-any.whl (12 kB)\r\nCollecting tomlkit>=0.10.1\r\n Using cached tomlkit-0.11.6-py3-none-any.whl (35 kB)\r\nCollecting platformdirs>=2.2.0\r\n Using cached platformdirs-2.6.2-py3-none-any.whl (14 kB)\r\nCollecting mccabe<0.8,>=0.6\r\n Using cached mccabe-0.7.0-py2.py3-none-any.whl (7.3 kB)\r\nCollecting dill>=0.2\r\n Using cached dill-0.3.6-py3-none-any.whl (110 kB)\r\nCollecting astroid<=2.14.0-dev0,>=2.12.13\r\n Using cached astroid-2.13.2-py3-none-any.whl (272 kB)\r\nCollecting isort<6,>=4.2.5\r\n Using cached isort-5.11.4-py3-none-any.whl (104 kB)\r\nCollecting PyQt5-Qt5>=5.15.0\r\n Using cached PyQt5_Qt5-5.15.2-py3-none-manylinux2014_x86_64.whl (59.9 MB)\r\nCollecting PyQt5-sip<13,>=12.11\r\n Using cached PyQt5_sip-12.11.0-cp310-cp310-manylinux1_x86_64.whl (359 kB)\r\nCollecting lazy-object-proxy>=1.4.0\r\n Using cached lazy_object_proxy-1.9.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (63 kB)\r\nCollecting wrapt<2,>=1.11\r\n Using cached wrapt-1.14.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (77 kB)\r\nCollecting typing-extensions>=4.0.0\r\n Using cached typing_extensions-4.4.0-py3-none-any.whl (26 kB)\r\nInstalling collected packages: PyQt5-Qt5, wrapt, typing-extensions, tomlkit, tomli, PyQt5-sip, platformdirs, mccabe, lazy-object-proxy, isort, dill, PyQt5, astroid, pylint\r\nSuccessfully installed PyQt5-5.15.7 PyQt5-Qt5-5.15.2 PyQt5-sip-12.11.0 astroid-2.13.2 dill-0.3.6 isort-5.11.4 lazy-object-proxy-1.9.0 mccabe-0.7.0 platformdirs-2.6.2 pylint-2.15.10 tomli-2.0.1 tomlkit-0.11.6 typing-extensions-4.4.0 wrapt-1.14.1\r\n\r\n[notice] A new release of pip available: 22.2.2 -> 22.3.1\r\n[notice] To update, run: python3 -m pip install --upgrade pip\r\n.venv/bin/pip install pylint PyQt5 3.18s user 0.57s system 74% cpu 5.004 total\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ cat x.py\r\nfrom PyQt5 import QtWidgets\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ .venv/bin/pylint --extension-pkg-whitelist=PyQt5 x.py \r\n************* Module x\r\nx.py:1:0: C0114: Missing module docstring (missing-module-docstring)\r\nException on node <ImportFrom l.1 at 0x7fa1f6e37d90> in file '/home/florian/tmp/pylintbug/x.py'\r\nTraceback (most recent call last):\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/utils/ast_walker.py\", line 90, in walk\r\n callback(astroid)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 1726, in visit_importfrom\r\n self._check_module_attrs(node, module, name.split(\".\"))\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 2701, in _check_module_attrs\r\n module = next(module.getattr(name)[0].infer())\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 412, in getattr\r\n result = [self.import_module(name, relative_only=True)]\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 527, in import_module\r\n return AstroidManager().ast_from_module_name(\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 205, in ast_from_module_name\r\n return self.ast_from_module(named_module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 312, in ast_from_module\r\n return AstroidBuilder(self).module_build(module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/builder.py\", line 101, in module_build\r\n node = self.inspect_build(module, modname=modname, path=path)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 366, in inspect_build\r\n self.object_build(node, module)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 422, in object_build\r\n elif hasattr(member, \"__all__\"):\r\nRuntimeError: wrapped C/C++ object of type QApplication has been deleted\r\nx.py:1:0: F0002: x.py: Fatal error while checking 'x.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/home/florian/.cache/pylint/pylint-crash-2023-01-10-12-36-04.txt'. (astroid-error)\r\n\r\n------------------------------------------------------------------\r\nYour code has been rated at 0.00/10 (previous run: 0.00/10, +0.00)\r\n```\r\n", "created_at": "2023-01-10T22:18:32Z", "version": "2.13", "FAIL_TO_PASS": ["tests/unittest_raw_building.py::RawBuildingTC::test_module_object_with_broken_getattr"], "PASS_TO_PASS": ["tests/unittest_raw_building.py::RawBuildingTC::test_attach_dummy_node", "tests/unittest_raw_building.py::RawBuildingTC::test_build_class", "tests/unittest_raw_building.py::RawBuildingTC::test_build_from_import", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_args", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_deepinspect_deprecation", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_defaults", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_kwonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_posonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_module", "tests/unittest_raw_building.py::RawBuildingTC::test_io_is__io"], "environment_setup_commit": "fe058bff95745371df5796286d33677c21137847"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-2240", "base_commit": "514991036806e9cda2b12cef8ab3184ac373bd6c", "patch": "diff --git a/astroid/arguments.py b/astroid/arguments.py\n--- a/astroid/arguments.py\n+++ b/astroid/arguments.py\n@@ -181,7 +181,13 @@ def infer_argument(\n \n positional = self.positional_arguments[: len(funcnode.args.args)]\n vararg = self.positional_arguments[len(funcnode.args.args) :]\n- argindex = funcnode.args.find_argname(name)[0]\n+\n+ # preserving previous behavior, when vararg and kwarg were not included in find_argname results\n+ if name in [funcnode.args.vararg, funcnode.args.kwarg]:\n+ argindex = None\n+ else:\n+ argindex = funcnode.args.find_argname(name)[0]\n+\n kwonlyargs = {arg.name for arg in funcnode.args.kwonlyargs}\n kwargs = {\n key: value\ndiff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py\n--- a/astroid/nodes/node_classes.py\n+++ b/astroid/nodes/node_classes.py\n@@ -605,7 +605,9 @@ def _infer(\n DEPRECATED_ARGUMENT_DEFAULT = \"DEPRECATED_ARGUMENT_DEFAULT\"\n \n \n-class Arguments(_base_nodes.AssignTypeNode):\n+class Arguments(\n+ _base_nodes.AssignTypeNode\n+): # pylint: disable=too-many-instance-attributes\n \"\"\"Class representing an :class:`ast.arguments` node.\n \n An :class:`Arguments` node represents that arguments in a\n@@ -704,7 +706,20 @@ class Arguments(_base_nodes.AssignTypeNode):\n kwargannotation: NodeNG | None\n \"\"\"The type annotation for the variable length keyword arguments.\"\"\"\n \n- def __init__(self, vararg: str | None, kwarg: str | None, parent: NodeNG) -> None:\n+ vararg_node: AssignName | None\n+ \"\"\"The node for variable length arguments\"\"\"\n+\n+ kwarg_node: AssignName | None\n+ \"\"\"The node for variable keyword arguments\"\"\"\n+\n+ def __init__(\n+ self,\n+ vararg: str | None,\n+ kwarg: str | None,\n+ parent: NodeNG,\n+ vararg_node: AssignName | None = None,\n+ kwarg_node: AssignName | None = None,\n+ ) -> None:\n \"\"\"Almost all attributes can be None for living objects where introspection failed.\"\"\"\n super().__init__(\n parent=parent,\n@@ -720,6 +735,9 @@ def __init__(self, vararg: str | None, kwarg: str | None, parent: NodeNG) -> Non\n self.kwarg = kwarg\n \"\"\"The name of the variable length keyword arguments.\"\"\"\n \n+ self.vararg_node = vararg_node\n+ self.kwarg_node = kwarg_node\n+\n # pylint: disable=too-many-arguments\n def postinit(\n self,\n@@ -780,8 +798,21 @@ def fromlineno(self) -> int:\n \n @cached_property\n def arguments(self):\n- \"\"\"Get all the arguments for this node, including positional only and positional and keyword\"\"\"\n- return list(itertools.chain((self.posonlyargs or ()), self.args or ()))\n+ \"\"\"Get all the arguments for this node. This includes:\n+ * Positional only arguments\n+ * Positional arguments\n+ * Keyword arguments\n+ * Variable arguments (.e.g *args)\n+ * Variable keyword arguments (e.g **kwargs)\n+ \"\"\"\n+ retval = list(itertools.chain((self.posonlyargs or ()), (self.args or ())))\n+ if self.vararg_node:\n+ retval.append(self.vararg_node)\n+ retval += self.kwonlyargs or ()\n+ if self.kwarg_node:\n+ retval.append(self.kwarg_node)\n+\n+ return retval\n \n def format_args(self, *, skippable_names: set[str] | None = None) -> str:\n \"\"\"Get the arguments formatted as string.\n@@ -911,15 +942,20 @@ def default_value(self, argname):\n :raises NoDefault: If there is no default value defined for the\n given argument.\n \"\"\"\n- args = self.arguments\n+ args = [\n+ arg for arg in self.arguments if arg.name not in [self.vararg, self.kwarg]\n+ ]\n+\n+ index = _find_arg(argname, self.kwonlyargs)[0]\n+ if index is not None and self.kw_defaults[index] is not None:\n+ return self.kw_defaults[index]\n+\n index = _find_arg(argname, args)[0]\n if index is not None:\n- idx = index - (len(args) - len(self.defaults))\n+ idx = index - (len(args) - len(self.defaults) - len(self.kw_defaults))\n if idx >= 0:\n return self.defaults[idx]\n- index = _find_arg(argname, self.kwonlyargs)[0]\n- if index is not None and self.kw_defaults[index] is not None:\n- return self.kw_defaults[index]\n+\n raise NoDefault(func=self.parent, name=argname)\n \n def is_argument(self, name) -> bool:\n@@ -934,11 +970,7 @@ def is_argument(self, name) -> bool:\n return True\n if name == self.kwarg:\n return True\n- return (\n- self.find_argname(name)[1] is not None\n- or self.kwonlyargs\n- and _find_arg(name, self.kwonlyargs)[1] is not None\n- )\n+ return self.find_argname(name)[1] is not None\n \n def find_argname(self, argname, rec=DEPRECATED_ARGUMENT_DEFAULT):\n \"\"\"Get the index and :class:`AssignName` node for given name.\n@@ -956,7 +988,9 @@ def find_argname(self, argname, rec=DEPRECATED_ARGUMENT_DEFAULT):\n stacklevel=2,\n )\n if self.arguments:\n- return _find_arg(argname, self.arguments)\n+ index, argument = _find_arg(argname, self.arguments)\n+ if argument:\n+ return index, argument\n return None, None\n \n def get_children(self):\ndiff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py\n--- a/astroid/nodes/scoped_nodes/scoped_nodes.py\n+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py\n@@ -963,11 +963,7 @@ def argnames(self) -> list[str]:\n names = [elt.name for elt in self.args.arguments]\n else:\n names = []\n- if self.args.vararg:\n- names.append(self.args.vararg)\n- names += [elt.name for elt in self.args.kwonlyargs]\n- if self.args.kwarg:\n- names.append(self.args.kwarg)\n+\n return names\n \n def infer_call_result(\n@@ -1280,11 +1276,7 @@ def argnames(self) -> list[str]:\n names = [elt.name for elt in self.args.arguments]\n else:\n names = []\n- if self.args.vararg:\n- names.append(self.args.vararg)\n- names += [elt.name for elt in self.args.kwonlyargs]\n- if self.args.kwarg:\n- names.append(self.args.kwarg)\n+\n return names\n \n def getattr(\ndiff --git a/astroid/protocols.py b/astroid/protocols.py\n--- a/astroid/protocols.py\n+++ b/astroid/protocols.py\n@@ -352,14 +352,15 @@ def _arguments_infer_argname(\n # more\n from astroid import arguments # pylint: disable=import-outside-toplevel\n \n- if not (self.arguments or self.vararg or self.kwarg):\n+ if not self.arguments:\n yield util.Uninferable\n return\n \n+ args = [arg for arg in self.arguments if arg.name not in [self.vararg, self.kwarg]]\n functype = self.parent.type\n # first argument of instance/class method\n if (\n- self.arguments\n+ args\n and getattr(self.arguments[0], \"name\", None) == name\n and functype != \"staticmethod\"\n ):\n@@ -388,7 +389,7 @@ def _arguments_infer_argname(\n if name == self.vararg:\n vararg = nodes.const_factory(())\n vararg.parent = self\n- if not self.arguments and self.parent.name == \"__init__\":\n+ if not args and self.parent.name == \"__init__\":\n cls = self.parent.parent.scope()\n vararg.elts = [cls.instantiate_class()]\n yield vararg\ndiff --git a/astroid/rebuilder.py b/astroid/rebuilder.py\n--- a/astroid/rebuilder.py\n+++ b/astroid/rebuilder.py\n@@ -21,6 +21,7 @@\n from astroid.const import IS_PYPY, PY38, PY39_PLUS, PY312_PLUS, Context\n from astroid.manager import AstroidManager\n from astroid.nodes import NodeNG\n+from astroid.nodes.node_classes import AssignName\n from astroid.nodes.utils import Position\n from astroid.typing import InferenceResult\n \n@@ -561,10 +562,33 @@ def visit_arguments(self, node: ast.arguments, parent: NodeNG) -> nodes.Argument\n \"\"\"Visit an Arguments node by returning a fresh instance of it.\"\"\"\n vararg: str | None = None\n kwarg: str | None = None\n+ vararg_node = node.vararg\n+ kwarg_node = node.kwarg\n+\n newnode = nodes.Arguments(\n node.vararg.arg if node.vararg else None,\n node.kwarg.arg if node.kwarg else None,\n parent,\n+ AssignName(\n+ vararg_node.arg,\n+ vararg_node.lineno,\n+ vararg_node.col_offset,\n+ parent,\n+ end_lineno=vararg_node.end_lineno,\n+ end_col_offset=vararg_node.end_col_offset,\n+ )\n+ if vararg_node\n+ else None,\n+ AssignName(\n+ kwarg_node.arg,\n+ kwarg_node.lineno,\n+ kwarg_node.col_offset,\n+ parent,\n+ end_lineno=kwarg_node.end_lineno,\n+ end_col_offset=kwarg_node.end_col_offset,\n+ )\n+ if kwarg_node\n+ else None,\n )\n args = [self.visit(child, newnode) for child in node.args]\n defaults = [self.visit(child, newnode) for child in node.defaults]\n", "test_patch": "diff --git a/tests/test_nodes.py b/tests/test_nodes.py\n--- a/tests/test_nodes.py\n+++ b/tests/test_nodes.py\n@@ -22,6 +22,7 @@\n Uninferable,\n bases,\n builder,\n+ extract_node,\n nodes,\n parse,\n test_utils,\n@@ -1975,3 +1976,38 @@ def test_str_repr_no_warnings(node):\n test_node = node(**args)\n str(test_node)\n repr(test_node)\n+\n+\n+def test_arguments_contains_all():\n+ \"\"\"Ensure Arguments.arguments actually returns all available arguments\"\"\"\n+\n+ def manually_get_args(arg_node) -> set:\n+ names = set()\n+ if arg_node.args.vararg:\n+ names.add(arg_node.args.vararg)\n+ if arg_node.args.kwarg:\n+ names.add(arg_node.args.kwarg)\n+\n+ names.update([x.name for x in arg_node.args.args])\n+ names.update([x.name for x in arg_node.args.kwonlyargs])\n+\n+ return names\n+\n+ node = extract_node(\"\"\"def a(fruit: str, *args, b=None, c=None, **kwargs): ...\"\"\")\n+ assert manually_get_args(node) == {x.name for x in node.args.arguments}\n+\n+ node = extract_node(\"\"\"def a(mango: int, b=\"banana\", c=None, **kwargs): ...\"\"\")\n+ assert manually_get_args(node) == {x.name for x in node.args.arguments}\n+\n+ node = extract_node(\"\"\"def a(self, num = 10, *args): ...\"\"\")\n+ assert manually_get_args(node) == {x.name for x in node.args.arguments}\n+\n+\n+def test_arguments_default_value():\n+ node = extract_node(\n+ \"def fruit(eat='please', *, peel='no', trim='yes', **kwargs): ...\"\n+ )\n+ assert node.args.default_value(\"eat\").value == \"please\"\n+\n+ node = extract_node(\"def fruit(seeds, flavor='good', *, peel='maybe'): ...\")\n+ assert node.args.default_value(\"flavor\").value == \"good\"\n", "problem_statement": "`.arguments` property ignores keyword-only args, *args, and **kwargs\n```python\r\n>>> from astroid import extract_node\r\n>>> node = extract_node(\"\"\"def a(*args, b=None, c=None, **kwargs): ...\"\"\")\r\n>>> node.args.arguments\r\n[]\r\n```\r\n\r\nExpected to find all the arguments from the function signature.\r\n\r\nThe wanted data can be found here:\r\n\r\n```python\r\n>>> node.args.vararg\r\n'args'\r\n>>> node.args.kwarg\r\n'kwargs'\r\n>>> node.args.kwonlyargs\r\n[<AssignName.b l.1 at 0x1048189b0>, <AssignName.c l.1 at 0x104818830>]\r\n```\r\n\r\nDiscussed at https://github.com/pylint-dev/pylint/pull/7577#discussion_r989000829.\r\n\r\nNotice that positional-only args are found for some reason \ud83e\udd37 \n", "hints_text": "Should the definition be changed as well? It states `args.arguments` returns required arguments, and AFAIK in the example none are required (I can call `a` without supplying any arguments).\r\n\r\nI tried running the following:\r\n\r\n```\r\n>>> node = extract_node(\"\"\"def a(kiwi, apple, *args, b=None, c=None, **kwargs): ...\"\"\")\r\n>>> node.args.arguments\r\n[<AssignName.kiwi l.1 at 0x7f5c55986b90>, <AssignName.apple l.1 at 0x7f5c55985a50>]\r\n```\r\n\r\nAnd it seems correct to me :thinking: \nhttps://github.com/pylint-dev/astroid/blob/fef38f2dd474b0dacd1dda3f15abbf61eb0e9a71/astroid/nodes/node_classes.py#L685-L688\r\n\r\nThe docstring seems to be correct?\nDepends on how you parse the language. \"positional and keyword\" could describe the argument `kiwi` and exclude keyword-only arguments.\r\n\r\nEssentially, the crux of this is whether we should\r\n- leave the function as is, and audit everywhere that uses it (given that we keep finding bugs)\r\n- change the function\r\n\r\n@crazybolillo have you happened to sample the places that use this function to be able to offer a view on that? I'd be eager to hear it!\nI think I got confused about the documentation :sob:. I was reading the docstring for `args` (`node.args.args` in the example):\r\n\r\nhttps://github.com/pylint-dev/astroid/blob/d4f4452fe089f600bf9144ffdcd8e698816df3c2/astroid/nodes/node_classes.py#L554-L555\r\n\r\n but we are dealing with `arguments` (`node.args.arguments`). I will review the code further to see if I can come up with something\r\n\r\n", "created_at": "2023-07-06T20:52:39Z", "version": "3.0", "FAIL_TO_PASS": ["tests/test_nodes.py::test_arguments_contains_all"], "PASS_TO_PASS": ["tests/test_nodes.py::AsStringTest::test_3k_annotations_and_metaclass", "tests/test_nodes.py::AsStringTest::test_3k_as_string", "tests/test_nodes.py::AsStringTest::test_as_string", "tests/test_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable", "tests/test_nodes.py::AsStringTest::test_as_string_unknown", "tests/test_nodes.py::AsStringTest::test_class_def", "tests/test_nodes.py::AsStringTest::test_ellipsis", "tests/test_nodes.py::AsStringTest::test_f_strings", "tests/test_nodes.py::AsStringTest::test_frozenset_as_string", "tests/test_nodes.py::AsStringTest::test_func_signature_issue_185", "tests/test_nodes.py::AsStringTest::test_int_attribute", "tests/test_nodes.py::AsStringTest::test_module2_as_string", "tests/test_nodes.py::AsStringTest::test_module_as_string", "tests/test_nodes.py::AsStringTest::test_operator_precedence", "tests/test_nodes.py::AsStringTest::test_slice_and_subscripts", "tests/test_nodes.py::AsStringTest::test_slices", "tests/test_nodes.py::AsStringTest::test_tuple_as_string", "tests/test_nodes.py::AsStringTest::test_varargs_kwargs_as_string", "tests/test_nodes.py::IfNodeTest::test_block_range", "tests/test_nodes.py::IfNodeTest::test_if_elif_else_node", "tests/test_nodes.py::TryNodeTest::test_block_range", "tests/test_nodes.py::TryExceptNodeTest::test_block_range", "tests/test_nodes.py::TryFinallyNodeTest::test_block_range", "tests/test_nodes.py::TryExceptFinallyNodeTest::test_block_range", "tests/test_nodes.py::ImportNodeTest::test_absolute_import", "tests/test_nodes.py::ImportNodeTest::test_as_string", "tests/test_nodes.py::ImportNodeTest::test_bad_import_inference", "tests/test_nodes.py::ImportNodeTest::test_conditional", "tests/test_nodes.py::ImportNodeTest::test_conditional_import", "tests/test_nodes.py::ImportNodeTest::test_from_self_resolve", "tests/test_nodes.py::ImportNodeTest::test_import_self_resolve", "tests/test_nodes.py::ImportNodeTest::test_more_absolute_import", "tests/test_nodes.py::ImportNodeTest::test_real_name", "tests/test_nodes.py::CmpNodeTest::test_as_string", "tests/test_nodes.py::ConstNodeTest::test_bool", "tests/test_nodes.py::ConstNodeTest::test_complex", "tests/test_nodes.py::ConstNodeTest::test_copy", "tests/test_nodes.py::ConstNodeTest::test_float", "tests/test_nodes.py::ConstNodeTest::test_int", "tests/test_nodes.py::ConstNodeTest::test_none", "tests/test_nodes.py::ConstNodeTest::test_str", "tests/test_nodes.py::ConstNodeTest::test_str_kind", "tests/test_nodes.py::ConstNodeTest::test_unicode", "tests/test_nodes.py::NameNodeTest::test_assign_to_true", "tests/test_nodes.py::TestNamedExprNode::test_frame", "tests/test_nodes.py::TestNamedExprNode::test_scope", "tests/test_nodes.py::AnnAssignNodeTest::test_as_string", "tests/test_nodes.py::AnnAssignNodeTest::test_complex", "tests/test_nodes.py::AnnAssignNodeTest::test_primitive", "tests/test_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value", "tests/test_nodes.py::ArgumentsNodeTC::test_kwoargs", "tests/test_nodes.py::ArgumentsNodeTC::test_linenumbering", "tests/test_nodes.py::ArgumentsNodeTC::test_positional_only", "tests/test_nodes.py::UnboundMethodNodeTest::test_no_super_getattr", "tests/test_nodes.py::BoundMethodNodeTest::test_is_property", "tests/test_nodes.py::AliasesTest::test_aliases", "tests/test_nodes.py::Python35AsyncTest::test_async_await_keywords", "tests/test_nodes.py::Python35AsyncTest::test_asyncfor_as_string", "tests/test_nodes.py::Python35AsyncTest::test_asyncwith_as_string", "tests/test_nodes.py::Python35AsyncTest::test_await_as_string", "tests/test_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string", "tests/test_nodes.py::ContextTest::test_list_del", "tests/test_nodes.py::ContextTest::test_list_load", "tests/test_nodes.py::ContextTest::test_list_store", "tests/test_nodes.py::ContextTest::test_starred_load", "tests/test_nodes.py::ContextTest::test_starred_store", "tests/test_nodes.py::ContextTest::test_subscript_del", "tests/test_nodes.py::ContextTest::test_subscript_load", "tests/test_nodes.py::ContextTest::test_subscript_store", "tests/test_nodes.py::ContextTest::test_tuple_load", "tests/test_nodes.py::ContextTest::test_tuple_store", "tests/test_nodes.py::test_unknown", "tests/test_nodes.py::test_type_comments_with", "tests/test_nodes.py::test_type_comments_for", "tests/test_nodes.py::test_type_coments_assign", "tests/test_nodes.py::test_type_comments_invalid_expression", "tests/test_nodes.py::test_type_comments_invalid_function_comments", "tests/test_nodes.py::test_type_comments_function", "tests/test_nodes.py::test_type_comments_arguments", "tests/test_nodes.py::test_type_comments_posonly_arguments", "tests/test_nodes.py::test_correct_function_type_comment_parent", "tests/test_nodes.py::test_is_generator_for_yield_assignments", "tests/test_nodes.py::test_f_string_correct_line_numbering", "tests/test_nodes.py::test_assignment_expression", "tests/test_nodes.py::test_assignment_expression_in_functiondef", "tests/test_nodes.py::test_get_doc", "tests/test_nodes.py::test_parse_fstring_debug_mode", "tests/test_nodes.py::test_parse_type_comments_with_proper_parent", "tests/test_nodes.py::test_const_itered", "tests/test_nodes.py::test_is_generator_for_yield_in_while", "tests/test_nodes.py::test_is_generator_for_yield_in_if", "tests/test_nodes.py::test_is_generator_for_yield_in_aug_assign", "tests/test_nodes.py::test_str_repr_no_warnings[AnnAssign]", "tests/test_nodes.py::test_str_repr_no_warnings[Arguments]", "tests/test_nodes.py::test_str_repr_no_warnings[Assert]", "tests/test_nodes.py::test_str_repr_no_warnings[Assign]", "tests/test_nodes.py::test_str_repr_no_warnings[AssignAttr]", "tests/test_nodes.py::test_str_repr_no_warnings[AssignName]", "tests/test_nodes.py::test_str_repr_no_warnings[AsyncFor]", "tests/test_nodes.py::test_str_repr_no_warnings[AsyncFunctionDef]", "tests/test_nodes.py::test_str_repr_no_warnings[AsyncWith]", "tests/test_nodes.py::test_str_repr_no_warnings[Attribute]", "tests/test_nodes.py::test_str_repr_no_warnings[AugAssign]", "tests/test_nodes.py::test_str_repr_no_warnings[Await]", "tests/test_nodes.py::test_str_repr_no_warnings[BinOp]", "tests/test_nodes.py::test_str_repr_no_warnings[BoolOp]", "tests/test_nodes.py::test_str_repr_no_warnings[Break]", "tests/test_nodes.py::test_str_repr_no_warnings[Call]", "tests/test_nodes.py::test_str_repr_no_warnings[ClassDef]", "tests/test_nodes.py::test_str_repr_no_warnings[Compare]", "tests/test_nodes.py::test_str_repr_no_warnings[Comprehension]", "tests/test_nodes.py::test_str_repr_no_warnings[ComprehensionScope]", "tests/test_nodes.py::test_str_repr_no_warnings[Const]", "tests/test_nodes.py::test_str_repr_no_warnings[Continue]", "tests/test_nodes.py::test_str_repr_no_warnings[Decorators]", "tests/test_nodes.py::test_str_repr_no_warnings[DelAttr]", "tests/test_nodes.py::test_str_repr_no_warnings[Delete]", "tests/test_nodes.py::test_str_repr_no_warnings[DelName]", "tests/test_nodes.py::test_str_repr_no_warnings[Dict]", "tests/test_nodes.py::test_str_repr_no_warnings[DictComp]", "tests/test_nodes.py::test_str_repr_no_warnings[DictUnpack]", "tests/test_nodes.py::test_str_repr_no_warnings[EmptyNode]", "tests/test_nodes.py::test_str_repr_no_warnings[EvaluatedObject]", "tests/test_nodes.py::test_str_repr_no_warnings[ExceptHandler]", "tests/test_nodes.py::test_str_repr_no_warnings[Expr]", "tests/test_nodes.py::test_str_repr_no_warnings[For]", "tests/test_nodes.py::test_str_repr_no_warnings[FormattedValue]", "tests/test_nodes.py::test_str_repr_no_warnings[FunctionDef]", "tests/test_nodes.py::test_str_repr_no_warnings[GeneratorExp]", "tests/test_nodes.py::test_str_repr_no_warnings[Global]", "tests/test_nodes.py::test_str_repr_no_warnings[If]", "tests/test_nodes.py::test_str_repr_no_warnings[IfExp]", "tests/test_nodes.py::test_str_repr_no_warnings[Import]", "tests/test_nodes.py::test_str_repr_no_warnings[ImportFrom]", "tests/test_nodes.py::test_str_repr_no_warnings[JoinedStr]", "tests/test_nodes.py::test_str_repr_no_warnings[Keyword]", "tests/test_nodes.py::test_str_repr_no_warnings[Lambda]", "tests/test_nodes.py::test_str_repr_no_warnings[List]", "tests/test_nodes.py::test_str_repr_no_warnings[ListComp]", "tests/test_nodes.py::test_str_repr_no_warnings[LocalsDictNodeNG]", "tests/test_nodes.py::test_str_repr_no_warnings[Match]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchAs]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchCase]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchClass]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchMapping]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchOr]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchSequence]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchSingleton]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchStar]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchValue]", "tests/test_nodes.py::test_str_repr_no_warnings[Module]", "tests/test_nodes.py::test_str_repr_no_warnings[Name]", "tests/test_nodes.py::test_str_repr_no_warnings[NamedExpr]", "tests/test_nodes.py::test_str_repr_no_warnings[Nonlocal]", "tests/test_nodes.py::test_str_repr_no_warnings[ParamSpec]", "tests/test_nodes.py::test_str_repr_no_warnings[Pass]", "tests/test_nodes.py::test_str_repr_no_warnings[Pattern]", "tests/test_nodes.py::test_str_repr_no_warnings[Raise]", "tests/test_nodes.py::test_str_repr_no_warnings[Return]", "tests/test_nodes.py::test_str_repr_no_warnings[Set]", "tests/test_nodes.py::test_str_repr_no_warnings[SetComp]", "tests/test_nodes.py::test_str_repr_no_warnings[Slice]", "tests/test_nodes.py::test_str_repr_no_warnings[Starred]", "tests/test_nodes.py::test_str_repr_no_warnings[Subscript]", "tests/test_nodes.py::test_str_repr_no_warnings[Try]", "tests/test_nodes.py::test_str_repr_no_warnings[TryStar]", "tests/test_nodes.py::test_str_repr_no_warnings[Tuple]", "tests/test_nodes.py::test_str_repr_no_warnings[TypeAlias]", "tests/test_nodes.py::test_str_repr_no_warnings[TypeVar]", "tests/test_nodes.py::test_str_repr_no_warnings[TypeVarTuple]", "tests/test_nodes.py::test_str_repr_no_warnings[UnaryOp]", "tests/test_nodes.py::test_str_repr_no_warnings[Unknown]", "tests/test_nodes.py::test_str_repr_no_warnings[While]", "tests/test_nodes.py::test_str_repr_no_warnings[With]", "tests/test_nodes.py::test_str_repr_no_warnings[Yield]", "tests/test_nodes.py::test_str_repr_no_warnings[YieldFrom]", "tests/test_nodes.py::test_arguments_default_value"], "environment_setup_commit": "1113d490ec4a94cdc1b35f45abfdaca9f19fa31e"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-941", "base_commit": "962becc0ae86c16f7b33140f43cd6ed8f1e8a045", "patch": "diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py\n--- a/astroid/brain/brain_namedtuple_enum.py\n+++ b/astroid/brain/brain_namedtuple_enum.py\n@@ -315,6 +315,7 @@ def infer_enum_class(node):\n if node.root().name == \"enum\":\n # Skip if the class is directly from enum module.\n break\n+ dunder_members = {}\n for local, values in node.locals.items():\n if any(not isinstance(value, nodes.AssignName) for value in values):\n continue\n@@ -372,7 +373,16 @@ def name(self):\n for method in node.mymethods():\n fake.locals[method.name] = [method]\n new_targets.append(fake.instantiate_class())\n+ dunder_members[local] = fake\n node.locals[local] = new_targets\n+ members = nodes.Dict(parent=node)\n+ members.postinit(\n+ [\n+ (nodes.Const(k, parent=members), nodes.Name(v.name, parent=members))\n+ for k, v in dunder_members.items()\n+ ]\n+ )\n+ node.locals[\"__members__\"] = [members]\n break\n return node\n \ndiff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py\n--- a/astroid/scoped_nodes.py\n+++ b/astroid/scoped_nodes.py\n@@ -2554,7 +2554,7 @@ def igetattr(self, name, context=None, class_context=True):\n context = contextmod.copy_context(context)\n context.lookupname = name\n \n- metaclass = self.declared_metaclass(context=context)\n+ metaclass = self.metaclass(context=context)\n try:\n attributes = self.getattr(name, context, class_context=class_context)\n # If we have more than one attribute, make sure that those starting from\n@@ -2587,9 +2587,12 @@ def igetattr(self, name, context=None, class_context=True):\n yield from function.infer_call_result(\n caller=self, context=context\n )\n- # If we have a metaclass, we're accessing this attribute through\n- # the class itself, which means we can solve the property\n- elif metaclass:\n+ # If we're in a class context, we need to determine if the property\n+ # was defined in the metaclass (a derived class must be a subclass of\n+ # the metaclass of all its bases), in which case we can resolve the\n+ # property. If not, i.e. the property is defined in some base class\n+ # instead, then we return the property object\n+ elif metaclass and function.parent.scope() is metaclass:\n # Resolve a property as long as it is not accessed through\n # the class itself.\n yield from function.infer_call_result(\n", "test_patch": "diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py\n--- a/tests/unittest_scoped_nodes.py\n+++ b/tests/unittest_scoped_nodes.py\n@@ -1923,6 +1923,153 @@ def update(self):\n builder.parse(data)\n \n \n+def test_issue940_metaclass_subclass_property():\n+ node = builder.extract_node(\n+ \"\"\"\n+ class BaseMeta(type):\n+ @property\n+ def __members__(cls):\n+ return ['a', 'property']\n+ class Parent(metaclass=BaseMeta):\n+ pass\n+ class Derived(Parent):\n+ pass\n+ Derived.__members__\n+ \"\"\"\n+ )\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.List)\n+ assert [c.value for c in inferred.elts] == [\"a\", \"property\"]\n+\n+\n+def test_issue940_property_grandchild():\n+ node = builder.extract_node(\n+ \"\"\"\n+ class Grandparent:\n+ @property\n+ def __members__(self):\n+ return ['a', 'property']\n+ class Parent(Grandparent):\n+ pass\n+ class Child(Parent):\n+ pass\n+ Child().__members__\n+ \"\"\"\n+ )\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.List)\n+ assert [c.value for c in inferred.elts] == [\"a\", \"property\"]\n+\n+\n+def test_issue940_metaclass_property():\n+ node = builder.extract_node(\n+ \"\"\"\n+ class BaseMeta(type):\n+ @property\n+ def __members__(cls):\n+ return ['a', 'property']\n+ class Parent(metaclass=BaseMeta):\n+ pass\n+ Parent.__members__\n+ \"\"\"\n+ )\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.List)\n+ assert [c.value for c in inferred.elts] == [\"a\", \"property\"]\n+\n+\n+def test_issue940_with_metaclass_class_context_property():\n+ node = builder.extract_node(\n+ \"\"\"\n+ class BaseMeta(type):\n+ pass\n+ class Parent(metaclass=BaseMeta):\n+ @property\n+ def __members__(self):\n+ return ['a', 'property']\n+ class Derived(Parent):\n+ pass\n+ Derived.__members__\n+ \"\"\"\n+ )\n+ inferred = next(node.infer())\n+ assert not isinstance(inferred, nodes.List)\n+ assert isinstance(inferred, objects.Property)\n+\n+\n+def test_issue940_metaclass_values_funcdef():\n+ node = builder.extract_node(\n+ \"\"\"\n+ class BaseMeta(type):\n+ def __members__(cls):\n+ return ['a', 'func']\n+ class Parent(metaclass=BaseMeta):\n+ pass\n+ Parent.__members__()\n+ \"\"\"\n+ )\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.List)\n+ assert [c.value for c in inferred.elts] == [\"a\", \"func\"]\n+\n+\n+def test_issue940_metaclass_derived_funcdef():\n+ node = builder.extract_node(\n+ \"\"\"\n+ class BaseMeta(type):\n+ def __members__(cls):\n+ return ['a', 'func']\n+ class Parent(metaclass=BaseMeta):\n+ pass\n+ class Derived(Parent):\n+ pass\n+ Derived.__members__()\n+ \"\"\"\n+ )\n+ inferred_result = next(node.infer())\n+ assert isinstance(inferred_result, nodes.List)\n+ assert [c.value for c in inferred_result.elts] == [\"a\", \"func\"]\n+\n+\n+def test_issue940_metaclass_funcdef_is_not_datadescriptor():\n+ node = builder.extract_node(\n+ \"\"\"\n+ class BaseMeta(type):\n+ def __members__(cls):\n+ return ['a', 'property']\n+ class Parent(metaclass=BaseMeta):\n+ @property\n+ def __members__(cls):\n+ return BaseMeta.__members__()\n+ class Derived(Parent):\n+ pass\n+ Derived.__members__\n+ \"\"\"\n+ )\n+ # Here the function is defined on the metaclass, but the property\n+ # is defined on the base class. When loading the attribute in a\n+ # class context, this should return the property object instead of\n+ # resolving the data descriptor\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, objects.Property)\n+\n+\n+def test_issue940_enums_as_a_real_world_usecase():\n+ node = builder.extract_node(\n+ \"\"\"\n+ from enum import Enum\n+ class Sounds(Enum):\n+ bee = \"buzz\"\n+ cat = \"meow\"\n+ Sounds.__members__\n+ \"\"\"\n+ )\n+ inferred_result = next(node.infer())\n+ assert isinstance(inferred_result, nodes.Dict)\n+ actual = [k.value for k, _ in inferred_result.items]\n+ assert sorted(actual) == [\"bee\", \"cat\"]\n+\n+\n def test_metaclass_cannot_infer_call_yields_an_instance():\n node = builder.extract_node(\n \"\"\"\n", "problem_statement": "@property members defined in metaclasses of a base class are not correctly inferred\nRef https://github.com/PyCQA/astroid/issues/927#issuecomment-817244963\r\n\r\nInference works on the parent class but not the child in the following example:\r\n\r\n```python\r\nclass BaseMeta(type):\r\n @property\r\n def __members__(cls):\r\n return ['a', 'property']\r\nclass Parent(metaclass=BaseMeta):\r\n pass\r\nclass Derived(Parent):\r\n pass\r\nParent.__members__ # [<Set.set l.10 at 0x...>]\r\nDerived.__members__ # [<Property.__members__ l.8 at 0x...>]\r\n```\n", "hints_text": "Looks like this is caused by https://github.com/PyCQA/astroid/blob/f2b197a4f8af0ceeddf435747a5c937c8632872a/astroid/scoped_nodes.py#L2590-L2603. When we are inferring an attribute on a derived class then `class_context` is `True` but `metaclass` is `False` so the property itself is returned.", "created_at": "2021-04-11T11:57:22Z", "version": "2.5", "FAIL_TO_PASS": ["tests/unittest_scoped_nodes.py::test_issue940_metaclass_subclass_property", "tests/unittest_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase"], "PASS_TO_PASS": ["tests/unittest_scoped_nodes.py::ModuleNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments", "tests/unittest_scoped_nodes.py::test_issue940_property_grandchild", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_property", "tests/unittest_scoped_nodes.py::test_issue940_with_metaclass_class_context_property", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_values_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_derived_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor", "tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance", "tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef", "tests/unittest_scoped_nodes.py::test_posonlyargs_default_value"], "environment_setup_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1417", "base_commit": "da745538c7236028a22cdf0405f6829fcf6886bc", "patch": "diff --git a/astroid/decorators.py b/astroid/decorators.py\n--- a/astroid/decorators.py\n+++ b/astroid/decorators.py\n@@ -52,6 +52,8 @@ def cached(func, instance, args, kwargs):\n return result\n \n \n+# TODO: Remove when support for 3.7 is dropped\n+# TODO: astroid 3.0 -> move class behind sys.version_info < (3, 8) guard\n class cachedproperty:\n \"\"\"Provides a cached property equivalent to the stacking of\n @cached and @property, but more efficient.\n@@ -70,6 +72,12 @@ class cachedproperty:\n __slots__ = (\"wrapped\",)\n \n def __init__(self, wrapped):\n+ if sys.version_info >= (3, 8):\n+ warnings.warn(\n+ \"cachedproperty has been deprecated and will be removed in astroid 3.0 for Python 3.8+. \"\n+ \"Use functools.cached_property instead.\",\n+ DeprecationWarning,\n+ )\n try:\n wrapped.__name__\n except AttributeError as exc:\ndiff --git a/astroid/mixins.py b/astroid/mixins.py\n--- a/astroid/mixins.py\n+++ b/astroid/mixins.py\n@@ -18,6 +18,7 @@\n \"\"\"This module contains some mixins for the different nodes.\n \"\"\"\n import itertools\n+import sys\n from typing import TYPE_CHECKING, Optional\n \n from astroid import decorators\n@@ -26,11 +27,16 @@\n if TYPE_CHECKING:\n from astroid import nodes\n \n+if sys.version_info >= (3, 8) or TYPE_CHECKING:\n+ from functools import cached_property\n+else:\n+ from astroid.decorators import cachedproperty as cached_property\n+\n \n class BlockRangeMixIn:\n \"\"\"override block range\"\"\"\n \n- @decorators.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n return self.lineno\n \n@@ -135,7 +141,7 @@ class MultiLineBlockMixin:\n Assign nodes, etc.\n \"\"\"\n \n- @decorators.cachedproperty\n+ @cached_property\n def _multi_line_blocks(self):\n return tuple(getattr(self, field) for field in self._multi_line_block_fields)\n \ndiff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py\n--- a/astroid/nodes/node_classes.py\n+++ b/astroid/nodes/node_classes.py\n@@ -80,6 +80,12 @@\n from astroid import nodes\n from astroid.nodes import LocalsDictNodeNG\n \n+if sys.version_info >= (3, 8) or TYPE_CHECKING:\n+ # pylint: disable-next=ungrouped-imports\n+ from functools import cached_property\n+else:\n+ from astroid.decorators import cachedproperty as cached_property\n+\n \n def _is_const(value):\n return isinstance(value, tuple(CONST_CLS))\n@@ -824,7 +830,7 @@ def _infer_name(self, frame, name):\n return name\n return None\n \n- @decorators.cachedproperty\n+ @cached_property\n def fromlineno(self):\n \"\"\"The first line that this node appears on in the source code.\n \n@@ -833,7 +839,7 @@ def fromlineno(self):\n lineno = super().fromlineno\n return max(lineno, self.parent.fromlineno or 0)\n \n- @decorators.cachedproperty\n+ @cached_property\n def arguments(self):\n \"\"\"Get all the arguments for this node, including positional only and positional and keyword\"\"\"\n return list(itertools.chain((self.posonlyargs or ()), self.args or ()))\n@@ -2601,7 +2607,7 @@ def postinit(\n if body is not None:\n self.body = body\n \n- @decorators.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n \"\"\"The line on which the beginning of this block ends.\n \n@@ -2734,7 +2740,7 @@ def postinit(\n See astroid/protocols.py for actual implementation.\n \"\"\"\n \n- @decorators.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n \"\"\"The line on which the beginning of this block ends.\n \n@@ -3093,7 +3099,7 @@ def postinit(\n if isinstance(self.parent, If) and self in self.parent.orelse:\n self.is_orelse = True\n \n- @decorators.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n \"\"\"The line on which the beginning of this block ends.\n \n@@ -3762,7 +3768,7 @@ def _wrap_attribute(self, attr):\n return const\n return attr\n \n- @decorators.cachedproperty\n+ @cached_property\n def _proxied(self):\n builtins = AstroidManager().builtins_module\n return builtins.getattr(\"slice\")[0]\n@@ -4384,7 +4390,7 @@ def postinit(\n if orelse is not None:\n self.orelse = orelse\n \n- @decorators.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n \"\"\"The line on which the beginning of this block ends.\n \n@@ -4500,7 +4506,7 @@ def postinit(\n See astroid/protocols.py for actual implementation.\n \"\"\"\n \n- @decorators.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n \"\"\"The line on which the beginning of this block ends.\n \ndiff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py\n--- a/astroid/nodes/node_ng.py\n+++ b/astroid/nodes/node_ng.py\n@@ -38,6 +38,12 @@\n else:\n from typing_extensions import Literal\n \n+if sys.version_info >= (3, 8) or TYPE_CHECKING:\n+ # pylint: disable-next=ungrouped-imports\n+ from functools import cached_property\n+else:\n+ # pylint: disable-next=ungrouped-imports\n+ from astroid.decorators import cachedproperty as cached_property\n \n # Types for 'NodeNG.nodes_of_class()'\n T_Nodes = TypeVar(\"T_Nodes\", bound=\"NodeNG\")\n@@ -435,14 +441,14 @@ def previous_sibling(self):\n # these are lazy because they're relatively expensive to compute for every\n # single node, and they rarely get looked at\n \n- @decorators.cachedproperty\n+ @cached_property\n def fromlineno(self) -> Optional[int]:\n \"\"\"The first line that this node appears on in the source code.\"\"\"\n if self.lineno is None:\n return self._fixed_source_line()\n return self.lineno\n \n- @decorators.cachedproperty\n+ @cached_property\n def tolineno(self) -> Optional[int]:\n \"\"\"The last line that this node appears on in the source code.\"\"\"\n if self.end_lineno is not None:\ndiff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py\n--- a/astroid/nodes/scoped_nodes/scoped_nodes.py\n+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py\n@@ -52,7 +52,7 @@\n import sys\n import typing\n import warnings\n-from typing import Dict, List, Optional, Set, TypeVar, Union, overload\n+from typing import TYPE_CHECKING, Dict, List, Optional, Set, TypeVar, Union, overload\n \n from astroid import bases\n from astroid import decorators as decorators_mod\n@@ -93,6 +93,12 @@\n else:\n from typing_extensions import Literal\n \n+if sys.version_info >= (3, 8) or TYPE_CHECKING:\n+ from functools import cached_property\n+else:\n+ # pylint: disable-next=ungrouped-imports\n+ from astroid.decorators import cachedproperty as cached_property\n+\n \n ITER_METHODS = (\"__iter__\", \"__getitem__\")\n EXCEPTION_BASE_CLASSES = frozenset({\"Exception\", \"BaseException\"})\n@@ -1611,7 +1617,7 @@ def postinit(\n self.position = position\n self.doc_node = doc_node\n \n- @decorators_mod.cachedproperty\n+ @cached_property\n def extra_decorators(self) -> List[node_classes.Call]:\n \"\"\"The extra decorators that this function can have.\n \n@@ -1652,7 +1658,7 @@ def extra_decorators(self) -> List[node_classes.Call]:\n decorators.append(assign.value)\n return decorators\n \n- @decorators_mod.cachedproperty\n+ @cached_property\n def type(\n self,\n ): # pylint: disable=invalid-overridden-method,too-many-return-statements\n@@ -1726,7 +1732,7 @@ def type(\n pass\n return type_name\n \n- @decorators_mod.cachedproperty\n+ @cached_property\n def fromlineno(self) -> Optional[int]:\n \"\"\"The first line that this node appears on in the source code.\"\"\"\n # lineno is the line number of the first decorator, we want the def\n@@ -1739,7 +1745,7 @@ def fromlineno(self) -> Optional[int]:\n \n return lineno\n \n- @decorators_mod.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n \"\"\"The line on which the beginning of this block ends.\n \n@@ -2337,7 +2343,7 @@ def _newstyle_impl(self, context=None):\n doc=(\"Whether this is a new style class or not\\n\\n\" \":type: bool or None\"),\n )\n \n- @decorators_mod.cachedproperty\n+ @cached_property\n def fromlineno(self) -> Optional[int]:\n \"\"\"The first line that this node appears on in the source code.\"\"\"\n if not PY38_PLUS:\n@@ -2352,7 +2358,7 @@ def fromlineno(self) -> Optional[int]:\n return lineno\n return super().fromlineno\n \n- @decorators_mod.cachedproperty\n+ @cached_property\n def blockstart_tolineno(self):\n \"\"\"The line on which the beginning of this block ends.\n \ndiff --git a/astroid/objects.py b/astroid/objects.py\n--- a/astroid/objects.py\n+++ b/astroid/objects.py\n@@ -22,8 +22,10 @@\n Call(func=Name('frozenset'), args=Tuple(...))\n \"\"\"\n \n+import sys\n+from typing import TYPE_CHECKING\n \n-from astroid import bases, decorators, util\n+from astroid import bases, util\n from astroid.exceptions import (\n AttributeInferenceError,\n InferenceError,\n@@ -35,6 +37,11 @@\n \n objectmodel = util.lazy_import(\"interpreter.objectmodel\")\n \n+if sys.version_info >= (3, 8) or TYPE_CHECKING:\n+ from functools import cached_property\n+else:\n+ from astroid.decorators import cachedproperty as cached_property\n+\n \n class FrozenSet(node_classes.BaseContainer):\n \"\"\"class representing a FrozenSet composite node\"\"\"\n@@ -45,7 +52,7 @@ def pytype(self):\n def _infer(self, context=None):\n yield self\n \n- @decorators.cachedproperty\n+ @cached_property\n def _proxied(self): # pylint: disable=method-hidden\n ast_builtins = AstroidManager().builtins_module\n return ast_builtins.getattr(\"frozenset\")[0]\n@@ -114,7 +121,7 @@ def super_mro(self):\n index = mro.index(self.mro_pointer)\n return mro[index + 1 :]\n \n- @decorators.cachedproperty\n+ @cached_property\n def _proxied(self):\n ast_builtins = AstroidManager().builtins_module\n return ast_builtins.getattr(\"super\")[0]\n@@ -218,7 +225,7 @@ class ExceptionInstance(bases.Instance):\n the case of .args.\n \"\"\"\n \n- @decorators.cachedproperty\n+ @cached_property\n def special_attributes(self):\n qname = self.qname()\n instance = objectmodel.BUILTIN_EXCEPTIONS.get(\n", "test_patch": "diff --git a/tests/unittest_decorators.py b/tests/unittest_decorators.py\n--- a/tests/unittest_decorators.py\n+++ b/tests/unittest_decorators.py\n@@ -1,7 +1,8 @@\n import pytest\n from _pytest.recwarn import WarningsRecorder\n \n-from astroid.decorators import deprecate_default_argument_values\n+from astroid.const import PY38_PLUS\n+from astroid.decorators import cachedproperty, deprecate_default_argument_values\n \n \n class SomeClass:\n@@ -97,3 +98,18 @@ def test_deprecated_default_argument_values_ok(recwarn: WarningsRecorder) -> Non\n instance = SomeClass(name=\"some_name\")\n instance.func(name=\"\", var=42)\n assert len(recwarn) == 0\n+\n+\[email protected](not PY38_PLUS, reason=\"Requires Python 3.8 or higher\")\n+def test_deprecation_warning_on_cachedproperty() -> None:\n+ \"\"\"Check the DeprecationWarning on cachedproperty.\"\"\"\n+\n+ with pytest.warns(DeprecationWarning) as records:\n+\n+ class MyClass: # pylint: disable=unused-variable\n+ @cachedproperty\n+ def my_property(self):\n+ return 1\n+\n+ assert len(records) == 1\n+ assert \"functools.cached_property\" in records[0].message.args[0]\n", "problem_statement": "Replace `cachedproperty` with `functools.cached_property` (>= 3.8)\nI thought about this PR recently again. Typing `cachedproperty` might not work, but it can be replaced with `functools.cached_property`. We only need to `sys` guard it for `< 3.8`. This should work\r\n```py\r\nif sys.version_info >= (3, 8):\r\n from functools import cached_property\r\nelse:\r\n from astroid.decorators import cachedproperty as cached_property\r\n```\r\n\r\nAdditionally, the deprecation warning can be limited to `>= 3.8`.\r\n\r\n_Originally posted by @cdce8p in https://github.com/PyCQA/astroid/issues/1243#issuecomment-1052834322_\n", "hints_text": "@cdce8p Just thinking out loud: can we also use a type guard to define `cached_property`? Would `mypy` pick up on that? \n> @cdce8p Just thinking out loud: can we also use a type guard to define `cached_property`? Would `mypy` pick up on that?\r\n\r\nNot completely sure what you want to do with that.\r\n\r\nOn other thing, I just saw that we don't set the `python-version` for mypy. If we do that, we probably need to do some more workarounds to tell mypy `cachedproperty` is equal to `cached_property`. Adding `TYPE_CHECKING` could work\r\n```py\r\nif sys.version_info >= (3, 8) or TYPE_CHECKING:\r\n from functools import cached_property\r\nelse:\r\n from astroid.decorators import cachedproperty as cached_property\r\n```", "created_at": "2022-03-01T18:24:29Z", "version": "2.10", "FAIL_TO_PASS": ["tests/unittest_decorators.py::test_deprecation_warning_on_cachedproperty"], "PASS_TO_PASS": ["tests/unittest_decorators.py::TestDeprecationDecorators::test_deprecated_default_argument_values_one_arg", "tests/unittest_decorators.py::TestDeprecationDecorators::test_deprecated_default_argument_values_two_args", "tests/unittest_decorators.py::TestDeprecationDecorators::test_deprecated_default_argument_values_ok"], "environment_setup_commit": "da745538c7236028a22cdf0405f6829fcf6886bc"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1364", "base_commit": "9363c34934f94124f4867caf1bdf8f6755201ccd", "patch": "diff --git a/astroid/const.py b/astroid/const.py\n--- a/astroid/const.py\n+++ b/astroid/const.py\n@@ -8,6 +8,8 @@\n PY310_PLUS = sys.version_info >= (3, 10)\n BUILTINS = \"builtins\" # TODO Remove in 2.8\n \n+WIN32 = sys.platform == \"win32\"\n+\n \n class Context(enum.Enum):\n Load = 1\n", "test_patch": "diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py\n--- a/tests/unittest_scoped_nodes.py\n+++ b/tests/unittest_scoped_nodes.py\n@@ -43,9 +43,9 @@\n \n import pytest\n \n-from astroid import MANAGER, builder, nodes, objects, test_utils, util\n+from astroid import MANAGER, builder, nodes, objects, parse, test_utils, util\n from astroid.bases import BoundMethod, Generator, Instance, UnboundMethod\n-from astroid.const import PY38_PLUS\n+from astroid.const import PY38_PLUS, PY310_PLUS, WIN32\n from astroid.exceptions import (\n AttributeInferenceError,\n DuplicateBasesError,\n@@ -1670,6 +1670,49 @@ class B(A[T], A[T]): ...\n with self.assertRaises(DuplicateBasesError):\n cls.mro()\n \n+ @test_utils.require_version(minver=\"3.7\")\n+ def test_mro_typing_extensions(self):\n+ \"\"\"Regression test for mro() inference on typing_extesnions.\n+\n+ Regression reported in:\n+ https://github.com/PyCQA/astroid/issues/1124\n+ \"\"\"\n+ module = parse(\n+ \"\"\"\n+ import abc\n+ import typing\n+ import dataclasses\n+\n+ import typing_extensions\n+\n+ T = typing.TypeVar(\"T\")\n+\n+ class MyProtocol(typing_extensions.Protocol): pass\n+ class EarlyBase(typing.Generic[T], MyProtocol): pass\n+ class Base(EarlyBase[T], abc.ABC): pass\n+ class Final(Base[object]): pass\n+ \"\"\"\n+ )\n+ class_names = [\n+ \"ABC\",\n+ \"Base\",\n+ \"EarlyBase\",\n+ \"Final\",\n+ \"Generic\",\n+ \"MyProtocol\",\n+ \"Protocol\",\n+ \"object\",\n+ ]\n+ if not PY38_PLUS:\n+ class_names.pop(-2)\n+ # typing_extensions is not installed on this combination of version\n+ # and platform\n+ if PY310_PLUS and WIN32:\n+ class_names.pop(-2)\n+\n+ final_def = module.body[-1]\n+ self.assertEqual(class_names, sorted(i.name for i in final_def.mro()))\n+\n def test_generator_from_infer_call_result_parent(self) -> None:\n func = builder.extract_node(\n \"\"\"\n", "problem_statement": "MRO failure on Python 3.7 with typing_extensions\n### Steps to reproduce\r\n\r\nRun the following script on Python 3.7:\r\n\r\n```python\r\nfrom astroid import parse\r\nmodule = parse(\"\"\"\r\nimport abc\r\nimport typing\r\nimport dataclasses\r\n\r\nimport typing_extensions\r\n\r\nT = typing.TypeVar(\"T\")\r\n\r\nclass MyProtocol(typing_extensions.Protocol): pass\r\nclass EarlyBase(typing.Generic[T], MyProtocol): pass\r\nclass Base(EarlyBase[T], abc.ABC): pass\r\nclass Final(Base[object]): pass\r\n\"\"\")\r\n\r\n# typing.Protocol\r\n# |\r\n# typing.Generic[T] MyProtocol\r\n# \\ /\r\n# EarlyBase abc.ABC\r\n# \\ /\r\n# Base\r\n# |\r\n# Final\r\n\r\nfinal_def = module.body[-1]\r\nfinal_def.mro()\r\n```\r\n\r\n### Current behavior\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"xxx.py\", line 31, in <module>\r\n print(\"mro:\", final_def.mro())\r\n File \"/home/rturner/astroid/astroid/nodes/scoped_nodes.py\", line 3009, in mro\r\n return self._compute_mro(context=context)\r\n File \"/home/rturner/astroid/astroid/nodes/scoped_nodes.py\", line 2985, in _compute_mro\r\n mro = base._compute_mro(context=context)\r\n File \"/home/rturner/astroid/astroid/nodes/scoped_nodes.py\", line 2999, in _compute_mro\r\n return _c3_merge(unmerged_mro, self, context)\r\n File \"/home/rturner/astroid/astroid/nodes/scoped_nodes.py\", line 103, in _c3_merge\r\n context=context,\r\nastroid.exceptions.InconsistentMroError: Cannot create a consistent method resolution order for MROs (tuple, object), (EarlyBase, tuple, Generic, object, MyProtocol), (ABC, object), (tuple, EarlyBase, ABC) of class <ClassDef.Base l.1347 at 0x7fa0efd52590>.\r\n```\r\n\r\n### Expected behavior\r\n\r\nNo MRO error is raised; Python 3.7 doesn't raise an error.\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.6.7-dev0; the test case fails in pylint 2.9.6 and on the main branch at commit 6e8699cef0888631bd827b096533fc6e894d2fb2.\n", "hints_text": "", "created_at": "2022-01-20T10:00:25Z", "version": "2.10", "FAIL_TO_PASS": ["tests/unittest_scoped_nodes.py::ModuleNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_typing_extensions", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_subclass_property", "tests/unittest_scoped_nodes.py::test_issue940_property_grandchild", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_property", "tests/unittest_scoped_nodes.py::test_issue940_with_metaclass_class_context_property", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_values_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_derived_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor", "tests/unittest_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase", "tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance", "tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef", "tests/unittest_scoped_nodes.py::test_posonlyargs_default_value", "tests/unittest_scoped_nodes.py::test_ancestor_with_generic", "tests/unittest_scoped_nodes.py::test_slots_duplicate_bases_issue_1089", "tests/unittest_scoped_nodes.py::TestFrameNodes::test_frame_node", "tests/unittest_scoped_nodes.py::TestFrameNodes::test_non_frame_node"], "PASS_TO_PASS": [], "environment_setup_commit": "da745538c7236028a22cdf0405f6829fcf6886bc"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-2023", "base_commit": "2108ae51b516458243c249cf67301cb387e33afa", "patch": "diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py\n--- a/astroid/nodes/node_classes.py\n+++ b/astroid/nodes/node_classes.py\n@@ -137,10 +137,14 @@ def are_exclusive(stmt1, stmt2, exceptions: list[str] | None = None) -> bool:\n # if the common parent is a If or TryExcept statement, look if\n # nodes are in exclusive branches\n if isinstance(node, If) and exceptions is None:\n- if (\n- node.locate_child(previous)[1]\n- is not node.locate_child(children[node])[1]\n- ):\n+ c2attr, c2node = node.locate_child(previous)\n+ c1attr, c1node = node.locate_child(children[node])\n+ if \"test\" in (c1attr, c2attr):\n+ # If any node is `If.test`, then it must be inclusive with\n+ # the other node (`If.body` and `If.orelse`)\n+ return False\n+ if c1attr != c2attr:\n+ # different `If` branches (`If.body` and `If.orelse`)\n return True\n elif isinstance(node, TryExcept):\n c2attr, c2node = node.locate_child(previous)\n", "test_patch": "diff --git a/tests/test_utils.py b/tests/test_utils.py\n--- a/tests/test_utils.py\n+++ b/tests/test_utils.py\n@@ -4,7 +4,10 @@\n \n import unittest\n \n-from astroid import Uninferable, builder, nodes\n+import pytest\n+\n+from astroid import Uninferable, builder, extract_node, nodes\n+from astroid.const import PY38_PLUS\n from astroid.exceptions import InferenceError\n \n \n@@ -30,6 +33,78 @@ def test_not_exclusive(self) -> None:\n self.assertEqual(nodes.are_exclusive(xass1, xnames[1]), False)\n self.assertEqual(nodes.are_exclusive(xass1, xnames[2]), False)\n \n+ @pytest.mark.skipif(not PY38_PLUS, reason=\"needs assignment expressions\")\n+ def test_not_exclusive_walrus_operator(self) -> None:\n+ node_if, node_body, node_or_else = extract_node(\n+ \"\"\"\n+ if val := True: #@\n+ print(val) #@\n+ else:\n+ print(val) #@\n+ \"\"\"\n+ )\n+ node_if: nodes.If\n+ node_walrus = next(node_if.nodes_of_class(nodes.NamedExpr))\n+\n+ assert nodes.are_exclusive(node_walrus, node_if) is False\n+ assert nodes.are_exclusive(node_walrus, node_body) is False\n+ assert nodes.are_exclusive(node_walrus, node_or_else) is False\n+\n+ assert nodes.are_exclusive(node_if, node_body) is False\n+ assert nodes.are_exclusive(node_if, node_or_else) is False\n+ assert nodes.are_exclusive(node_body, node_or_else) is True\n+\n+ @pytest.mark.skipif(not PY38_PLUS, reason=\"needs assignment expressions\")\n+ def test_not_exclusive_walrus_multiple(self) -> None:\n+ node_if, body_1, body_2, or_else_1, or_else_2 = extract_node(\n+ \"\"\"\n+ if (val := True) or (val_2 := True): #@\n+ print(val) #@\n+ print(val_2) #@\n+ else:\n+ print(val) #@\n+ print(val_2) #@\n+ \"\"\"\n+ )\n+ node_if: nodes.If\n+ walruses = list(node_if.nodes_of_class(nodes.NamedExpr))\n+\n+ assert nodes.are_exclusive(node_if, walruses[0]) is False\n+ assert nodes.are_exclusive(node_if, walruses[1]) is False\n+\n+ assert nodes.are_exclusive(walruses[0], walruses[1]) is False\n+\n+ assert nodes.are_exclusive(walruses[0], body_1) is False\n+ assert nodes.are_exclusive(walruses[0], body_2) is False\n+ assert nodes.are_exclusive(walruses[1], body_1) is False\n+ assert nodes.are_exclusive(walruses[1], body_2) is False\n+\n+ assert nodes.are_exclusive(walruses[0], or_else_1) is False\n+ assert nodes.are_exclusive(walruses[0], or_else_2) is False\n+ assert nodes.are_exclusive(walruses[1], or_else_1) is False\n+ assert nodes.are_exclusive(walruses[1], or_else_2) is False\n+\n+ @pytest.mark.skipif(not PY38_PLUS, reason=\"needs assignment expressions\")\n+ def test_not_exclusive_walrus_operator_nested(self) -> None:\n+ node_if, node_body, node_or_else = extract_node(\n+ \"\"\"\n+ if all((last_val := i) % 2 == 0 for i in range(10)): #@\n+ print(last_val) #@\n+ else:\n+ print(last_val) #@\n+ \"\"\"\n+ )\n+ node_if: nodes.If\n+ node_walrus = next(node_if.nodes_of_class(nodes.NamedExpr))\n+\n+ assert nodes.are_exclusive(node_walrus, node_if) is False\n+ assert nodes.are_exclusive(node_walrus, node_body) is False\n+ assert nodes.are_exclusive(node_walrus, node_or_else) is False\n+\n+ assert nodes.are_exclusive(node_if, node_body) is False\n+ assert nodes.are_exclusive(node_if, node_or_else) is False\n+ assert nodes.are_exclusive(node_body, node_or_else) is True\n+\n def test_if(self) -> None:\n module = builder.parse(\n \"\"\"\n", "problem_statement": "Invalid variable lookup when walrus operator is used\n### Steps to reproduce\r\n1. Consider following code in `loop_error.py`:\r\n\t```\r\n \"\"\"Test module\"\"\"\r\n\r\n\r\n\tdef walrus_in_comprehension_test_2(some_path, module_namespace):\r\n\t \"\"\"Suspected error\"\"\"\r\n\t for mod in some_path.iterdir():\r\n\t print(mod)\r\n\t\r\n\t for org_mod in some_path.iterdir():\r\n\t if org_mod.is_dir():\r\n\t if mod := module_namespace.get_mod_from_alias(org_mod.name):\r\n\t new_name = mod.name\r\n\t else:\r\n\t new_name = org_mod.name\r\n\t\r\n\t print(new_name)\r\n\t```\r\n2. Run `pylint ./loop_error.py`\r\n\r\n### Current behavior\r\nA warning appears: ```W0631: Using possibly undefined loop variable 'mod' (undefined-loop-variable)```\r\n\r\n### Expected behavior\r\nNo warning, because the variable `mod` is always defined.\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n- 2.14.1\r\n- 2.15.0-dev0 on 56a65daf1ba391cc85d1a32a8802cfd0c7b7b2ab with Python 3.10.6\n", "hints_text": "## Investigation\r\nI tried to understand the possible reason for this warning. \r\n\r\n### Minimum reproducible code\r\nIt seems ultra-rare case, because we cannot:\r\n- remove first loop (`for mod in some_path.iterdir():`),\r\n- remove first condition (`if org_mod.is_dir():`),\r\n- rewrite walrus operator to standard assignment (`mod :=`),\r\n- remove `else` with body,\r\n\r\notherwise, there is no error.\r\n\r\n### Tracked calls\r\n- [`pylint/checkers/variables.py:_loopvar_name:419`](https://github.com/PyCQA/pylint/blob/bd22f2822f9344487357c90e18a8505705c60a29/pylint/checkers/variables.py#L2419) - in this function we got only 1 statement in `astmts` - should be 2,\r\n- I looked at `scope_lookup` functions. Until [`astroid/filter_statements.py:_filter_stmts:201`](https://github.com/PyCQA/astroid/blob/56a65daf1ba391cc85d1a32a8802cfd0c7b7b2ab/astroid/filter_statements.py#L201) there are always 2 statements - that is good.\r\n- So the problem is in [`astroid.are_exclusive`](https://github.com/PyCQA/astroid/blob/56a65daf1ba391cc85d1a32a8802cfd0c7b7b2ab/astroid/nodes/node_classes.py#L140). Probably there is an invalid (old, before Python 3.8) assumption that `ast.IfExp` branches are searched only in `IfExp.body` and `IfExp.orelse` and therefore they must be exclusive. But it turns out that if assignment is in `IfExp.test` (i.e. walrus operator), branches are not exclusive - actually there are always inclusive.\r\n\r\n### Simpler minimum reproducible code\r\nIt seems that this code is a minimum to reproduce error:\r\n```\r\nfrom astroid import nodes, extract_node\r\n\r\nnode_if, node_body, node_or_else = extract_node(\"\"\"\r\n if val := True: #@\r\n print(val) #@ \r\n else:\r\n print(val) #@\r\n \"\"\")\r\nnode_if: nodes.If\r\nnode_walrus = next(node_if.nodes_of_class(nodes.NamedExpr))\r\n\r\nassert not nodes.are_exclusive(node_walrus, node_body)\r\n```\r\n\r\n I will try to fix it and add test cases.", "created_at": "2023-02-11T18:13:13Z", "version": "2.15", "FAIL_TO_PASS": ["tests/test_utils.py::InferenceUtil::test_not_exclusive_walrus_multiple", "tests/test_utils.py::InferenceUtil::test_not_exclusive_walrus_operator", "tests/test_utils.py::InferenceUtil::test_not_exclusive_walrus_operator_nested"], "PASS_TO_PASS": ["tests/test_utils.py::InferenceUtil::test_if", "tests/test_utils.py::InferenceUtil::test_not_exclusive", "tests/test_utils.py::InferenceUtil::test_try_except", "tests/test_utils.py::InferenceUtil::test_unpack_infer_empty_tuple", "tests/test_utils.py::InferenceUtil::test_unpack_infer_uninferable_nodes"], "environment_setup_commit": "29b42e5e9745b172d5980511d14efeac745a5a82"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1719", "base_commit": "5bb3ddef43b35c07485a84f90b6a453fc649e31d", "patch": "diff --git a/astroid/raw_building.py b/astroid/raw_building.py\n--- a/astroid/raw_building.py\n+++ b/astroid/raw_building.py\n@@ -388,9 +388,9 @@ def object_build(\n pypy__class_getitem__ = IS_PYPY and name == \"__class_getitem__\"\n try:\n with warnings.catch_warnings():\n- warnings.simplefilter(\"error\")\n+ warnings.simplefilter(\"ignore\")\n member = getattr(obj, name)\n- except (AttributeError, DeprecationWarning):\n+ except (AttributeError):\n # damned ExtensionClass.Base, I know you're there !\n attach_dummy_node(node, name)\n continue\n", "test_patch": "diff --git a/tests/testdata/python3/data/fake_module_with_warnings.py b/tests/testdata/python3/data/fake_module_with_warnings.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/testdata/python3/data/fake_module_with_warnings.py\n@@ -0,0 +1,22 @@\n+'''\n+This is a mock of a module like Pandas, which can throw warnings for deprecated attributes\n+'''\n+import warnings\n+\n+\n+def __dir__():\n+ # GH43028\n+ # Int64Index etc. are deprecated, but we still want them to be available in the dir.\n+ # Remove in Pandas 2.0, when we remove Int64Index etc. from the code base.\n+ return list(globals().keys()) + [\"Float64Index\"]\n+\n+\n+def __getattr__(name):\n+ if name == \"Float64Index\":\n+ warnings.warn(\"This is what pandas would do\", FutureWarning, stacklevel=2)\n+ return 5\n+ raise AttributeError(f\"module 'pandas' has no attribute '{name}'\")\n+\n+\n+__all__ = [\"Float64Index\"] # pylint: disable=E0603\n+__doc__ = \"\"\ndiff --git a/tests/unittest_raw_building.py b/tests/unittest_raw_building.py\n--- a/tests/unittest_raw_building.py\n+++ b/tests/unittest_raw_building.py\n@@ -2,11 +2,14 @@\n # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE\n # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt\n \n+import types\n import unittest\n \n import _io\n import pytest\n \n+# A fake module to simulate pandas in unittest below\n+import tests.testdata.python3.data.fake_module_with_warnings as fm\n from astroid.builder import AstroidBuilder\n from astroid.const import IS_PYPY\n from astroid.raw_building import (\n@@ -86,6 +89,19 @@ def test_io_is__io(self):\n buffered_reader = module.getattr(\"BufferedReader\")[0]\n self.assertEqual(buffered_reader.root().name, \"io\")\n \n+ def test_build_function_deepinspect_deprecation(self) -> None:\n+ # Tests https://github.com/PyCQA/astroid/issues/1717\n+ # When astroid deep inspection of modules raises\n+ # attribute errors when getting all attributes\n+ # Create a mock module to simulate a Cython module\n+ m = types.ModuleType(\"test\")\n+\n+ # Attach a mock of pandas with the same behavior\n+ m.pd = fm\n+\n+ # This should not raise an exception\n+ AstroidBuilder().module_build(m, \"test\")\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "problem_statement": "Cython module with import triggers deep introspection for pandas, raises unhandled FutureWarning\nThis is a somewhat complicated situation to reproduce, but basically `pandas` throws `FutureWarning`s for certain attributes, and when you import it into a Cython module (triggering astroid's deep module inspection), these future warnings are not handled by astroid and bubble up as `AstroidError`s through to pylint. Here is a full repro:\r\n\r\n\r\n### Cython module `pyx.pyx`\r\n\r\n```python\r\n# distutils: language = c++\r\nimport pandas as pd\r\n\r\ncdef class Test:\r\n def __cinit__(self):\r\n ...\r\n```\r\n\r\n\r\n### Python module `test.py`\r\n\r\n```python\r\nimport pyx\r\n\r\npyx.Test()\r\n```\r\n\r\n\r\n\r\n### Commands\r\n```\r\ncythonize -a -i pyx.pyx\r\npylint --extension-pkg-allow-list=pyx,pandas test.py\r\n```\r\n\r\n\r\n### Exception\r\n```\r\nException on node <Import l.1 at 0x106b23ca0> in file '/Users/timkpaine/Programs/projects/other/astroid/test.py'\r\nTraceback (most recent call last):\r\n File \"/opt/homebrew/lib/python3.9/site-packages/pylint/checkers/imports.py\", line 765, in _get_imported_module\r\n return importnode.do_import_module(modname)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/mixins.py\", line 102, in do_import_module\r\n return mymodule.import_module(\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 527, in import_module\r\n return AstroidManager().ast_from_module_name(absmodname)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/manager.py\", line 168, in ast_from_module_name\r\n return self.ast_from_module(module, modname)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/manager.py\", line 265, in ast_from_module\r\n return AstroidBuilder(self).module_build(module, modname)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/builder.py\", line 91, in module_build\r\n node = self.inspect_build(module, modname=modname, path=path)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/raw_building.py\", line 311, in inspect_build\r\n self.object_build(node, module)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/raw_building.py\", line 367, in object_build\r\n self.object_build(module, member)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/astroid/raw_building.py\", line 325, in object_build\r\n member = getattr(obj, name)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/pandas/__init__.py\", line 198, in __getattr__\r\n warnings.warn(\r\nFutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File \"/opt/homebrew/lib/python3.9/site-packages/pylint/utils/ast_walker.py\", line 90, in walk\r\n callback(astroid)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/pylint/checkers/imports.py\", line 472, in visit_import\r\n imported_module = self._get_imported_module(node, name)\r\n File \"/opt/homebrew/lib/python3.9/site-packages/pylint/checkers/imports.py\", line 788, in _get_imported_module\r\n raise astroid.AstroidError from e\r\nastroid.exceptions.AstroidError\r\n************* Module test\r\ntest.py:1:0: F0002: test.py: Fatal error while checking 'test.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/Users/timkpaine/Library/Caches/pylint/pylint-crash-2022-07-19-17.txt'. (astroid-error)\r\n```\r\n\r\n\r\n\r\n\r\n### Standalone (Non Cython) repro for convenience\r\n\r\n```python\r\nimport types\r\nimport pandas as pd\r\nfrom astroid.builder import AstroidBuilder\r\n\r\n\r\nm = types.ModuleType(\"test\")\r\nm.pd = pd\r\n\r\nAstroidBuilder().module_build(m, \"test\")\r\n```\r\n\r\n\r\nxref: https://github.com/PyCQA/pylint/issues/7205\r\nxref: https://github.com/PyCQA/astroid/pull/1719\n", "hints_text": "", "created_at": "2022-07-19T21:09:19Z", "version": "2.13", "FAIL_TO_PASS": ["tests/unittest_raw_building.py::RawBuildingTC::test_build_function_deepinspect_deprecation"], "PASS_TO_PASS": ["tests/unittest_raw_building.py::RawBuildingTC::test_attach_dummy_node", "tests/unittest_raw_building.py::RawBuildingTC::test_build_class", "tests/unittest_raw_building.py::RawBuildingTC::test_build_from_import", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_args", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_defaults", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_kwonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_posonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_module", "tests/unittest_raw_building.py::RawBuildingTC::test_io_is__io"], "environment_setup_commit": "fe058bff95745371df5796286d33677c21137847"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1614", "base_commit": "aa5a0d92e640ee5f3fa9a8ba3ba058a7b594ca44", "patch": "diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py\n--- a/astroid/brain/brain_builtin_inference.py\n+++ b/astroid/brain/brain_builtin_inference.py\n@@ -946,7 +946,7 @@ def _infer_str_format_call(\n \n try:\n formatted_string = format_template.format(*pos_values, **keyword_values)\n- except IndexError:\n+ except (IndexError, KeyError):\n # If there is an IndexError there are too few arguments to interpolate\n return iter([util.Uninferable])\n \n", "test_patch": "diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py\n--- a/tests/unittest_brain_builtin.py\n+++ b/tests/unittest_brain_builtin.py\n@@ -93,6 +93,9 @@ def test_string_format(self, format_string: str) -> None:\n \"My name is {}, I'm {}\".format(Unknown, 12)\n \"\"\",\n \"\"\"\"I am {}\".format()\"\"\",\n+ \"\"\"\n+ \"My name is {fname}, I'm {age}\".format(fsname = \"Daniel\", age = 12)\n+ \"\"\",\n ],\n )\n def test_string_format_uninferable(self, format_string: str) -> None:\n", "problem_statement": "Crash when inferring `str.format` call involving unpacking kwargs\nWhen parsing the following file:\r\n\r\n<!--\r\n If sharing the code is not an option, please state so,\r\n but providing only the stacktrace would still be helpful.\r\n -->\r\n\r\n```python\r\nclass A:\r\n def render(self, audit_log_entry: AuditLogEntry):\r\n return \"joined team {team_slug}\".format(**audit_log_entry.data)\r\n\r\n\r\n\r\n```\r\n\r\npylint crashed with a ``AstroidError`` and with the following stacktrace:\r\n```\r\nTraceback (most recent call last):\r\n File \"/Users/.../astroid/astroid/inference_tip.py\", line 38, in _inference_tip_cached\r\n result = _cache[func, node]\r\nKeyError: (<function _infer_str_format_call at 0x1064a96c0>, <Call l.3 at 0x106c452d0>)\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/Users/.../pylint/pylint/lint/pylinter.py\", line 731, in _check_file\r\n check_astroid_module(ast_node)\r\n File \"/Users/.../pylint/pylint/lint/pylinter.py\", line 950, in check_astroid_module\r\n retval = self._check_astroid_module(\r\n File \"/Users/.../pylint/pylint/lint/pylinter.py\", line 1000, in _check_astroid_module\r\n walker.walk(node)\r\n File \"/Users/.../pylint/pylint/utils/ast_walker.py\", line 93, in walk\r\n self.walk(child)\r\n File \"/Users/.../pylint/pylint/utils/ast_walker.py\", line 93, in walk\r\n self.walk(child)\r\n File \"/Users/.../pylint/pylint/utils/ast_walker.py\", line 90, in walk\r\n callback(astroid)\r\n File \"/Users/.../pylint/pylint/checkers/classes/special_methods_checker.py\", line 170, in visit_functiondef\r\n inferred = _safe_infer_call_result(node, node)\r\n File \"/Users/.../pylint/pylint/checkers/classes/special_methods_checker.py\", line 31, in _safe_infer_call_result\r\n value = next(inferit)\r\n File \"/Users/.../astroid/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 1752, in infer_call_result\r\n yield from returnnode.value.infer(context)\r\n File \"/Users/.../astroid/astroid/nodes/node_ng.py\", line 159, in infer\r\n results = list(self._explicit_inference(self, context, **kwargs))\r\n File \"/Users/.../astroid/astroid/inference_tip.py\", line 45, in _inference_tip_cached\r\n result = _cache[func, node] = list(func(*args, **kwargs))\r\n File \"/Users/.../astroid/astroid/brain/brain_builtin_inference.py\", line 948, in _infer_str_format_call\r\n formatted_string = format_template.format(*pos_values, **keyword_values)\r\nKeyError: 'team_slug'\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File \"/Users/.../pylint/pylint/lint/pylinter.py\", line 688, in _check_files\r\n self._check_file(get_ast, check_astroid_module, file)\r\n File \"/Users/.../pylint/pylint/lint/pylinter.py\", line 733, in _check_file\r\n raise astroid.AstroidError from e\r\nastroid.exceptions.AstroidError\r\n```\r\n***\r\ncc @DanielNoord in #1602 \r\nfound by pylint primer \ud83d\ude80 \n", "hints_text": "Thanks! Going to add `KeyError` to the caught exceptions.", "created_at": "2022-06-11T10:33:20Z", "version": "2.12", "FAIL_TO_PASS": ["tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n"], "PASS_TO_PASS": ["tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs"], "environment_setup_commit": "52f6d2d7722db383af035be929f18af5e9fe8cd5"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-984", "base_commit": "d2394a3e24236106355418e102b1bb0f1bef879c", "patch": "diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py\n--- a/astroid/interpreter/_import/spec.py\n+++ b/astroid/interpreter/_import/spec.py\n@@ -292,15 +292,13 @@ def _precache_zipimporters(path=None):\n new_paths = _cached_set_diff(req_paths, cached_paths)\n for entry_path in new_paths:\n try:\n- pic[entry_path] = zipimport.zipimporter( # pylint: disable=no-member\n- entry_path\n- )\n- except zipimport.ZipImportError: # pylint: disable=no-member\n+ pic[entry_path] = zipimport.zipimporter(entry_path)\n+ except zipimport.ZipImportError:\n continue\n return {\n key: value\n for key, value in pic.items()\n- if isinstance(value, zipimport.zipimporter) # pylint: disable=no-member\n+ if isinstance(value, zipimport.zipimporter)\n }\n \n \ndiff --git a/astroid/manager.py b/astroid/manager.py\n--- a/astroid/manager.py\n+++ b/astroid/manager.py\n@@ -213,9 +213,7 @@ def zip_import_data(self, filepath):\n except ValueError:\n continue\n try:\n- importer = zipimport.zipimporter( # pylint: disable=no-member\n- eggpath + ext\n- )\n+ importer = zipimport.zipimporter(eggpath + ext)\n zmodname = resource.replace(os.path.sep, \".\")\n if importer.is_package(resource):\n zmodname = zmodname + \".__init__\"\ndiff --git a/astroid/modutils.py b/astroid/modutils.py\n--- a/astroid/modutils.py\n+++ b/astroid/modutils.py\n@@ -18,6 +18,7 @@\n # Copyright (c) 2020 hippo91 <[email protected]>\n # Copyright (c) 2020 Peter Kolbus <[email protected]>\n # Copyright (c) 2021 Pierre Sassoulas <[email protected]>\n+# Copyright (c) 2021 Andreas Finkler <[email protected]>\n \n # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n # For details: https://github.com/PyCQA/astroid/blob/master/LICENSE\n@@ -37,6 +38,8 @@\n # We disable the import-error so pylint can work without distutils installed.\n # pylint: disable=no-name-in-module,useless-suppression\n \n+import importlib\n+import importlib.machinery\n import importlib.util\n import itertools\n import os\n@@ -574,21 +577,11 @@ def is_relative(modname, from_file):\n from_file = os.path.dirname(from_file)\n if from_file in sys.path:\n return False\n- name = os.path.basename(from_file)\n- file_path = os.path.dirname(from_file)\n- parent_spec = importlib.util.find_spec(name, from_file)\n- while parent_spec is None and len(file_path) > 0:\n- name = os.path.basename(file_path) + \".\" + name\n- file_path = os.path.dirname(file_path)\n- parent_spec = importlib.util.find_spec(name, from_file)\n-\n- if parent_spec is None:\n- return False\n-\n- submodule_spec = importlib.util.find_spec(\n- name + \".\" + modname.split(\".\")[0], parent_spec.submodule_search_locations\n+ return bool(\n+ importlib.machinery.PathFinder.find_spec(\n+ modname.split(\".\", maxsplit=1)[0], [from_file]\n+ )\n )\n- return submodule_spec is not None\n \n \n # internal only functions #####################################################\n", "test_patch": "diff --git a/tests/unittest_modutils.py b/tests/unittest_modutils.py\n--- a/tests/unittest_modutils.py\n+++ b/tests/unittest_modutils.py\n@@ -301,6 +301,18 @@ def test_knownValues_is_relative_1(self):\n def test_knownValues_is_relative_3(self):\n self.assertFalse(modutils.is_relative(\"astroid\", astroid.__path__[0]))\n \n+ def test_knownValues_is_relative_4(self):\n+ self.assertTrue(\n+ modutils.is_relative(\"util\", astroid.interpreter._import.spec.__file__)\n+ )\n+\n+ def test_knownValues_is_relative_5(self):\n+ self.assertFalse(\n+ modutils.is_relative(\n+ \"objectmodel\", astroid.interpreter._import.spec.__file__\n+ )\n+ )\n+\n def test_deep_relative(self):\n self.assertTrue(modutils.is_relative(\"ElementTree\", xml.etree.__path__[0]))\n \n", "problem_statement": "Pyreverse regression after #857 (astroid 2.5)\n### Steps to reproduce\r\n1. Checkout pylint's source (which contains pyreverse)\r\n1. cd `<pylint checkout>` \r\n2. Run `source .tox/py39/bin/activate` or similar (you may need to run a tox session first)\r\n3. Ensure you have `astroid` ac2b173bc8acd2d08f6b6ffe29dd8cda0b2c8814 or later\r\n4. Ensure you have installed `astroid` (`python3 -m pip install -e <path-to-astroid>`) as dependencies may be different\r\n4. Run `pyreverse --output png --project test tests/data`\r\n\r\n### Current behaviour\r\nA `ModuleNotFoundError` exception is raised.\r\n\r\n```\r\n$ pyreverse --output png --project test tests/data\r\nparsing tests/data/__init__.py...\r\nparsing /opt/contrib/pylint/pylint/tests/data/suppliermodule_test.py...\r\nparsing /opt/contrib/pylint/pylint/tests/data/__init__.py...\r\nparsing /opt/contrib/pylint/pylint/tests/data/clientmodule_test.py...\r\nTraceback (most recent call last):\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/bin/pyreverse\", line 8, in <module>\r\n sys.exit(run_pyreverse())\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/__init__.py\", line 39, in run_pyreverse\r\n PyreverseRun(sys.argv[1:])\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/main.py\", line 201, in __init__\r\n sys.exit(self.run(args))\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/main.py\", line 219, in run\r\n diadefs = handler.get_diadefs(project, linker)\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/diadefslib.py\", line 236, in get_diadefs\r\n diagrams = DefaultDiadefGenerator(linker, self).visit(project)\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py\", line 210, in visit\r\n self.visit(local_node)\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py\", line 207, in visit\r\n methods[0](node)\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/diadefslib.py\", line 162, in visit_module\r\n self.linker.visit(node)\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py\", line 210, in visit\r\n self.visit(local_node)\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/utils.py\", line 207, in visit\r\n methods[0](node)\r\n File \"/opt/contrib/pylint/pylint/.tox/py39/lib/python3.9/site-packages/pylint/pyreverse/inspector.py\", line 257, in visit_importfrom\r\n relative = astroid.modutils.is_relative(basename, context_file)\r\n File \"/opt/contrib/pylint/astroid/astroid/modutils.py\", line 581, in is_relative\r\n parent_spec = importlib.util.find_spec(name, from_file)\r\n File \"/usr/local/Cellar/[email protected]/3.9.2_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/util.py\", line 94, in find_spec\r\n parent = __import__(parent_name, fromlist=['__path__'])\r\nModuleNotFoundError: No module named 'pylint.tests'\r\n```\r\n\r\n### Expected behaviour\r\nNo exception should be raised. Prior to #857 no exception was raised.\r\n\r\n```\r\n$ pyreverse --output png --project test tests/data\r\nparsing tests/data/__init__.py...\r\nparsing /opt/contributing/pylint/tests/data/suppliermodule_test.py...\r\nparsing /opt/contributing/pylint/tests/data/__init__.py...\r\nparsing /opt/contributing/pylint/tests/data/clientmodule_test.py...\r\n```\r\n\r\n### ``python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"`` output\r\n`2.6.0-dev0` (cab9b08737ed7aad2a08ce90718c67155fa5c4a0)\r\n\n", "hints_text": "Some notes:\r\n\r\n- The `ModuleNotFoundError` exception is thrown by `importlib.util.find_spec`. Before python 3.7 this was an `AttributeError`\r\n- `modutils.is_relative()` is the call-site for the `find_spec` call\r\n- It seems that `is_ralative()` is trying to find a parent mod-spec for the anchor `from_file` parameter so that it can check to see if the `modname` is contained by it\r\n- Neither `is_relative` nor its tests, explicitly handle on-disk paths (that is, paths for which `os.path.exists()` returns `True`) vs virtual-paths (`exists() == False`). The seems to be important to `find_spec` which raises if the package's `__path__` attribute isn't found (which it won't be for virtual paths).\r\n- The existing unit tests for `is_realtive()` use a range of modules to check against a set of module paths via `__path__[0]`. Somehow these pass and it is not clear why/how\r\n\r\nOne workaround fix, that feels like a hack until I understand the problem better, is for `is_relative()` to handle the `ModuleNotFoundError`/`AttributeError` exceptions and them as signifying that the `parent_spec` is being not-yet found. However, that requires that the loop-logic is fixed for linux-like systems, otherwise you end up in an infinite loop with `len(file_path)>0` always being true for `/` and `file_path = os.path.dirname('/')` always returning `/`.\r\n\r\nI have written some new unit tests for this issue and extended the existing ones, but there is some fundamental logic underpinning the use of `importlib.util.find_spec` that I am not smart enough to understand. For example, why do the existing unit-tests not all use the same `modname` parameter? Is it to work around the import caching in `sys.modules`? Should we take that into account?\r\n\r\nMy unit tests look at both virtual and ondisk paths (because of the `if not os.path.isdir(from_file):` line in `is_realtive()`, and the docs for `find_spec`). They also look at both absolute and relative paths explicitly. Finally, they also use system modules and assert that they are already in the import cache.\r\n\r\n.. and I thought this fix was going to be easy.\n@doublethefish thanks for your report and investigation.\r\nI can reproduce it and i confirm that #857 is the origin of the issue.\nIt seems like this happens if an import inside a package which is at least two levels deep is processed.\r\nFor example, trying to run ``pyreverse`` on ``pylint`` itself will crash as soon as the import statements in checker modules in ``pylint.checkers.refactoring`` are processed.\r\n``importlib.util.find_spec(name, from_file)`` is called with ``name`` = ``checkers.refactoring``. \r\n``find_spec`` will then split this up and try to import ``checkers``, which fails because the path to _inside_ the ``pylint`` package (i.e. ``pylint/pylint`` from the repo root) is normally not in the Pythonpath.", "created_at": "2021-05-01T16:13:04Z", "version": "2.5", "FAIL_TO_PASS": ["tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_4", "tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_5"], "PASS_TO_PASS": ["tests/unittest_modutils.py::ModuleFileTest::test_find_egg_module", "tests/unittest_modutils.py::ModuleFileTest::test_find_zipped_module", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_knownValues_load_module_from_name_1", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_knownValues_load_module_from_name_2", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_raise_load_module_from_name_1", "tests/unittest_modutils.py::GetModulePartTest::test_get_module_part_exception", "tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_builtin_module_part", "tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_compiled_module_part", "tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_module_part_1", "tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_module_part_2", "tests/unittest_modutils.py::GetModulePartTest::test_knownValues_get_module_part_3", "tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_both_outside_of_path", "tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_with_source_outside_of_path", "tests/unittest_modutils.py::ModPathFromFileTest::test_knownValues_modpath_from_file_1", "tests/unittest_modutils.py::ModPathFromFileTest::test_load_from_module_symlink_on_symlinked_paths_in_syspath", "tests/unittest_modutils.py::ModPathFromFileTest::test_raise_modpath_from_file_Exception", "tests/unittest_modutils.py::LoadModuleFromPathTest::test_do_not_load_twice", "tests/unittest_modutils.py::FileFromModPathTest::test_builtin", "tests/unittest_modutils.py::FileFromModPathTest::test_site_packages", "tests/unittest_modutils.py::FileFromModPathTest::test_std_lib", "tests/unittest_modutils.py::FileFromModPathTest::test_unexisting", "tests/unittest_modutils.py::FileFromModPathTest::test_unicode_in_package_init", "tests/unittest_modutils.py::GetSourceFileTest::test", "tests/unittest_modutils.py::GetSourceFileTest::test_raise", "tests/unittest_modutils.py::StandardLibModuleTest::test_4", "tests/unittest_modutils.py::StandardLibModuleTest::test_builtin", "tests/unittest_modutils.py::StandardLibModuleTest::test_builtins", "tests/unittest_modutils.py::StandardLibModuleTest::test_custom_path", "tests/unittest_modutils.py::StandardLibModuleTest::test_datetime", "tests/unittest_modutils.py::StandardLibModuleTest::test_failing_edge_cases", "tests/unittest_modutils.py::StandardLibModuleTest::test_nonstandard", "tests/unittest_modutils.py::StandardLibModuleTest::test_unknown", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative2", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative3", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative4", "tests/unittest_modutils.py::IsRelativeTest::test_is_relative_bad_path", "tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_1", "tests/unittest_modutils.py::IsRelativeTest::test_knownValues_is_relative_3", "tests/unittest_modutils.py::GetModuleFilesTest::test_get_all_files", "tests/unittest_modutils.py::GetModuleFilesTest::test_get_module_files_1", "tests/unittest_modutils.py::GetModuleFilesTest::test_load_module_set_attribute"], "environment_setup_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1164", "base_commit": "40ea1a3b8e52bbfed43deb1725cde461f4bd8a96", "patch": "diff --git a/astroid/nodes/__init__.py b/astroid/nodes/__init__.py\n--- a/astroid/nodes/__init__.py\n+++ b/astroid/nodes/__init__.py\n@@ -89,6 +89,7 @@\n Set,\n Slice,\n Starred,\n+ Statement,\n Subscript,\n TryExcept,\n TryFinally,\n@@ -116,6 +117,7 @@\n SetComp,\n builtin_lookup,\n function_to_method,\n+ get_wrapping_class,\n )\n \n _BaseContainer = BaseContainer # TODO Remove for astroid 3.0\n@@ -254,6 +256,7 @@\n \"FunctionDef\",\n \"function_to_method\",\n \"GeneratorExp\",\n+ \"get_wrapping_class\",\n \"Global\",\n \"If\",\n \"IfExp\",\n@@ -287,6 +290,7 @@\n \"SetComp\",\n \"Slice\",\n \"Starred\",\n+ \"Statement\",\n \"Subscript\",\n \"TryExcept\",\n \"TryFinally\",\n", "test_patch": "diff --git a/tests/unittest_brain_ctypes.py b/tests/unittest_brain_ctypes.py\n--- a/tests/unittest_brain_ctypes.py\n+++ b/tests/unittest_brain_ctypes.py\n@@ -2,8 +2,7 @@\n \n import pytest\n \n-from astroid import extract_node\n-from astroid.nodes.node_classes import Const\n+from astroid import extract_node, nodes\n \n pytestmark = pytest.mark.skipif(\n hasattr(sys, \"pypy_version_info\"),\n@@ -72,7 +71,7 @@ def test_ctypes_redefined_types_members(c_type, builtin_type, type_code):\n \"\"\"\n node = extract_node(src)\n node_inf = node.inferred()[0]\n- assert isinstance(node_inf, Const)\n+ assert isinstance(node_inf, nodes.Const)\n assert node_inf.value == type_code\n \n \n@@ -102,5 +101,5 @@ def test_other_ctypes_member_untouched():\n \"\"\"\n node = extract_node(src)\n node_inf = node.inferred()[0]\n- assert isinstance(node_inf, Const)\n+ assert isinstance(node_inf, nodes.Const)\n assert node_inf.value == 6\ndiff --git a/tests/unittest_lookup.py b/tests/unittest_lookup.py\n--- a/tests/unittest_lookup.py\n+++ b/tests/unittest_lookup.py\n@@ -24,7 +24,6 @@\n InferenceError,\n NameInferenceError,\n )\n-from astroid.nodes.scoped_nodes import builtin_lookup\n \n from . import resources\n \n@@ -389,8 +388,8 @@ def initialize(linter):\n self.assertEqual(len(path.lookup(\"__path__\")[1]), 1)\n \n def test_builtin_lookup(self):\n- self.assertEqual(builtin_lookup(\"__dict__\")[1], ())\n- intstmts = builtin_lookup(\"int\")[1]\n+ self.assertEqual(nodes.builtin_lookup(\"__dict__\")[1], ())\n+ intstmts = nodes.builtin_lookup(\"int\")[1]\n self.assertEqual(len(intstmts), 1)\n self.assertIsInstance(intstmts[0], nodes.ClassDef)\n self.assertEqual(intstmts[0].name, \"int\")\n@@ -411,7 +410,10 @@ class foo:\n def test(self):\n pass\n \"\"\"\n- member = builder.extract_node(code, __name__).targets[0]\n+\n+ node = builder.extract_node(code, __name__)\n+ assert isinstance(node, nodes.Assign)\n+ member = node.targets[0]\n it = member.infer()\n obj = next(it)\n self.assertIsInstance(obj, nodes.Const)\ndiff --git a/tests/unittest_protocols.py b/tests/unittest_protocols.py\n--- a/tests/unittest_protocols.py\n+++ b/tests/unittest_protocols.py\n@@ -22,7 +22,6 @@\n from astroid import extract_node, nodes, util\n from astroid.const import PY38_PLUS, PY310_PLUS\n from astroid.exceptions import InferenceError\n-from astroid.nodes.node_classes import AssignName, Const, Name, Starred\n \n \n @contextlib.contextmanager\n@@ -38,14 +37,14 @@ class ProtocolTests(unittest.TestCase):\n def assertConstNodesEqual(self, nodes_list_expected, nodes_list_got):\n self.assertEqual(len(nodes_list_expected), len(nodes_list_got))\n for node in nodes_list_got:\n- self.assertIsInstance(node, Const)\n+ self.assertIsInstance(node, nodes.Const)\n for node, expected_value in zip(nodes_list_got, nodes_list_expected):\n self.assertEqual(expected_value, node.value)\n \n def assertNameNodesEqual(self, nodes_list_expected, nodes_list_got):\n self.assertEqual(len(nodes_list_expected), len(nodes_list_got))\n for node in nodes_list_got:\n- self.assertIsInstance(node, Name)\n+ self.assertIsInstance(node, nodes.Name)\n for node, expected_name in zip(nodes_list_got, nodes_list_expected):\n self.assertEqual(expected_name, node.name)\n \n@@ -60,11 +59,11 @@ def test_assigned_stmts_simple_for(self):\n \"\"\"\n )\n \n- for1_assnode = next(assign_stmts[0].nodes_of_class(AssignName))\n+ for1_assnode = next(assign_stmts[0].nodes_of_class(nodes.AssignName))\n assigned = list(for1_assnode.assigned_stmts())\n self.assertConstNodesEqual([1, 2, 3], assigned)\n \n- for2_assnode = next(assign_stmts[1].nodes_of_class(AssignName))\n+ for2_assnode = next(assign_stmts[1].nodes_of_class(nodes.AssignName))\n self.assertRaises(InferenceError, list, for2_assnode.assigned_stmts())\n \n def test_assigned_stmts_starred_for(self):\n@@ -75,14 +74,14 @@ def test_assigned_stmts_starred_for(self):\n \"\"\"\n )\n \n- for1_starred = next(assign_stmts.nodes_of_class(Starred))\n+ for1_starred = next(assign_stmts.nodes_of_class(nodes.Starred))\n assigned = next(for1_starred.assigned_stmts())\n assert isinstance(assigned, astroid.List)\n assert assigned.as_string() == \"[1, 2]\"\n \n def _get_starred_stmts(self, code):\n assign_stmt = extract_node(f\"{code} #@\")\n- starred = next(assign_stmt.nodes_of_class(Starred))\n+ starred = next(assign_stmt.nodes_of_class(nodes.Starred))\n return next(starred.assigned_stmts())\n \n def _helper_starred_expected_const(self, code, expected):\n@@ -97,7 +96,7 @@ def _helper_starred_expected(self, code, expected):\n \n def _helper_starred_inference_error(self, code):\n assign_stmt = extract_node(f\"{code} #@\")\n- starred = next(assign_stmt.nodes_of_class(Starred))\n+ starred = next(assign_stmt.nodes_of_class(nodes.Starred))\n self.assertRaises(InferenceError, list, starred.assigned_stmts())\n \n def test_assigned_stmts_starred_assnames(self):\n@@ -143,11 +142,11 @@ def test_assigned_stmts_assignments(self):\n \"\"\"\n )\n \n- simple_assnode = next(assign_stmts[0].nodes_of_class(AssignName))\n+ simple_assnode = next(assign_stmts[0].nodes_of_class(nodes.AssignName))\n assigned = list(simple_assnode.assigned_stmts())\n self.assertNameNodesEqual([\"a\"], assigned)\n \n- assnames = assign_stmts[1].nodes_of_class(AssignName)\n+ assnames = assign_stmts[1].nodes_of_class(nodes.AssignName)\n simple_mul_assnode_1 = next(assnames)\n assigned = list(simple_mul_assnode_1.assigned_stmts())\n self.assertNameNodesEqual([\"b\"], assigned)\n@@ -162,13 +161,15 @@ def test_assigned_stmts_annassignments(self):\n b: str #@\n \"\"\"\n )\n- simple_annassign_node = next(annassign_stmts[0].nodes_of_class(AssignName))\n+ simple_annassign_node = next(\n+ annassign_stmts[0].nodes_of_class(nodes.AssignName)\n+ )\n assigned = list(simple_annassign_node.assigned_stmts())\n self.assertEqual(1, len(assigned))\n- self.assertIsInstance(assigned[0], Const)\n+ self.assertIsInstance(assigned[0], nodes.Const)\n self.assertEqual(assigned[0].value, \"abc\")\n \n- empty_annassign_node = next(annassign_stmts[1].nodes_of_class(AssignName))\n+ empty_annassign_node = next(annassign_stmts[1].nodes_of_class(nodes.AssignName))\n assigned = list(empty_annassign_node.assigned_stmts())\n self.assertEqual(1, len(assigned))\n self.assertIs(assigned[0], util.Uninferable)\ndiff --git a/tests/unittest_python3.py b/tests/unittest_python3.py\n--- a/tests/unittest_python3.py\n+++ b/tests/unittest_python3.py\n@@ -20,8 +20,6 @@\n \n from astroid import nodes\n from astroid.builder import AstroidBuilder, extract_node\n-from astroid.nodes.node_classes import Assign, Const, Expr, Name, YieldFrom\n-from astroid.nodes.scoped_nodes import ClassDef, FunctionDef\n from astroid.test_utils import require_version\n \n \n@@ -36,7 +34,7 @@ def test_starred_notation(self):\n # Get the star node\n node = next(next(next(astroid.get_children()).get_children()).get_children())\n \n- self.assertTrue(isinstance(node.assign_type(), Assign))\n+ self.assertTrue(isinstance(node.assign_type(), nodes.Assign))\n \n def test_yield_from(self):\n body = dedent(\n@@ -47,11 +45,11 @@ def func():\n )\n astroid = self.builder.string_build(body)\n func = astroid.body[0]\n- self.assertIsInstance(func, FunctionDef)\n+ self.assertIsInstance(func, nodes.FunctionDef)\n yieldfrom_stmt = func.body[0]\n \n- self.assertIsInstance(yieldfrom_stmt, Expr)\n- self.assertIsInstance(yieldfrom_stmt.value, YieldFrom)\n+ self.assertIsInstance(yieldfrom_stmt, nodes.Expr)\n+ self.assertIsInstance(yieldfrom_stmt.value, nodes.YieldFrom)\n self.assertEqual(yieldfrom_stmt.as_string(), \"yield from iter([1, 2])\")\n \n def test_yield_from_is_generator(self):\n@@ -63,7 +61,7 @@ def func():\n )\n astroid = self.builder.string_build(body)\n func = astroid.body[0]\n- self.assertIsInstance(func, FunctionDef)\n+ self.assertIsInstance(func, nodes.FunctionDef)\n self.assertTrue(func.is_generator())\n \n def test_yield_from_as_string(self):\n@@ -85,7 +83,7 @@ def test_simple_metaclass(self):\n klass = astroid.body[0]\n \n metaclass = klass.metaclass()\n- self.assertIsInstance(metaclass, ClassDef)\n+ self.assertIsInstance(metaclass, nodes.ClassDef)\n self.assertEqual(metaclass.name, \"type\")\n \n def test_metaclass_error(self):\n@@ -104,7 +102,7 @@ class Test(metaclass=ABCMeta): pass\"\"\"\n klass = astroid.body[1]\n \n metaclass = klass.metaclass()\n- self.assertIsInstance(metaclass, ClassDef)\n+ self.assertIsInstance(metaclass, nodes.ClassDef)\n self.assertEqual(metaclass.name, \"ABCMeta\")\n \n def test_metaclass_multiple_keywords(self):\n@@ -114,7 +112,7 @@ def test_metaclass_multiple_keywords(self):\n klass = astroid.body[0]\n \n metaclass = klass.metaclass()\n- self.assertIsInstance(metaclass, ClassDef)\n+ self.assertIsInstance(metaclass, nodes.ClassDef)\n self.assertEqual(metaclass.name, \"type\")\n \n def test_as_string(self):\n@@ -171,7 +169,7 @@ class SubTest(Test): pass\n klass = astroid[\"SubTest\"]\n self.assertTrue(klass.newstyle)\n metaclass = klass.metaclass()\n- self.assertIsInstance(metaclass, ClassDef)\n+ self.assertIsInstance(metaclass, nodes.ClassDef)\n self.assertEqual(metaclass.name, \"ABCMeta\")\n \n def test_metaclass_ancestors(self):\n@@ -199,7 +197,7 @@ class ThirdImpl(Simple, SecondMeta):\n for name in names:\n impl = astroid[name]\n meta = impl.metaclass()\n- self.assertIsInstance(meta, ClassDef)\n+ self.assertIsInstance(meta, nodes.ClassDef)\n self.assertEqual(meta.name, metaclass)\n \n def test_annotation_support(self):\n@@ -213,18 +211,18 @@ def test(a: int, b: str, c: None, d, e,\n )\n )\n func = astroid[\"test\"]\n- self.assertIsInstance(func.args.varargannotation, Name)\n+ self.assertIsInstance(func.args.varargannotation, nodes.Name)\n self.assertEqual(func.args.varargannotation.name, \"float\")\n- self.assertIsInstance(func.args.kwargannotation, Name)\n+ self.assertIsInstance(func.args.kwargannotation, nodes.Name)\n self.assertEqual(func.args.kwargannotation.name, \"int\")\n- self.assertIsInstance(func.returns, Name)\n+ self.assertIsInstance(func.returns, nodes.Name)\n self.assertEqual(func.returns.name, \"int\")\n arguments = func.args\n- self.assertIsInstance(arguments.annotations[0], Name)\n+ self.assertIsInstance(arguments.annotations[0], nodes.Name)\n self.assertEqual(arguments.annotations[0].name, \"int\")\n- self.assertIsInstance(arguments.annotations[1], Name)\n+ self.assertIsInstance(arguments.annotations[1], nodes.Name)\n self.assertEqual(arguments.annotations[1].name, \"str\")\n- self.assertIsInstance(arguments.annotations[2], Const)\n+ self.assertIsInstance(arguments.annotations[2], nodes.Const)\n self.assertIsNone(arguments.annotations[2].value)\n self.assertIsNone(arguments.annotations[3])\n self.assertIsNone(arguments.annotations[4])\n@@ -238,9 +236,9 @@ def test(a: int=1, b: str=2):\n )\n )\n func = astroid[\"test\"]\n- self.assertIsInstance(func.args.annotations[0], Name)\n+ self.assertIsInstance(func.args.annotations[0], nodes.Name)\n self.assertEqual(func.args.annotations[0].name, \"int\")\n- self.assertIsInstance(func.args.annotations[1], Name)\n+ self.assertIsInstance(func.args.annotations[1], nodes.Name)\n self.assertEqual(func.args.annotations[1].name, \"str\")\n self.assertIsNone(func.returns)\n \n@@ -255,11 +253,11 @@ def test(*, a: int, b: str, c: None, d, e):\n )\n func = node[\"test\"]\n arguments = func.args\n- self.assertIsInstance(arguments.kwonlyargs_annotations[0], Name)\n+ self.assertIsInstance(arguments.kwonlyargs_annotations[0], nodes.Name)\n self.assertEqual(arguments.kwonlyargs_annotations[0].name, \"int\")\n- self.assertIsInstance(arguments.kwonlyargs_annotations[1], Name)\n+ self.assertIsInstance(arguments.kwonlyargs_annotations[1], nodes.Name)\n self.assertEqual(arguments.kwonlyargs_annotations[1].name, \"str\")\n- self.assertIsInstance(arguments.kwonlyargs_annotations[2], Const)\n+ self.assertIsInstance(arguments.kwonlyargs_annotations[2], nodes.Const)\n self.assertIsNone(arguments.kwonlyargs_annotations[2].value)\n self.assertIsNone(arguments.kwonlyargs_annotations[3])\n self.assertIsNone(arguments.kwonlyargs_annotations[4])\n@@ -283,6 +281,7 @@ def test_unpacking_in_dicts(self):\n code = \"{'x': 1, **{'y': 2}}\"\n node = extract_node(code)\n self.assertEqual(node.as_string(), code)\n+ assert isinstance(node, nodes.Dict)\n keys = [key for (key, _) in node.items]\n self.assertIsInstance(keys[0], nodes.Const)\n self.assertIsInstance(keys[1], nodes.DictUnpack)\ndiff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py\n--- a/tests/unittest_scoped_nodes.py\n+++ b/tests/unittest_scoped_nodes.py\n@@ -53,7 +53,7 @@\n ResolveError,\n TooManyLevelsError,\n )\n-from astroid.nodes import scoped_nodes\n+from astroid.nodes.scoped_nodes import _is_metaclass\n \n from . import resources\n \n@@ -1120,7 +1120,7 @@ class BBB(AAA.JJJ):\n pass\n \"\"\"\n )\n- self.assertFalse(scoped_nodes._is_metaclass(klass))\n+ self.assertFalse(_is_metaclass(klass))\n ancestors = [base.name for base in klass.ancestors()]\n self.assertIn(\"object\", ancestors)\n self.assertIn(\"JJJ\", ancestors)\n@@ -1169,7 +1169,7 @@ class WithMeta(object, metaclass=abc.ABCMeta):\n )\n inferred = next(klass.infer())\n metaclass = inferred.metaclass()\n- self.assertIsInstance(metaclass, scoped_nodes.ClassDef)\n+ self.assertIsInstance(metaclass, nodes.ClassDef)\n self.assertIn(metaclass.qname(), (\"abc.ABCMeta\", \"_py_abc.ABCMeta\"))\n \n @unittest.skipUnless(HAS_SIX, \"These tests require the six library\")\n@@ -1667,7 +1667,7 @@ class A(object):\n pass\n \"\"\"\n )\n- type_cls = scoped_nodes.builtin_lookup(\"type\")[1][0]\n+ type_cls = nodes.builtin_lookup(\"type\")[1][0]\n self.assertEqual(cls.implicit_metaclass(), type_cls)\n \n def test_implicit_metaclass_lookup(self):\n@@ -1743,7 +1743,7 @@ class A(object, metaclass=Metaclass):\n # of the property\n property_meta = next(module[\"Metaclass\"].igetattr(\"meta_property\"))\n self.assertIsInstance(property_meta, objects.Property)\n- wrapping = scoped_nodes.get_wrapping_class(property_meta)\n+ wrapping = nodes.get_wrapping_class(property_meta)\n self.assertEqual(wrapping, module[\"Metaclass\"])\n \n property_class = next(acls.igetattr(\"meta_property\"))\n@@ -1751,7 +1751,7 @@ class A(object, metaclass=Metaclass):\n self.assertEqual(property_class.value, 42)\n \n static = next(acls.igetattr(\"static\"))\n- self.assertIsInstance(static, scoped_nodes.FunctionDef)\n+ self.assertIsInstance(static, nodes.FunctionDef)\n \n def test_local_attr_invalid_mro(self):\n cls = builder.extract_node(\n@@ -1820,14 +1820,14 @@ class Test(object): #@\n \"\"\"\n )\n cls = next(ast_nodes[0].infer())\n- self.assertIsInstance(next(cls.igetattr(\"lam\")), scoped_nodes.Lambda)\n- self.assertIsInstance(next(cls.igetattr(\"not_method\")), scoped_nodes.Lambda)\n+ self.assertIsInstance(next(cls.igetattr(\"lam\")), nodes.Lambda)\n+ self.assertIsInstance(next(cls.igetattr(\"not_method\")), nodes.Lambda)\n \n instance = next(ast_nodes[1].infer())\n lam = next(instance.igetattr(\"lam\"))\n self.assertIsInstance(lam, BoundMethod)\n not_method = next(instance.igetattr(\"not_method\"))\n- self.assertIsInstance(not_method, scoped_nodes.Lambda)\n+ self.assertIsInstance(not_method, nodes.Lambda)\n \n def test_instance_bound_method_lambdas_2(self):\n \"\"\"\n@@ -1846,7 +1846,7 @@ class MyClass(object): #@\n \"\"\"\n )\n cls = next(ast_nodes[0].infer())\n- self.assertIsInstance(next(cls.igetattr(\"f2\")), scoped_nodes.Lambda)\n+ self.assertIsInstance(next(cls.igetattr(\"f2\")), nodes.Lambda)\n \n instance = next(ast_nodes[1].infer())\n f2 = next(instance.igetattr(\"f2\"))\ndiff --git a/tests/unittest_utils.py b/tests/unittest_utils.py\n--- a/tests/unittest_utils.py\n+++ b/tests/unittest_utils.py\n@@ -13,10 +13,8 @@\n \n import unittest\n \n-from astroid import builder, nodes\n-from astroid import util as astroid_util\n+from astroid import Uninferable, builder, nodes\n from astroid.exceptions import InferenceError\n-from astroid.nodes import node_classes\n \n \n class InferenceUtil(unittest.TestCase):\n@@ -38,8 +36,8 @@ def test_not_exclusive(self):\n xnames = [n for n in module.nodes_of_class(nodes.Name) if n.name == \"x\"]\n assert len(xnames) == 3\n assert xnames[1].lineno == 6\n- self.assertEqual(node_classes.are_exclusive(xass1, xnames[1]), False)\n- self.assertEqual(node_classes.are_exclusive(xass1, xnames[2]), False)\n+ self.assertEqual(nodes.are_exclusive(xass1, xnames[1]), False)\n+ self.assertEqual(nodes.are_exclusive(xass1, xnames[2]), False)\n \n def test_if(self):\n module = builder.parse(\n@@ -61,12 +59,12 @@ def test_if(self):\n a4 = module.locals[\"a\"][3]\n a5 = module.locals[\"a\"][4]\n a6 = module.locals[\"a\"][5]\n- self.assertEqual(node_classes.are_exclusive(a1, a2), False)\n- self.assertEqual(node_classes.are_exclusive(a1, a3), True)\n- self.assertEqual(node_classes.are_exclusive(a1, a5), True)\n- self.assertEqual(node_classes.are_exclusive(a3, a5), True)\n- self.assertEqual(node_classes.are_exclusive(a3, a4), False)\n- self.assertEqual(node_classes.are_exclusive(a5, a6), False)\n+ self.assertEqual(nodes.are_exclusive(a1, a2), False)\n+ self.assertEqual(nodes.are_exclusive(a1, a3), True)\n+ self.assertEqual(nodes.are_exclusive(a1, a5), True)\n+ self.assertEqual(nodes.are_exclusive(a3, a5), True)\n+ self.assertEqual(nodes.are_exclusive(a3, a4), False)\n+ self.assertEqual(nodes.are_exclusive(a5, a6), False)\n \n def test_try_except(self):\n module = builder.parse(\n@@ -89,16 +87,16 @@ def exclusive_func2():\n f2 = module.locals[\"exclusive_func2\"][1]\n f3 = module.locals[\"exclusive_func2\"][2]\n f4 = module.locals[\"exclusive_func2\"][3]\n- self.assertEqual(node_classes.are_exclusive(f1, f2), True)\n- self.assertEqual(node_classes.are_exclusive(f1, f3), True)\n- self.assertEqual(node_classes.are_exclusive(f1, f4), False)\n- self.assertEqual(node_classes.are_exclusive(f2, f4), True)\n- self.assertEqual(node_classes.are_exclusive(f3, f4), True)\n- self.assertEqual(node_classes.are_exclusive(f3, f2), True)\n+ self.assertEqual(nodes.are_exclusive(f1, f2), True)\n+ self.assertEqual(nodes.are_exclusive(f1, f3), True)\n+ self.assertEqual(nodes.are_exclusive(f1, f4), False)\n+ self.assertEqual(nodes.are_exclusive(f2, f4), True)\n+ self.assertEqual(nodes.are_exclusive(f3, f4), True)\n+ self.assertEqual(nodes.are_exclusive(f3, f2), True)\n \n- self.assertEqual(node_classes.are_exclusive(f2, f1), True)\n- self.assertEqual(node_classes.are_exclusive(f4, f1), False)\n- self.assertEqual(node_classes.are_exclusive(f4, f2), True)\n+ self.assertEqual(nodes.are_exclusive(f2, f1), True)\n+ self.assertEqual(nodes.are_exclusive(f4, f1), False)\n+ self.assertEqual(nodes.are_exclusive(f4, f2), True)\n \n def test_unpack_infer_uninferable_nodes(self):\n node = builder.extract_node(\n@@ -109,9 +107,9 @@ def test_unpack_infer_uninferable_nodes(self):\n \"\"\"\n )\n inferred = next(node.infer())\n- unpacked = list(node_classes.unpack_infer(inferred))\n+ unpacked = list(nodes.unpack_infer(inferred))\n self.assertEqual(len(unpacked), 3)\n- self.assertTrue(all(elt is astroid_util.Uninferable for elt in unpacked))\n+ self.assertTrue(all(elt is Uninferable for elt in unpacked))\n \n def test_unpack_infer_empty_tuple(self):\n node = builder.extract_node(\n@@ -121,7 +119,7 @@ def test_unpack_infer_empty_tuple(self):\n )\n inferred = next(node.infer())\n with self.assertRaises(InferenceError):\n- list(node_classes.unpack_infer(inferred))\n+ list(nodes.unpack_infer(inferred))\n \n \n if __name__ == \"__main__\":\n", "problem_statement": "ImportError: cannot import name 'Statement' from 'astroid.node_classes' \n### Steps to reproduce\r\n\r\n1. run pylint <some_file>\r\n\r\n\r\n### Current behavior\r\n\r\n```python\r\nexception: Traceback (most recent call last):\r\n File \"/usr/lib/python3.9/runpy.py\", line 197, in _run_module_as_main\r\n return _run_code(code, main_globals, None,\r\n File \"/usr/lib/python3.9/runpy.py\", line 87, in _run_code\r\n exec(code, run_globals)\r\n File \"/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/__main__.py\", line 9, in <module>\r\n pylint.run_pylint()\r\n File \"/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/__init__.py\", line 24, in run_pylint\r\n PylintRun(sys.argv[1:])\r\n File \"/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/lint/run.py\", line 331, in __init__\r\n linter.load_plugin_modules(plugins)\r\n File \"/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/pylint/lint/pylinter.py\", line 551, in load_plugin_modules\r\n module = astroid.modutils.load_module_from_name(modname)\r\n File \"/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/astroid/modutils.py\", line 218, in load_module_from_name\r\n return importlib.import_module(dotted_name)\r\n File \"/usr/lib/python3.9/importlib/__init__.py\", line 127, in import_module\r\n return _bootstrap._gcd_import(name[level:], package, level)\r\n File \"<frozen importlib._bootstrap>\", line 1030, in _gcd_import\r\n File \"<frozen importlib._bootstrap>\", line 1007, in _find_and_load\r\n File \"<frozen importlib._bootstrap>\", line 986, in _find_and_load_unlocked\r\n File \"<frozen importlib._bootstrap>\", line 680, in _load_unlocked\r\n File \"<frozen importlib._bootstrap_external>\", line 855, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 228, in _call_with_frames_removed\r\n File \"/home/user/folder/check_mk/tests/testlib/pylint_checker_cmk_module_layers.py\", line 14, in <module>\r\n from astroid.node_classes import Import, ImportFrom, Statement # type: ignore[import]\r\nImportError: cannot import name 'Statement' from 'astroid.node_classes' (/home/user/folder/check_mk/.venv/lib/python3.9/site-packages/astroid/node_classes.py)\r\n```\r\n\r\n### Expected behavior\r\nNo exception\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n2.7.3\r\npylint 2.10.2\r\nastroid 2.7.3\r\nPython 3.9.5 (default, May 11 2021, 08:20:37) \n", "hints_text": "This is caused by our local plugin.\r\n\r\nHas probably nothing to do with upstream. \nThis is caused by a bad refactor from us, we deprecated `astroid.node_classes` and `astroid.scoped_nodes` in favor of `astroid.nodes` but nothing should break before astroid 3.0.\n@Pierre-Sassoulas I see.\r\nAlso Statement is not available in astroid.nodes it is in astroid.nodes.node_classes\r\n\r\nWas the Statement also deprecated? Or called something else now?\nIt seems we're not using it ourselves or not by using `astroid.nodes` API so we did not realize it was not importable easily. But it should, I'm going to add it.", "created_at": "2021-09-04T15:03:02Z", "version": "2.7", "FAIL_TO_PASS": ["tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup"], "PASS_TO_PASS": ["tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_bool-bool-?]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_byte-int-b]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_char-bytes-c]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_double-float-d]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_float-float-f]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int-int-i]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int16-int-h]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int32-int-i]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int64-int-l]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_int8-int-b]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_long-int-l]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_longdouble-float-g]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_longlong-int-l]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_short-int-h]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_size_t-int-L]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ssize_t-int-l]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ubyte-int-B]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint-int-I]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint16-int-H]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint32-int-I]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint64-int-L]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_uint8-int-B]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ulong-int-L]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ulonglong-int-L]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_ushort-int-H]", "tests/unittest_brain_ctypes.py::test_ctypes_redefined_types_members[c_wchar-str-u]", "tests/unittest_brain_ctypes.py::test_cdata_member_access", "tests/unittest_brain_ctypes.py::test_other_ctypes_member_untouched", "tests/unittest_lookup.py::LookupTest::test_builtin_lookup", "tests/unittest_lookup.py::LookupTest::test_class", "tests/unittest_lookup.py::LookupTest::test_class_ancestor_name", "tests/unittest_lookup.py::LookupTest::test_class_in_function", "tests/unittest_lookup.py::LookupTest::test_class_variables", "tests/unittest_lookup.py::LookupTest::test_decorator_arguments_lookup", "tests/unittest_lookup.py::LookupTest::test_dict_comp_nested", "tests/unittest_lookup.py::LookupTest::test_dict_comps", "tests/unittest_lookup.py::LookupTest::test_explicit___name__", "tests/unittest_lookup.py::LookupTest::test_function_argument_with_default", "tests/unittest_lookup.py::LookupTest::test_function_module_special", "tests/unittest_lookup.py::LookupTest::test_function_nested", "tests/unittest_lookup.py::LookupTest::test_generator_attributes", "tests/unittest_lookup.py::LookupTest::test_global_delete", "tests/unittest_lookup.py::LookupTest::test_inner_classes", "tests/unittest_lookup.py::LookupTest::test_inner_decorator_member_lookup", "tests/unittest_lookup.py::LookupTest::test_lambda_nested", "tests/unittest_lookup.py::LookupTest::test_limit", "tests/unittest_lookup.py::LookupTest::test_list_comp_nested", "tests/unittest_lookup.py::LookupTest::test_list_comp_target", "tests/unittest_lookup.py::LookupTest::test_list_comps", "tests/unittest_lookup.py::LookupTest::test_loopvar_hiding", "tests/unittest_lookup.py::LookupTest::test_method", "tests/unittest_lookup.py::LookupTest::test_module", "tests/unittest_lookup.py::LookupTest::test_set_comp_closure", "tests/unittest_lookup.py::LookupTest::test_set_comp_nested", "tests/unittest_lookup.py::LookupTest::test_set_comps", "tests/unittest_lookup.py::LookupTest::test_static_method_lookup", "tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_args_param", "tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_kwonly_param", "tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_param", "tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_posonly_param", "tests/unittest_lookup.py::LookupControlFlowTest::test_assign_after_use", "tests/unittest_lookup.py::LookupControlFlowTest::test_assign_exclusive", "tests/unittest_lookup.py::LookupControlFlowTest::test_assign_not_exclusive", "tests/unittest_lookup.py::LookupControlFlowTest::test_consecutive_assign", "tests/unittest_lookup.py::LookupControlFlowTest::test_del_exclusive", "tests/unittest_lookup.py::LookupControlFlowTest::test_del_no_effect_after", "tests/unittest_lookup.py::LookupControlFlowTest::test_del_not_exclusive", "tests/unittest_lookup.py::LookupControlFlowTest::test_del_removes_prior", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_after_block", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_after_block_overwritten", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_in_block", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_assign_in_block_multiple", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_after_block_multiple", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_after_block_single", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_in_block", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_in_block_overwrites", "tests/unittest_lookup.py::LookupControlFlowTest::test_except_var_in_multiple_blocks", "tests/unittest_lookup.py::LookupControlFlowTest::test_if_assign", "tests/unittest_lookup.py::LookupControlFlowTest::test_if_assigns_different_branch", "tests/unittest_lookup.py::LookupControlFlowTest::test_if_assigns_same_branch", "tests/unittest_lookup.py::LookupControlFlowTest::test_if_else", "tests/unittest_lookup.py::LookupControlFlowTest::test_if_variable_in_condition_1", "tests/unittest_lookup.py::LookupControlFlowTest::test_if_variable_in_condition_2", "tests/unittest_protocols.py::ProtocolTests::test_assign_stmts_starred_fails", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_annassignments", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_assignments", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_simple_for", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_assnames", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_for", "tests/unittest_protocols.py::ProtocolTests::test_assigned_stmts_starred_yes", "tests/unittest_protocols.py::ProtocolTests::test_not_passing_uninferable_in_seq_inference", "tests/unittest_protocols.py::ProtocolTests::test_sequence_assigned_stmts_not_accepting_empty_node", "tests/unittest_protocols.py::test_named_expr_inference", "tests/unittest_python3.py::Python3TC::test_annotation_as_string", "tests/unittest_python3.py::Python3TC::test_annotation_support", "tests/unittest_python3.py::Python3TC::test_as_string", "tests/unittest_python3.py::Python3TC::test_async_comprehensions", "tests/unittest_python3.py::Python3TC::test_async_comprehensions_as_string", "tests/unittest_python3.py::Python3TC::test_async_comprehensions_outside_coroutine", "tests/unittest_python3.py::Python3TC::test_format_string", "tests/unittest_python3.py::Python3TC::test_kwonlyargs_annotations_supper", "tests/unittest_python3.py::Python3TC::test_metaclass_ancestors", "tests/unittest_python3.py::Python3TC::test_metaclass_error", "tests/unittest_python3.py::Python3TC::test_metaclass_imported", "tests/unittest_python3.py::Python3TC::test_metaclass_multiple_keywords", "tests/unittest_python3.py::Python3TC::test_metaclass_yes_leak", "tests/unittest_python3.py::Python3TC::test_nested_unpacking_in_dicts", "tests/unittest_python3.py::Python3TC::test_old_syntax_works", "tests/unittest_python3.py::Python3TC::test_parent_metaclass", "tests/unittest_python3.py::Python3TC::test_simple_metaclass", "tests/unittest_python3.py::Python3TC::test_starred_notation", "tests/unittest_python3.py::Python3TC::test_underscores_in_numeral_literal", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dicts", "tests/unittest_python3.py::Python3TC::test_yield_from", "tests/unittest_python3.py::Python3TC::test_yield_from_as_string", "tests/unittest_python3.py::Python3TC::test_yield_from_is_generator", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_subclass_property", "tests/unittest_scoped_nodes.py::test_issue940_property_grandchild", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_property", "tests/unittest_scoped_nodes.py::test_issue940_with_metaclass_class_context_property", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_values_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_derived_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor", "tests/unittest_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase", "tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance", "tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef", "tests/unittest_scoped_nodes.py::test_posonlyargs_default_value", "tests/unittest_scoped_nodes.py::test_ancestor_with_generic", "tests/unittest_scoped_nodes.py::test_slots_duplicate_bases_issue_1089", "tests/unittest_utils.py::InferenceUtil::test_if", "tests/unittest_utils.py::InferenceUtil::test_not_exclusive", "tests/unittest_utils.py::InferenceUtil::test_try_except", "tests/unittest_utils.py::InferenceUtil::test_unpack_infer_empty_tuple", "tests/unittest_utils.py::InferenceUtil::test_unpack_infer_uninferable_nodes"], "environment_setup_commit": "40ea1a3b8e52bbfed43deb1725cde461f4bd8a96"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1030", "base_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843", "patch": "diff --git a/astroid/__pkginfo__.py b/astroid/__pkginfo__.py\n--- a/astroid/__pkginfo__.py\n+++ b/astroid/__pkginfo__.py\n@@ -24,13 +24,5 @@\n # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n # For details: https://github.com/PyCQA/astroid/blob/master/LICENSE\n \n-\"\"\"astroid packaging information\"\"\"\n-\n-from pkg_resources import DistributionNotFound, get_distribution\n-\n-try:\n- __version__ = get_distribution(\"astroid\").version\n-except DistributionNotFound:\n- __version__ = \"2.5.7+\"\n-\n+__version__ = \"2.6.0-dev0\"\n version = __version__\ndiff --git a/astroid/helpers.py b/astroid/helpers.py\n--- a/astroid/helpers.py\n+++ b/astroid/helpers.py\n@@ -5,8 +5,8 @@\n # Copyright (c) 2020 Simon Hewitt <[email protected]>\n # Copyright (c) 2020 Bryce Guinta <[email protected]>\n # Copyright (c) 2020 Ram Rachum <[email protected]>\n-# Copyright (c) 2021 Andrew Haigh <[email protected]>\n # Copyright (c) 2021 Pierre Sassoulas <[email protected]>\n+# Copyright (c) 2021 Andrew Haigh <[email protected]>\n \n # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n # For details: https://github.com/PyCQA/astroid/blob/master/LICENSE\ndiff --git a/astroid/node_classes.py b/astroid/node_classes.py\n--- a/astroid/node_classes.py\n+++ b/astroid/node_classes.py\n@@ -23,9 +23,9 @@\n # Copyright (c) 2019 kavins14 <[email protected]>\n # Copyright (c) 2020 Raphael Gaschignard <[email protected]>\n # Copyright (c) 2020 Bryce Guinta <[email protected]>\n-# Copyright (c) 2021 Andrew Haigh <[email protected]>\n-# Copyright (c) 2021 Marc Mueller <[email protected]>\n # Copyright (c) 2021 Pierre Sassoulas <[email protected]>\n+# Copyright (c) 2021 Marc Mueller <[email protected]>\n+# Copyright (c) 2021 Andrew Haigh <[email protected]>\n # Copyright (c) 2021 Federico Bond <[email protected]>\n \n # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\ndiff --git a/astroid/transforms.py b/astroid/transforms.py\n--- a/astroid/transforms.py\n+++ b/astroid/transforms.py\n@@ -1,8 +1,8 @@\n # Copyright (c) 2015-2016, 2018 Claudiu Popa <[email protected]>\n # Copyright (c) 2016 Ceridwen <[email protected]>\n # Copyright (c) 2018 Nick Drozd <[email protected]>\n-# Copyright (c) 2021 Andrew Haigh <[email protected]>\n # Copyright (c) 2021 Pierre Sassoulas <[email protected]>\n+# Copyright (c) 2021 Andrew Haigh <[email protected]>\n \n # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n # For details: https://github.com/PyCQA/astroid/blob/master/LICENSE\ndiff --git a/script/bump_changelog.py b/script/bump_changelog.py\nnew file mode 100644\n--- /dev/null\n+++ b/script/bump_changelog.py\n@@ -0,0 +1,77 @@\n+\"\"\"\n+This script permits to upgrade the changelog in astroid or pylint when releasing a version.\n+\"\"\"\n+import argparse\n+from datetime import datetime\n+from pathlib import Path\n+\n+DEFAULT_CHANGELOG_PATH = Path(\"ChangeLog\")\n+err = \"in the changelog, fix that first!\"\n+TBA_ERROR_MSG = \"More than one release date 'TBA' %s\" % err\n+NEW_VERSION_ERROR_MSG = \"The text for this version '{version}' did not exists %s\" % err\n+NEXT_VERSION_ERROR_MSG = (\n+ \"The text for the next version '{version}' already exists %s\" % err\n+)\n+\n+TODAY = datetime.now()\n+WHATS_NEW_TEXT = \"What's New in astroid\"\n+FULL_WHATS_NEW_TEXT = WHATS_NEW_TEXT + \" {version}?\"\n+RELEASE_DATE_TEXT = \"Release Date: TBA\"\n+NEW_RELEASE_DATE_MESSAGE = \"Release Date: {}\".format(TODAY.strftime(\"%Y-%m-%d\"))\n+\n+\n+def main() -> None:\n+ parser = argparse.ArgumentParser(add_help=__doc__)\n+ parser.add_argument(\"version\", help=\"The version we want to release\")\n+ args = parser.parse_args()\n+ if \"dev\" not in args.version:\n+ version = args.version\n+ next_version = get_next_version(version)\n+ run(version, next_version)\n+\n+\n+def get_next_version(version: str) -> str:\n+ new_version = version.split(\".\")\n+ patch = new_version[2]\n+ reminder = None\n+ if \"-\" in patch:\n+ patch, reminder = patch.split(\"-\")\n+ patch = str(int(patch) + 1)\n+ new_version[2] = patch if reminder is None else f\"{patch}-{reminder}\"\n+ return \".\".join(new_version)\n+\n+\n+def run(version: str, next_version: str) -> None:\n+ with open(DEFAULT_CHANGELOG_PATH) as f:\n+ content = f.read()\n+ content = transform_content(content, version, next_version)\n+ with open(DEFAULT_CHANGELOG_PATH, \"w\") as f:\n+ f.write(content)\n+\n+\n+def transform_content(content: str, version: str, next_version: str) -> str:\n+ wn_new_version = FULL_WHATS_NEW_TEXT.format(version=version)\n+ wn_next_version = FULL_WHATS_NEW_TEXT.format(version=next_version)\n+ # There is only one field where the release date is TBA\n+ assert content.count(RELEASE_DATE_TEXT) == 1, TBA_ERROR_MSG\n+ # There is already a release note for the version we want to release\n+ assert content.count(wn_new_version) == 1, NEW_VERSION_ERROR_MSG.format(\n+ version=version\n+ )\n+ # There is no release notes for the next version\n+ assert content.count(wn_next_version) == 0, NEXT_VERSION_ERROR_MSG.format(\n+ version=next_version\n+ )\n+ index = content.find(WHATS_NEW_TEXT)\n+ content = content.replace(RELEASE_DATE_TEXT, NEW_RELEASE_DATE_MESSAGE)\n+ end_content = content[index:]\n+ content = content[:index]\n+ content += wn_next_version + \"\\n\"\n+ content += \"=\" * len(wn_next_version) + \"\\n\"\n+ content += RELEASE_DATE_TEXT + \"\\n\" * 4\n+ content += end_content\n+ return content\n+\n+\n+if __name__ == \"__main__\":\n+ main()\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -1,3 +1,3 @@\n from setuptools import setup\n \n-setup(use_scm_version=True)\n+setup()\n", "test_patch": "diff --git a/requirements_test.txt b/requirements_test.txt\n--- a/requirements_test.txt\n+++ b/requirements_test.txt\n@@ -4,3 +4,4 @@ coveralls~=3.0\n coverage~=5.5\n pre-commit~=2.13\n pytest-cov~=2.11\n+tbump~=6.3.2\ndiff --git a/script/test_bump_changelog.py b/script/test_bump_changelog.py\nnew file mode 100644\n--- /dev/null\n+++ b/script/test_bump_changelog.py\n@@ -0,0 +1,83 @@\n+import pytest\n+from bump_changelog import get_next_version, transform_content\n+\n+\[email protected](\n+ \"version,expected\", [[\"2.6.1\", \"2.6.2\"], [\"2.6.1-dev0\", \"2.6.2-dev0\"]]\n+)\n+def test_get_next_version(version, expected):\n+ assert get_next_version(version) == expected\n+\n+\[email protected](\n+ \"old_content,expected_error\",\n+ [\n+ [\n+ \"\"\"\n+What's New in astroid 2.6.1?\n+============================\n+Release Date: TBA\n+\n+What's New in astroid 2.6.0?\n+============================\n+Release Date: TBA\n+\"\"\",\n+ \"More than one release date 'TBA'\",\n+ ],\n+ [\n+ \"\"\"===================\n+astroid's ChangeLog\n+===================\n+\n+What's New in astroid 2.6.0?\n+============================\n+Release Date: TBA\n+\"\"\",\n+ \"text for this version '2.6.1' did not exists\",\n+ ],\n+ [\n+ \"\"\"\n+What's New in astroid 2.6.2?\n+============================\n+Release Date: TBA\n+\n+What's New in astroid 2.6.1?\n+============================\n+Release Date: 2012-02-05\n+\"\"\",\n+ \"the next version '2.6.2' already exists\",\n+ ],\n+ ],\n+)\n+def test_update_content_error(old_content, expected_error):\n+ with pytest.raises(AssertionError, match=expected_error):\n+ transform_content(old_content, \"2.6.1\", \"2.6.2\")\n+\n+\n+def test_update_content():\n+ old_content = \"\"\"\n+===================\n+astroid's ChangeLog\n+===================\n+\n+What's New in astroid 2.6.1?\n+============================\n+Release Date: TBA\n+\"\"\"\n+ expected_beginning = \"\"\"\n+===================\n+astroid's ChangeLog\n+===================\n+\n+What's New in astroid 2.6.2?\n+============================\n+Release Date: TBA\n+\n+\n+\n+What's New in astroid 2.6.1?\n+============================\n+Release Date: 20\"\"\"\n+\n+ new_content = transform_content(old_content, \"2.6.1\", \"2.6.2\")\n+ assert new_content.startswith(expected_beginning)\ndiff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py\n--- a/tests/unittest_nodes.py\n+++ b/tests/unittest_nodes.py\n@@ -16,8 +16,8 @@\n # Copyright (c) 2019 Alex Hall <[email protected]>\n # Copyright (c) 2019 Hugo van Kemenade <[email protected]>\n # Copyright (c) 2020 David Gilman <[email protected]>\n-# Copyright (c) 2021 Marc Mueller <[email protected]>\n # Copyright (c) 2021 Pierre Sassoulas <[email protected]>\n+# Copyright (c) 2021 Marc Mueller <[email protected]>\n # Copyright (c) 2021 Federico Bond <[email protected]>\n # Copyright (c) 2021 hippo91 <[email protected]>\n \n", "problem_statement": "astroid has an undeclared dependency on setuptools.\nThe dependency is here: https://github.com/PyCQA/astroid/blob/1342591e2beb955a377e4486e5595478f79789e8/astroid/__pkginfo__.py#L29\n\nThe lack of declaration is here: https://github.com/PyCQA/astroid/blob/1342591e2beb955a377e4486e5595478f79789e8/setup.cfg#L37-L41\n", "hints_text": "Hmm, thank you for opening a report for this. There is the same problem in pylint btw. I thought `pkg_resources` was a builtin. Do you know a way to remove this dependency for python < 3.8 ? We can use ` from importlib.metadata import version` for python > 3.8. If there is no way to do that for 3.6 and 3.7 we could add a conditional requirements for those interpreters.\nYou can use https://pypi.org/project/importlib-metadata/ for 3.6 and 3.7 if I understand correctly.\nHo that's still a dependency to add but that's better, thank you for the advise, will do :) \nI'd send up an MR but this is all from my phone. On a road trip today and won't be back to a keyboard for a few days. Happy to review the fix though. Thanks for looking into this.\nI have a feeling that astroid do not need to calculate it's version like this so we could remove the dependency altogether. But pylint will need it because we broke a lot of pylint related tool when we removed the numversion in 2.8.0. Having to add a dependency for such a small benefit makes me rethink using ``setuptools_scm``. Having proper github actions would probably be better than that. There is such a release here: https://github.com/python/importlib_metadata/blob/main/.github/workflows/main.yml#L61. Maybe we just have to create a small script that will update the version in two places and be done with it. Thoughts @cdce8p ?\n> Maybe we just have to create a small script that will update the version in two places and be done with it.\r\n\r\nI believe there are already tools for it. `tbump` certainly looks promising although I haven't used it yet.\r\nhttps://github.com/dmerejkowsky/tbump", "created_at": "2021-06-15T11:04:30Z", "version": "2.5", "FAIL_TO_PASS": ["script/test_bump_changelog.py::test_get_next_version[2.6.1-2.6.2]", "script/test_bump_changelog.py::test_get_next_version[2.6.1-dev0-2.6.2-dev0]", "script/test_bump_changelog.py::test_update_content_error[\\nWhat's", "script/test_bump_changelog.py::test_update_content_error[===================\\nastroid's", "script/test_bump_changelog.py::test_update_content", "tests/unittest_nodes.py::AsStringTest::test_3k_annotations_and_metaclass", "tests/unittest_nodes.py::AsStringTest::test_3k_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable", "tests/unittest_nodes.py::AsStringTest::test_class_def", "tests/unittest_nodes.py::AsStringTest::test_ellipsis", "tests/unittest_nodes.py::AsStringTest::test_f_strings", "tests/unittest_nodes.py::AsStringTest::test_frozenset_as_string", "tests/unittest_nodes.py::AsStringTest::test_func_signature_issue_185", "tests/unittest_nodes.py::AsStringTest::test_int_attribute", "tests/unittest_nodes.py::AsStringTest::test_module2_as_string", "tests/unittest_nodes.py::AsStringTest::test_module_as_string", "tests/unittest_nodes.py::AsStringTest::test_operator_precedence", "tests/unittest_nodes.py::AsStringTest::test_slice_and_subscripts", "tests/unittest_nodes.py::AsStringTest::test_slices", "tests/unittest_nodes.py::AsStringTest::test_tuple_as_string", "tests/unittest_nodes.py::AsStringTest::test_varargs_kwargs_as_string", "tests/unittest_nodes.py::IfNodeTest::test_block_range", "tests/unittest_nodes.py::IfNodeTest::test_if_elif_else_node", "tests/unittest_nodes.py::TryExceptNodeTest::test_block_range", "tests/unittest_nodes.py::TryFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::TryExceptFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::ImportNodeTest::test_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_as_string", "tests/unittest_nodes.py::ImportNodeTest::test_bad_import_inference", "tests/unittest_nodes.py::ImportNodeTest::test_from_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_import_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_more_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_real_name", "tests/unittest_nodes.py::CmpNodeTest::test_as_string", "tests/unittest_nodes.py::ConstNodeTest::test_bool", "tests/unittest_nodes.py::ConstNodeTest::test_complex", "tests/unittest_nodes.py::ConstNodeTest::test_copy", "tests/unittest_nodes.py::ConstNodeTest::test_float", "tests/unittest_nodes.py::ConstNodeTest::test_int", "tests/unittest_nodes.py::ConstNodeTest::test_none", "tests/unittest_nodes.py::ConstNodeTest::test_str", "tests/unittest_nodes.py::ConstNodeTest::test_str_kind", "tests/unittest_nodes.py::ConstNodeTest::test_unicode", "tests/unittest_nodes.py::NameNodeTest::test_assign_to_True", "tests/unittest_nodes.py::AnnAssignNodeTest::test_as_string", "tests/unittest_nodes.py::AnnAssignNodeTest::test_complex", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value", "tests/unittest_nodes.py::ArgumentsNodeTC::test_kwoargs", "tests/unittest_nodes.py::ArgumentsNodeTC::test_positional_only", "tests/unittest_nodes.py::UnboundMethodNodeTest::test_no_super_getattr", "tests/unittest_nodes.py::BoundMethodNodeTest::test_is_property", "tests/unittest_nodes.py::AliasesTest::test_aliases", "tests/unittest_nodes.py::Python35AsyncTest::test_async_await_keywords", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncfor_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncwith_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_await_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string", "tests/unittest_nodes.py::ContextTest::test_list_del", "tests/unittest_nodes.py::ContextTest::test_list_load", "tests/unittest_nodes.py::ContextTest::test_list_store", "tests/unittest_nodes.py::ContextTest::test_starred_load", "tests/unittest_nodes.py::ContextTest::test_starred_store", "tests/unittest_nodes.py::ContextTest::test_subscript_del", "tests/unittest_nodes.py::ContextTest::test_subscript_load", "tests/unittest_nodes.py::ContextTest::test_subscript_store", "tests/unittest_nodes.py::ContextTest::test_tuple_load", "tests/unittest_nodes.py::ContextTest::test_tuple_store", "tests/unittest_nodes.py::test_unknown", "tests/unittest_nodes.py::test_type_comments_with", "tests/unittest_nodes.py::test_type_comments_for", "tests/unittest_nodes.py::test_type_coments_assign", "tests/unittest_nodes.py::test_type_comments_invalid_expression", "tests/unittest_nodes.py::test_type_comments_invalid_function_comments", "tests/unittest_nodes.py::test_type_comments_function", "tests/unittest_nodes.py::test_type_comments_arguments", "tests/unittest_nodes.py::test_type_comments_posonly_arguments", "tests/unittest_nodes.py::test_correct_function_type_comment_parent", "tests/unittest_nodes.py::test_is_generator_for_yield_assignments", "tests/unittest_nodes.py::test_f_string_correct_line_numbering", "tests/unittest_nodes.py::test_assignment_expression", "tests/unittest_nodes.py::test_get_doc", "tests/unittest_nodes.py::test_parse_fstring_debug_mode", "tests/unittest_nodes.py::test_parse_type_comments_with_proper_parent", "tests/unittest_nodes.py::test_const_itered", "tests/unittest_nodes.py::test_is_generator_for_yield_in_while", "tests/unittest_nodes.py::test_is_generator_for_yield_in_if", "tests/unittest_nodes.py::test_is_generator_for_yield_in_aug_assign"], "PASS_TO_PASS": [], "environment_setup_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1333", "base_commit": "d2a5b3c7b1e203fec3c7ca73c30eb1785d3d4d0a", "patch": "diff --git a/astroid/modutils.py b/astroid/modutils.py\n--- a/astroid/modutils.py\n+++ b/astroid/modutils.py\n@@ -297,6 +297,9 @@ def _get_relative_base_path(filename, path_to_check):\n if os.path.normcase(real_filename).startswith(path_to_check):\n importable_path = real_filename\n \n+ # if \"var\" in path_to_check:\n+ # breakpoint()\n+\n if importable_path:\n base_path = os.path.splitext(importable_path)[0]\n relative_base_path = base_path[len(path_to_check) :]\n@@ -307,8 +310,11 @@ def _get_relative_base_path(filename, path_to_check):\n \n def modpath_from_file_with_callback(filename, path=None, is_package_cb=None):\n filename = os.path.expanduser(_path_from_filename(filename))\n+ paths_to_check = sys.path.copy()\n+ if path:\n+ paths_to_check += path\n for pathname in itertools.chain(\n- path or [], map(_cache_normalize_path, sys.path), sys.path\n+ paths_to_check, map(_cache_normalize_path, paths_to_check)\n ):\n if not pathname:\n continue\n", "test_patch": "diff --git a/tests/unittest_modutils.py b/tests/unittest_modutils.py\n--- a/tests/unittest_modutils.py\n+++ b/tests/unittest_modutils.py\n@@ -30,6 +30,7 @@\n import tempfile\n import unittest\n import xml\n+from pathlib import Path\n from xml import etree\n from xml.etree import ElementTree\n \n@@ -189,6 +190,30 @@ def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self) -> None:\n # this should be equivalent to: import secret\n self.assertEqual(modutils.modpath_from_file(symlink_secret_path), [\"secret\"])\n \n+ def test_load_packages_without_init(self) -> None:\n+ \"\"\"Test that we correctly find packages with an __init__.py file.\n+\n+ Regression test for issue reported in:\n+ https://github.com/PyCQA/astroid/issues/1327\n+ \"\"\"\n+ tmp_dir = Path(tempfile.gettempdir())\n+ self.addCleanup(os.chdir, os.curdir)\n+ os.chdir(tmp_dir)\n+\n+ self.addCleanup(shutil.rmtree, tmp_dir / \"src\")\n+ os.mkdir(tmp_dir / \"src\")\n+ os.mkdir(tmp_dir / \"src\" / \"package\")\n+ with open(tmp_dir / \"src\" / \"__init__.py\", \"w\", encoding=\"utf-8\"):\n+ pass\n+ with open(tmp_dir / \"src\" / \"package\" / \"file.py\", \"w\", encoding=\"utf-8\"):\n+ pass\n+\n+ # this should be equivalent to: import secret\n+ self.assertEqual(\n+ modutils.modpath_from_file(str(Path(\"src\") / \"package\"), [\".\"]),\n+ [\"src\", \"package\"],\n+ )\n+\n \n class LoadModuleFromPathTest(resources.SysPathSetup, unittest.TestCase):\n def test_do_not_load_twice(self) -> None:\n", "problem_statement": "astroid 2.9.1 breaks pylint with missing __init__.py: F0010: error while code parsing: Unable to load file __init__.py\n### Steps to reproduce\r\n> Steps provided are for Windows 11, but initial problem found in Ubuntu 20.04\r\n\r\n> Update 2022-01-04: Corrected repro steps and added more environment details\r\n\r\n1. Set up simple repo with following structure (all files can be empty):\r\n```\r\nroot_dir/\r\n|--src/\r\n|----project/ # Notice the missing __init__.py\r\n|------file.py # It can be empty, but I added `import os` at the top\r\n|----__init__.py\r\n```\r\n2. Open a command prompt\r\n3. `cd root_dir`\r\n4. `python -m venv venv`\r\n5. `venv/Scripts/activate`\r\n6. `pip install pylint astroid==2.9.1` # I also repro'd on the latest, 2.9.2\r\n7. `pylint src/project` # Updated from `pylint src`\r\n8. Observe failure:\r\n```\r\nsrc\\project\\__init__.py:1:0: F0010: error while code parsing: Unable to load file src\\project\\__init__.py:\r\n```\r\n\r\n### Current behavior\r\nFails with `src\\project\\__init__.py:1:0: F0010: error while code parsing: Unable to load file src\\project\\__init__.py:`\r\n\r\n### Expected behavior\r\nDoes not fail with error.\r\n> If you replace step 6 with `pip install pylint astroid==2.9.0`, you get no failure with an empty output - since no files have content\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n2.9.1\r\n\r\n`python 3.9.1`\r\n`pylint 2.12.2 `\r\n\r\n\r\n\r\nThis issue has been observed with astroid `2.9.1` and `2.9.2`\n", "hints_text": "I can't seem to reproduce this in my `virtualenv`. This might be specific to `venv`? Needs some further investigation.\n@interifter Which version of `pylint` are you using?\nRight, ``pip install pylint astroid==2.9.0``, will keep the local version if you already have one, so I thought it was ``2.12.2`` but that could be false. In fact it probably isn't 2.12.2. For the record, you're not supposed to set the version of ``astroid`` yourself, pylint does, and bad thing will happen if you try to set the version of an incompatible astroid. We might want to update the issue's template to have this information next.\nMy apologies... I updated the repro steps with a critical missed detail: `pylint src/project`, instead of `pylint src`\r\n\r\nBut I verified that either with, or without, `venv`, the issue is reproduced.\r\n\r\nAlso, I never have specified the `astroid` version, before. \r\n\r\nHowever, this isn't the first time the issue has been observed.\r\nBack in early 2019, a [similar issue](https://stackoverflow.com/questions/48024049/pylint-raises-error-if-directory-doesnt-contain-init-py-file) was observed with either `astroid 2.2.0` or `isort 4.3.5`, which led me to try pinning `astroid==2.9.0`, which worked.\n> @interifter Which version of `pylint` are you using?\r\n\r\n`2.12.2`\r\n\r\nFull env info:\r\n\r\n```\r\nPackage Version\r\n----------------- -------\r\nastroid 2.9.2\r\ncolorama 0.4.4\r\nisort 5.10.1\r\nlazy-object-proxy 1.7.1\r\nmccabe 0.6.1\r\npip 20.2.3\r\nplatformdirs 2.4.1\r\npylint 2.12.2\r\nsetuptools 49.2.1\r\ntoml 0.10.2\r\ntyping-extensions 4.0.1\r\nwrapt 1.13.3\r\n```\r\n\nI confirm the bug and i'm able to reproduce it with `python 3.9.1`. \r\n```\r\n$> pip freeze\r\nastroid==2.9.2\r\nisort==5.10.1\r\nlazy-object-proxy==1.7.1\r\nmccabe==0.6.1\r\nplatformdirs==2.4.1\r\npylint==2.12.2\r\ntoml==0.10.2\r\ntyping-extensions==4.0.1\r\nwrapt==1.13.3\r\n```\nBisected and this is the faulty commit:\r\nhttps://github.com/PyCQA/astroid/commit/2ee20ccdf62450db611acc4a1a7e42f407ce8a14\nFix in #1333, no time to write tests yet so if somebody has any good ideas: please let me know!", "created_at": "2022-01-08T19:36:45Z", "version": "2.10", "FAIL_TO_PASS": ["tests/unittest_modutils.py::ModPathFromFileTest::test_load_packages_without_init"], "PASS_TO_PASS": ["tests/unittest_modutils.py::ModuleFileTest::test_find_egg_module", "tests/unittest_modutils.py::ModuleFileTest::test_find_zipped_module", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_known_values_load_module_from_name_1", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_known_values_load_module_from_name_2", "tests/unittest_modutils.py::LoadModuleFromNameTest::test_raise_load_module_from_name_1", "tests/unittest_modutils.py::GetModulePartTest::test_get_module_part_exception", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_builtin_module_part", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_compiled_module_part", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_1", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_2", "tests/unittest_modutils.py::GetModulePartTest::test_known_values_get_module_part_3", "tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_both_outside_of_path", "tests/unittest_modutils.py::ModPathFromFileTest::test_import_symlink_with_source_outside_of_path", "tests/unittest_modutils.py::ModPathFromFileTest::test_known_values_modpath_from_file_1", "tests/unittest_modutils.py::ModPathFromFileTest::test_load_from_module_symlink_on_symlinked_paths_in_syspath", "tests/unittest_modutils.py::ModPathFromFileTest::test_raise_modpath_from_file_exception", "tests/unittest_modutils.py::LoadModuleFromPathTest::test_do_not_load_twice", "tests/unittest_modutils.py::FileFromModPathTest::test_builtin", "tests/unittest_modutils.py::FileFromModPathTest::test_site_packages", "tests/unittest_modutils.py::FileFromModPathTest::test_std_lib", "tests/unittest_modutils.py::FileFromModPathTest::test_unexisting", "tests/unittest_modutils.py::FileFromModPathTest::test_unicode_in_package_init", "tests/unittest_modutils.py::GetSourceFileTest::test", "tests/unittest_modutils.py::GetSourceFileTest::test_raise", "tests/unittest_modutils.py::StandardLibModuleTest::test_4", "tests/unittest_modutils.py::StandardLibModuleTest::test_builtin", "tests/unittest_modutils.py::StandardLibModuleTest::test_builtins", "tests/unittest_modutils.py::StandardLibModuleTest::test_custom_path", "tests/unittest_modutils.py::StandardLibModuleTest::test_datetime", "tests/unittest_modutils.py::StandardLibModuleTest::test_failing_edge_cases", "tests/unittest_modutils.py::StandardLibModuleTest::test_nonstandard", "tests/unittest_modutils.py::StandardLibModuleTest::test_unknown", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative2", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative3", "tests/unittest_modutils.py::IsRelativeTest::test_deep_relative4", "tests/unittest_modutils.py::IsRelativeTest::test_is_relative_bad_path", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_1", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_3", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_4", "tests/unittest_modutils.py::IsRelativeTest::test_known_values_is_relative_5", "tests/unittest_modutils.py::GetModuleFilesTest::test_get_all_files", "tests/unittest_modutils.py::GetModuleFilesTest::test_get_module_files_1", "tests/unittest_modutils.py::GetModuleFilesTest::test_load_module_set_attribute", "tests/unittest_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_success", "tests/unittest_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_true"], "environment_setup_commit": "da745538c7236028a22cdf0405f6829fcf6886bc"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1903", "base_commit": "344454c8ee25d41a4ce12980bc85ba604b7835dd", "patch": "diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py\n--- a/astroid/brain/brain_builtin_inference.py\n+++ b/astroid/brain/brain_builtin_inference.py\n@@ -952,7 +952,8 @@ def _infer_str_format_call(\n \n try:\n formatted_string = format_template.format(*pos_values, **keyword_values)\n- except (IndexError, KeyError, TypeError, ValueError):\n+ except (AttributeError, IndexError, KeyError, TypeError, ValueError):\n+ # AttributeError: processing a replacement field using the arguments failed\n # IndexError: there are too few arguments to interpolate\n # TypeError: Unsupported format string\n # ValueError: Unknown format code\n", "test_patch": "diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py\n--- a/tests/unittest_brain_builtin.py\n+++ b/tests/unittest_brain_builtin.py\n@@ -109,6 +109,10 @@ def test_string_format(self, format_string: str) -> None:\n \"\"\"\n \"My hex format is {:4x}\".format('1')\n \"\"\",\n+ \"\"\"\n+ daniel_age = 12\n+ \"My name is {0.name}\".format(daniel_age)\n+ \"\"\",\n ],\n )\n def test_string_format_uninferable(self, format_string: str) -> None:\n", "problem_statement": "Unhandled AttributeError during str.format template evaluation\n### Steps to reproduce\r\n\r\n1. Use `astroid` to parse code that provides arguments to a `str.format` template that attempts to access non-existent attributes\r\n\r\n```py\r\ndaniel_age = 12\r\n\"My name is {0.name}\".format(daniel_age) # int literal has no 'name' attribute\r\n```\r\n\r\n### Current behavior\r\n\r\n1. unhandled `AttributeError` when it attempts to [evaluate the templated string](https://github.com/PyCQA/astroid/blob/8bdec591f228e7db6a0be66b6ca814227ff50001/astroid/brain/brain_builtin_inference.py#L956)\r\n\r\n### Expected behavior\r\n\r\n1. could raise an `AstroidTypeError` to indicate that the template formatting is invalid\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n`2.13.0-dev0`\r\n\r\nRelates to pycqa/pylint#7939.\nUnhandled AttributeError during str.format template evaluation\n### Steps to reproduce\r\n\r\n1. Use `astroid` to parse code that provides arguments to a `str.format` template that attempts to access non-existent attributes\r\n\r\n```py\r\ndaniel_age = 12\r\n\"My name is {0.name}\".format(daniel_age) # int literal has no 'name' attribute\r\n```\r\n\r\n### Current behavior\r\n\r\n1. unhandled `AttributeError` when it attempts to [evaluate the templated string](https://github.com/PyCQA/astroid/blob/8bdec591f228e7db6a0be66b6ca814227ff50001/astroid/brain/brain_builtin_inference.py#L956)\r\n\r\n### Expected behavior\r\n\r\n1. could raise an `AstroidTypeError` to indicate that the template formatting is invalid\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n`2.13.0-dev0`\r\n\r\nRelates to pycqa/pylint#7939.\n", "hints_text": "\n", "created_at": "2022-12-15T02:58:17Z", "version": "2.13", "FAIL_TO_PASS": ["tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n"], "PASS_TO_PASS": ["tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes-on-variable]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs"], "environment_setup_commit": "fe058bff95745371df5796286d33677c21137847"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1196", "base_commit": "39c2a9805970ca57093d32bbaf0e6a63e05041d8", "patch": "diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py\n--- a/astroid/nodes/node_classes.py\n+++ b/astroid/nodes/node_classes.py\n@@ -2346,24 +2346,33 @@ def itered(self):\n \"\"\"\n return [key for (key, _) in self.items]\n \n- def getitem(self, index, context=None):\n+ def getitem(\n+ self, index: Const | Slice, context: InferenceContext | None = None\n+ ) -> NodeNG:\n \"\"\"Get an item from this node.\n \n :param index: The node to use as a subscript index.\n- :type index: Const or Slice\n \n :raises AstroidTypeError: When the given index cannot be used as a\n subscript index, or if this node is not subscriptable.\n :raises AstroidIndexError: If the given index does not exist in the\n dictionary.\n \"\"\"\n+ # pylint: disable-next=import-outside-toplevel; circular import\n+ from astroid.helpers import safe_infer\n+\n for key, value in self.items:\n # TODO(cpopa): no support for overriding yet, {1:2, **{1: 3}}.\n if isinstance(key, DictUnpack):\n+ inferred_value = safe_infer(value, context)\n+ if not isinstance(inferred_value, Dict):\n+ continue\n+\n try:\n- return value.getitem(index, context)\n+ return inferred_value.getitem(index, context)\n except (AstroidTypeError, AstroidIndexError):\n continue\n+\n for inferredkey in key.infer(context):\n if inferredkey is util.Uninferable:\n continue\n", "test_patch": "diff --git a/tests/unittest_python3.py b/tests/unittest_python3.py\n--- a/tests/unittest_python3.py\n+++ b/tests/unittest_python3.py\n@@ -5,7 +5,9 @@\n import unittest\n from textwrap import dedent\n \n-from astroid import nodes\n+import pytest\n+\n+from astroid import exceptions, nodes\n from astroid.builder import AstroidBuilder, extract_node\n from astroid.test_utils import require_version\n \n@@ -285,6 +287,33 @@ def test_unpacking_in_dict_getitem(self) -> None:\n self.assertIsInstance(value, nodes.Const)\n self.assertEqual(value.value, expected)\n \n+ @staticmethod\n+ def test_unpacking_in_dict_getitem_with_ref() -> None:\n+ node = extract_node(\n+ \"\"\"\n+ a = {1: 2}\n+ {**a, 2: 3} #@\n+ \"\"\"\n+ )\n+ assert isinstance(node, nodes.Dict)\n+\n+ for key, expected in ((1, 2), (2, 3)):\n+ value = node.getitem(nodes.Const(key))\n+ assert isinstance(value, nodes.Const)\n+ assert value.value == expected\n+\n+ @staticmethod\n+ def test_unpacking_in_dict_getitem_uninferable() -> None:\n+ node = extract_node(\"{**a, 2: 3}\")\n+ assert isinstance(node, nodes.Dict)\n+\n+ with pytest.raises(exceptions.AstroidIndexError):\n+ node.getitem(nodes.Const(1))\n+\n+ value = node.getitem(nodes.Const(2))\n+ assert isinstance(value, nodes.Const)\n+ assert value.value == 3\n+\n def test_format_string(self) -> None:\n code = \"f'{greetings} {person}'\"\n node = extract_node(code)\n", "problem_statement": "getitem does not infer the actual unpacked value\nWhen trying to call `Dict.getitem()` on a context where we have a dict unpacking of anything beside a real dict, astroid currently raises an `AttributeError: 'getitem'`, which has 2 problems:\r\n\r\n- The object might be a reference against something constant, this pattern is usually seen when we have different sets of dicts that extend each other, and all of their values are inferrable. \r\n- We can have something that is uninferable, but in that case instead of an `AttributeError` I think it makes sense to raise the usual `AstroidIndexError` which is supposed to be already handled by the downstream.\r\n\r\n\r\nHere is a short reproducer;\r\n\r\n```py\r\nfrom astroid import parse\r\n\r\n\r\nsource = \"\"\"\r\nX = {\r\n 'A': 'B'\r\n}\r\n\r\nY = {\r\n **X\r\n}\r\n\r\nKEY = 'A'\r\n\"\"\"\r\n\r\ntree = parse(source)\r\n\r\nfirst_dict = tree.body[0].value\r\nsecond_dict = tree.body[1].value\r\nkey = tree.body[2].value\r\n\r\nprint(f'{first_dict.getitem(key).value = }')\r\nprint(f'{second_dict.getitem(key).value = }')\r\n\r\n\r\n```\r\n\r\nThe current output;\r\n\r\n```\r\n $ python t1.py 3ms\r\nfirst_dict.getitem(key).value = 'B'\r\nTraceback (most recent call last):\r\n File \"/home/isidentical/projects/astroid/t1.py\", line 23, in <module>\r\n print(f'{second_dict.getitem(key).value = }')\r\n File \"/home/isidentical/projects/astroid/astroid/nodes/node_classes.py\", line 2254, in getitem\r\n return value.getitem(index, context)\r\nAttributeError: 'Name' object has no attribute 'getitem'\r\n```\r\n\r\nExpeceted output;\r\n```\r\n $ python t1.py 4ms\r\nfirst_dict.getitem(key).value = 'B'\r\nsecond_dict.getitem(key).value = 'B'\r\n\r\n```\r\n\n", "hints_text": "", "created_at": "2021-10-03T15:58:07Z", "version": "2.12", "FAIL_TO_PASS": ["tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem_uninferable", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem_with_ref"], "PASS_TO_PASS": ["tests/unittest_python3.py::Python3TC::test_annotation_as_string", "tests/unittest_python3.py::Python3TC::test_annotation_support", "tests/unittest_python3.py::Python3TC::test_as_string", "tests/unittest_python3.py::Python3TC::test_async_comprehensions", "tests/unittest_python3.py::Python3TC::test_async_comprehensions_as_string", "tests/unittest_python3.py::Python3TC::test_async_comprehensions_outside_coroutine", "tests/unittest_python3.py::Python3TC::test_format_string", "tests/unittest_python3.py::Python3TC::test_kwonlyargs_annotations_supper", "tests/unittest_python3.py::Python3TC::test_metaclass_ancestors", "tests/unittest_python3.py::Python3TC::test_metaclass_error", "tests/unittest_python3.py::Python3TC::test_metaclass_imported", "tests/unittest_python3.py::Python3TC::test_metaclass_multiple_keywords", "tests/unittest_python3.py::Python3TC::test_metaclass_yes_leak", "tests/unittest_python3.py::Python3TC::test_nested_unpacking_in_dicts", "tests/unittest_python3.py::Python3TC::test_old_syntax_works", "tests/unittest_python3.py::Python3TC::test_parent_metaclass", "tests/unittest_python3.py::Python3TC::test_simple_metaclass", "tests/unittest_python3.py::Python3TC::test_starred_notation", "tests/unittest_python3.py::Python3TC::test_underscores_in_numeral_literal", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dict_getitem", "tests/unittest_python3.py::Python3TC::test_unpacking_in_dicts", "tests/unittest_python3.py::Python3TC::test_yield_from", "tests/unittest_python3.py::Python3TC::test_yield_from_as_string", "tests/unittest_python3.py::Python3TC::test_yield_from_is_generator"], "environment_setup_commit": "52f6d2d7722db383af035be929f18af5e9fe8cd5"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-2307", "base_commit": "1113d490ec4a94cdc1b35f45abfdaca9f19fa31e", "patch": "diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py\n--- a/astroid/brain/brain_typing.py\n+++ b/astroid/brain/brain_typing.py\n@@ -17,6 +17,7 @@\n from astroid.builder import AstroidBuilder, _extract_single_node\n from astroid.const import PY39_PLUS, PY312_PLUS\n from astroid.exceptions import (\n+ AstroidSyntaxError,\n AttributeInferenceError,\n InferenceError,\n UseInferenceDefault,\n@@ -136,14 +137,10 @@ def infer_typing_typevar_or_newtype(\n raise UseInferenceDefault\n \n typename = node.args[0].as_string().strip(\"'\")\n- node = ClassDef(\n- name=typename,\n- lineno=node.lineno,\n- col_offset=node.col_offset,\n- parent=node.parent,\n- end_lineno=node.end_lineno,\n- end_col_offset=node.end_col_offset,\n- )\n+ try:\n+ node = extract_node(TYPING_TYPE_TEMPLATE.format(typename))\n+ except AstroidSyntaxError as exc:\n+ raise InferenceError from exc\n return node.infer(context=context_itton)\n \n \n", "test_patch": "diff --git a/tests/brain/test_typing.py b/tests/brain/test_typing.py\n--- a/tests/brain/test_typing.py\n+++ b/tests/brain/test_typing.py\n@@ -2,7 +2,10 @@\n # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE\n # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt\n \n-from astroid import builder, nodes\n+import pytest\n+\n+from astroid import builder\n+from astroid.exceptions import InferenceError\n \n \n def test_infer_typevar() -> None:\n@@ -12,13 +15,11 @@ def test_infer_typevar() -> None:\n Test that an inferred `typing.TypeVar()` call produces a `nodes.ClassDef`\n node.\n \"\"\"\n- assign_node = builder.extract_node(\n+ call_node = builder.extract_node(\n \"\"\"\n from typing import TypeVar\n- MyType = TypeVar('My.Type')\n+ TypeVar('My.Type')\n \"\"\"\n )\n- call = assign_node.value\n- inferred = next(call.infer())\n- assert isinstance(inferred, nodes.ClassDef)\n- assert inferred.name == \"My.Type\"\n+ with pytest.raises(InferenceError):\n+ call_node.inferred()\n", "problem_statement": "Regression in Astroid version 2.15.7 in handling subscriptable type parameters\nAstroid version 2.15.7 fails to correctly handle a subscriptable type parameter most likely due to the change in this [PR](https://github.com/pylint-dev/astroid/pull/2239). \r\n\r\n### Steps to reproduce\r\n\r\n```python\r\nfrom collections.abc import Mapping\r\nfrom typing import Generic, TypeVar, TypedDict\r\nfrom dataclasses import dataclass\r\n\r\nclass Identity(TypedDict):\r\n \"\"\"It's the identity.\"\"\"\r\n\r\n name: str\r\n\r\nT = TypeVar(\"T\", bound=Mapping)\r\n\r\n@dataclass\r\nclass Animal(Generic[T]):\r\n \"\"\"It's an animal.\"\"\"\r\n\r\n identity: T\r\n\r\nclass Dog(Animal[Identity]):\r\n \"\"\"It's a Dog.\"\"\"\r\n\r\ndog = Dog(identity=Identity(name=\"Dog\"))\r\nprint(dog.identity[\"name\"])\r\n```\r\n\r\n### Current behavior\r\nPylint (running Astroid 2.15.7) gives the following error for the example above:\r\n```\r\nE1136: Value 'dog.identity' is unsubscriptable (unsubscriptable-object)\r\n```\r\n### Expected behavior\r\nAstroid should correctly handle a subscriptable type parameter.\r\n\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n2.15.7\n", "hints_text": "Thanks for the report.\n@mbyrnepr2 Would you be willing to take a look?", "created_at": "2023-09-25T18:41:07Z", "version": "3.0", "FAIL_TO_PASS": ["tests/brain/test_typing.py::test_infer_typevar"], "PASS_TO_PASS": [], "environment_setup_commit": "1113d490ec4a94cdc1b35f45abfdaca9f19fa31e"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-927", "base_commit": "cd8b6a43192724128af68605ef22aabf3254f495", "patch": "diff --git a/astroid/context.py b/astroid/context.py\n--- a/astroid/context.py\n+++ b/astroid/context.py\n@@ -102,7 +102,7 @@ def clone(self):\n starts with the same context but diverge as each side is inferred\n so the InferenceContext will need be cloned\"\"\"\n # XXX copy lookupname/callcontext ?\n- clone = InferenceContext(self.path, inferred=self.inferred)\n+ clone = InferenceContext(self.path.copy(), inferred=self.inferred.copy())\n clone.callcontext = self.callcontext\n clone.boundnode = self.boundnode\n clone.extra_context = self.extra_context\n", "test_patch": "diff --git a/tests/unittest_brain_numpy_core_umath.py b/tests/unittest_brain_numpy_core_umath.py\n--- a/tests/unittest_brain_numpy_core_umath.py\n+++ b/tests/unittest_brain_numpy_core_umath.py\n@@ -14,7 +14,7 @@\n except ImportError:\n HAS_NUMPY = False\n \n-from astroid import bases, builder, nodes, util\n+from astroid import bases, builder, nodes\n \n \n @unittest.skipUnless(HAS_NUMPY, \"This test requires the numpy library.\")\n@@ -220,9 +220,7 @@ def test_numpy_core_umath_functions_return_type(self):\n with self.subTest(typ=func_):\n inferred_values = list(self._inferred_numpy_func_call(func_))\n self.assertTrue(\n- len(inferred_values) == 1\n- or len(inferred_values) == 2\n- and inferred_values[-1].pytype() is util.Uninferable,\n+ len(inferred_values) == 1,\n msg=\"Too much inferred values ({}) for {:s}\".format(\n inferred_values[-1].pytype(), func_\n ),\ndiff --git a/tests/unittest_inference.py b/tests/unittest_inference.py\n--- a/tests/unittest_inference.py\n+++ b/tests/unittest_inference.py\n@@ -1704,7 +1704,8 @@ def __init__(self):\n \"\"\"\n ast = extract_node(code, __name__)\n expr = ast.func.expr\n- self.assertIs(next(expr.infer()), util.Uninferable)\n+ with pytest.raises(exceptions.InferenceError):\n+ next(expr.infer())\n \n def test_tuple_builtin_inference(self):\n code = \"\"\"\n@@ -6032,5 +6033,37 @@ def test_infer_list_of_uninferables_does_not_crash():\n assert not inferred.elts\n \n \n+# https://github.com/PyCQA/astroid/issues/926\n+def test_issue926_infer_stmts_referencing_same_name_is_not_uninferable():\n+ code = \"\"\"\n+ pair = [1, 2]\n+ ex = pair[0]\n+ if 1 + 1 == 2:\n+ ex = pair[1]\n+ ex\n+ \"\"\"\n+ node = extract_node(code)\n+ inferred = list(node.infer())\n+ assert len(inferred) == 2\n+ assert isinstance(inferred[0], nodes.Const)\n+ assert inferred[0].value == 1\n+ assert isinstance(inferred[1], nodes.Const)\n+ assert inferred[1].value == 2\n+\n+\n+# https://github.com/PyCQA/astroid/issues/926\n+def test_issue926_binop_referencing_same_name_is_not_uninferable():\n+ code = \"\"\"\n+ pair = [1, 2]\n+ ex = pair[0] + pair[1]\n+ ex\n+ \"\"\"\n+ node = extract_node(code)\n+ inferred = list(node.infer())\n+ assert len(inferred) == 1\n+ assert isinstance(inferred[0], nodes.Const)\n+ assert inferred[0].value == 3\n+\n+\n if __name__ == \"__main__\":\n unittest.main()\ndiff --git a/tests/unittest_regrtest.py b/tests/unittest_regrtest.py\n--- a/tests/unittest_regrtest.py\n+++ b/tests/unittest_regrtest.py\n@@ -99,7 +99,7 @@ def test_numpy_crash(self):\n astroid = builder.string_build(data, __name__, __file__)\n callfunc = astroid.body[1].value.func\n inferred = callfunc.inferred()\n- self.assertEqual(len(inferred), 2)\n+ self.assertEqual(len(inferred), 1)\n \n def test_nameconstant(self):\n # used to fail for Python 3.4\n", "problem_statement": "infer_stmts cannot infer multiple uses of the same AssignName\nGiven multiple assignments to the same target which both reference the same AssignName, infer_stmts fails for subsequent attempts after the first.\r\n\r\n### Steps to reproduce\r\n\r\nThis appears to be a minimum working example, removing any part removes the effect:\r\n\r\n```python\r\nfails = astroid.extract_node(\"\"\"\r\n pair = [1, 2]\r\n ex = pair[0]\r\n if 1 + 1 == 2:\r\n ex = pair[1]\r\n ex\r\n\"\"\")\r\nprint(list(fails.infer()))\r\n# [<Const.int l.2 at 0x...>, Uninferable]\r\n```\r\n\r\nFor some context, I originally saw this with attributes on an imported module, i.e.\r\n\r\n```python\r\nimport mod\r\nex = mod.One()\r\n# later ... or in some branch\r\nex = mod.Two()\r\n```\r\n\r\n### Current behavior\r\n\r\nSee above.\r\n\r\n### Expected behavior\r\n\r\nInlining the variable or switching to a different name works fine:\r\n\r\n```python\r\nworks = astroid.extract_node(\"\"\"\r\n # pair = [1, 2]\r\n ex = [1, 2][0]\r\n if 1 + 1 == 2:\r\n ex = [1, 2][1]\r\n ex\r\n\"\"\")\r\nprint(list(works.infer()))\r\n# [<Const.int l.3 at 0x...>, <Const.int l.5 at 0x...>]\r\n\r\nworks = astroid.extract_node(\"\"\"\r\n first = [1, 2]\r\n second = [1, 2]\r\n ex = first[0]\r\n if 1 + 1 == 2:\r\n ex = second[1]\r\n ex\r\n\"\"\")\r\nprint(list(works.infer()))\r\n# [<Const.int l.2 at 0x...>, <Const.int l.3 at 0x...>]\r\n```\r\n\r\nI would expect that the first failing example would work similarly. This (only) worked\r\nin astroid 2.5 and appears to have been \"broken\" by the revert of cc3bfc5 in 03d15b0 (astroid 2.5.1 and above).\r\n\r\n### ``python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"`` output\r\n\r\n```\r\n$ python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"\r\n2.5-dev\r\n$ git rev-parse HEAD\r\n03d15b0f32f7d7c9b2cb062b9321e531bd954344\r\n```\r\n\n", "hints_text": "It appears that this is caused by `InferenceContext` maintaining a strong reference to the mutable set that is shared between clones, see this simplified example:\r\n\r\n```python\r\nclass Context:\r\n def __init__(self, path=None):\r\n self.path = path or set()\r\n def clone(self):\r\n return Context(path=self.path)\r\n\r\na = Context()\r\na.path.add('hello')\r\nb = a.clone()\r\nb.path.add('world')\r\nprint(a.path, b.path)\r\n# (set(['world', 'hello']), set(['world', 'hello']))\r\nprint(a.path is b.path)\r\n# True\r\n```", "created_at": "2021-03-29T12:55:48Z", "version": "2.5", "FAIL_TO_PASS": ["tests/unittest_inference.py::InferenceTest::test_stop_iteration_leak", "tests/unittest_inference.py::test_issue926_infer_stmts_referencing_same_name_is_not_uninferable", "tests/unittest_inference.py::test_issue926_binop_referencing_same_name_is_not_uninferable"], "PASS_TO_PASS": ["tests/unittest_inference.py::InferenceUtilsTest::test_path_wrapper", "tests/unittest_inference.py::InferenceTest::test__new__", "tests/unittest_inference.py::InferenceTest::test__new__bound_methods", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference1", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference2", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference2", "tests/unittest_inference.py::InferenceTest::test_args_default_inference1", "tests/unittest_inference.py::InferenceTest::test_args_default_inference2", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented_rop_fallback", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_not_implemented_normal_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_aug_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_normal_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_augassign", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_none_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_normal_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_not_implemented_returned_for_all", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_reflected_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_bin_op_classes", "tests/unittest_inference.py::InferenceTest::test_bin_op_supertype_more_complicated_example", "tests/unittest_inference.py::InferenceTest::test_binary_op_custom_class", "tests/unittest_inference.py::InferenceTest::test_binary_op_float_div", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitand", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitxor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftleft", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftright", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_sub", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_int", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_none", "tests/unittest_inference.py::InferenceTest::test_binary_op_on_self", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type_using_reflected_operands", "tests/unittest_inference.py::InferenceTest::test_binary_op_reflected_and_not_implemented_is_type_error", "tests/unittest_inference.py::InferenceTest::test_binary_op_str_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_tuple_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_type_errors", "tests/unittest_inference.py::InferenceTest::test_binop_ambiguity", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_normal_not_implemented_and_reflected", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_and_normal_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_only", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_unknown_bases", "tests/unittest_inference.py::InferenceTest::test_binop_inference_errors", "tests/unittest_inference.py::InferenceTest::test_binop_list_with_elts", "tests/unittest_inference.py::InferenceTest::test_binop_same_types", "tests/unittest_inference.py::InferenceTest::test_binop_subtype", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_implemented_in_parent", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_rop_not_implemented", "tests/unittest_inference.py::InferenceTest::test_bool_value", "tests/unittest_inference.py::InferenceTest::test_bool_value_instances", "tests/unittest_inference.py::InferenceTest::test_bool_value_recursive", "tests/unittest_inference.py::InferenceTest::test_bool_value_variable", "tests/unittest_inference.py::InferenceTest::test_bound_method_inference", "tests/unittest_inference.py::InferenceTest::test_bt_ancestor_crash", "tests/unittest_inference.py::InferenceTest::test_builtin_help", "tests/unittest_inference.py::InferenceTest::test_builtin_inference_py3k", "tests/unittest_inference.py::InferenceTest::test_builtin_name_inference", "tests/unittest_inference.py::InferenceTest::test_builtin_open", "tests/unittest_inference.py::InferenceTest::test_builtin_types", "tests/unittest_inference.py::InferenceTest::test_bytes_subscript", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_func", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_lambda", "tests/unittest_inference.py::InferenceTest::test_callfunc_inference", "tests/unittest_inference.py::InferenceTest::test_class_inference", "tests/unittest_inference.py::InferenceTest::test_classmethod_inferred_by_context", "tests/unittest_inference.py::InferenceTest::test_context_call_for_context_managers", "tests/unittest_inference.py::InferenceTest::test_conversion_of_dict_methods", "tests/unittest_inference.py::InferenceTest::test_del1", "tests/unittest_inference.py::InferenceTest::test_del2", "tests/unittest_inference.py::InferenceTest::test_delayed_attributes_without_slots", "tests/unittest_inference.py::InferenceTest::test_dict_inference", "tests/unittest_inference.py::InferenceTest::test_dict_inference_for_multiple_starred", "tests/unittest_inference.py::InferenceTest::test_dict_inference_kwargs", "tests/unittest_inference.py::InferenceTest::test_dict_inference_unpack_repeated_key", "tests/unittest_inference.py::InferenceTest::test_dict_invalid_args", "tests/unittest_inference.py::InferenceTest::test_exc_ancestors", "tests/unittest_inference.py::InferenceTest::test_except_inference", "tests/unittest_inference.py::InferenceTest::test_f_arg_f", "tests/unittest_inference.py::InferenceTest::test_factory_method", "tests/unittest_inference.py::InferenceTest::test_factory_methods_cls_call", "tests/unittest_inference.py::InferenceTest::test_factory_methods_object_new_call", "tests/unittest_inference.py::InferenceTest::test_float_complex_ambiguity", "tests/unittest_inference.py::InferenceTest::test_frozenset_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_function_inference", "tests/unittest_inference.py::InferenceTest::test_genexpr_bool_value", "tests/unittest_inference.py::InferenceTest::test_getattr_inference1", "tests/unittest_inference.py::InferenceTest::test_getattr_inference2", "tests/unittest_inference.py::InferenceTest::test_getattr_inference3", "tests/unittest_inference.py::InferenceTest::test_getattr_inference4", "tests/unittest_inference.py::InferenceTest::test_getitem_of_class_raised_type_error", "tests/unittest_inference.py::InferenceTest::test_im_func_unwrap", "tests/unittest_inference.py::InferenceTest::test_import_as", "tests/unittest_inference.py::InferenceTest::test_infer_abstract_property_return_values", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_object_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_defined_in_outer_scope_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_subscript_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arguments", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_crash", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_invalid_dunder_call_on_instance", "tests/unittest_inference.py::InferenceTest::test_infer_cls_in_class_methods", "tests/unittest_inference.py::InferenceTest::test_infer_coercion_rules_for_floats_complex", "tests/unittest_inference.py::InferenceTest::test_infer_empty_nodes", "tests/unittest_inference.py::InferenceTest::test_infer_nested", "tests/unittest_inference.py::InferenceTest::test_infer_variable_arguments", "tests/unittest_inference.py::InferenceTest::test_inference_restrictions", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_skip_index_error", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_unpacking_inference_error", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager_failures", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement_failures", "tests/unittest_inference.py::InferenceTest::test_infinite_loop_for_decorators", "tests/unittest_inference.py::InferenceTest::test_inner_value_redefined_by_subclass", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_multiple_methods", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_parent", "tests/unittest_inference.py::InferenceTest::test_instance_slicing", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_fails", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_slices", "tests/unittest_inference.py::InferenceTest::test_invalid_slicing_primaries", "tests/unittest_inference.py::InferenceTest::test_invalid_subscripts", "tests/unittest_inference.py::InferenceTest::test_lambda_as_methods", "tests/unittest_inference.py::InferenceTest::test_list_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_list_inference", "tests/unittest_inference.py::InferenceTest::test_listassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_lookup_cond_branches", "tests/unittest_inference.py::InferenceTest::test_matmul", "tests/unittest_inference.py::InferenceTest::test_metaclass__getitem__", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call_boundnode", "tests/unittest_inference.py::InferenceTest::test_metaclass_subclasses_arguments_are_classes_not_instances", "tests/unittest_inference.py::InferenceTest::test_metaclass_with_keyword_args", "tests/unittest_inference.py::InferenceTest::test_method_argument", "tests/unittest_inference.py::InferenceTest::test_module_inference", "tests/unittest_inference.py::InferenceTest::test_mul_list_supports__index__", "tests/unittest_inference.py::InferenceTest::test_mulassign_inference", "tests/unittest_inference.py::InferenceTest::test_name_bool_value", "tests/unittest_inference.py::InferenceTest::test_no_infinite_ancestor_loop", "tests/unittest_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference", "tests/unittest_inference.py::InferenceTest::test_nonregr_absolute_import", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_arg", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_global", "tests/unittest_inference.py::InferenceTest::test_nonregr_getitem_empty_tuple", "tests/unittest_inference.py::InferenceTest::test_nonregr_inference_modifying_col_offset", "tests/unittest_inference.py::InferenceTest::test_nonregr_instance_attrs", "tests/unittest_inference.py::InferenceTest::test_nonregr_lambda_arg", "tests/unittest_inference.py::InferenceTest::test_pluggable_inference", "tests/unittest_inference.py::InferenceTest::test_property", "tests/unittest_inference.py::InferenceTest::test_python25_no_relative_import", "tests/unittest_inference.py::InferenceTest::test_scope_lookup_same_attributes", "tests/unittest_inference.py::InferenceTest::test_set_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_simple_for", "tests/unittest_inference.py::InferenceTest::test_simple_for_genexpr", "tests/unittest_inference.py::InferenceTest::test_simple_subscript", "tests/unittest_inference.py::InferenceTest::test_simple_tuple", "tests/unittest_inference.py::InferenceTest::test_slicing_list", "tests/unittest_inference.py::InferenceTest::test_slicing_str", "tests/unittest_inference.py::InferenceTest::test_slicing_tuple", "tests/unittest_inference.py::InferenceTest::test_special_method_masquerading_as_another", "tests/unittest_inference.py::InferenceTest::test_starred_in_list_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_literals_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_no_inference_possible", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_non_const_keys_values", "tests/unittest_inference.py::InferenceTest::test_starred_in_set_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_tuple_literal", "tests/unittest_inference.py::InferenceTest::test_str_methods", "tests/unittest_inference.py::InferenceTest::test_subscript_inference_error", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_slice", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_value", "tests/unittest_inference.py::InferenceTest::test_subscript_supports__index__", "tests/unittest_inference.py::InferenceTest::test_swap_assign_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_then_list", "tests/unittest_inference.py::InferenceTest::test_tupleassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_two_parents_from_same_module", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_attrs", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_bases", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_mcs_argument", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_name", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_and_ancestors_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__not_enough_arguments", "tests/unittest_inference.py::InferenceTest::test_type__new__with_metaclass", "tests/unittest_inference.py::InferenceTest::test_unary_empty_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_not", "tests/unittest_inference.py::InferenceTest::test_unary_op_assignment", "tests/unittest_inference.py::InferenceTest::test_unary_op_classes", "tests/unittest_inference.py::InferenceTest::test_unary_op_instance_method_not_callable", "tests/unittest_inference.py::InferenceTest::test_unary_op_leaks_stop_iteration", "tests/unittest_inference.py::InferenceTest::test_unary_op_numbers", "tests/unittest_inference.py::InferenceTest::test_unary_operands", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors_for_non_instance_objects", "tests/unittest_inference.py::InferenceTest::test_unbound_method_inference", "tests/unittest_inference.py::InferenceTest::test_unicode_methods", "tests/unittest_inference.py::GetattrTest::test_attribute_missing", "tests/unittest_inference.py::GetattrTest::test_attrname_not_string", "tests/unittest_inference.py::GetattrTest::test_default", "tests/unittest_inference.py::GetattrTest::test_lambda", "tests/unittest_inference.py::GetattrTest::test_lookup", "tests/unittest_inference.py::GetattrTest::test_yes_when_unknown", "tests/unittest_inference.py::HasattrTest::test_attribute_is_missing", "tests/unittest_inference.py::HasattrTest::test_attribute_is_not_missing", "tests/unittest_inference.py::HasattrTest::test_inference_errors", "tests/unittest_inference.py::HasattrTest::test_lambda", "tests/unittest_inference.py::BoolOpTest::test_bool_ops", "tests/unittest_inference.py::BoolOpTest::test_other_nodes", "tests/unittest_inference.py::BoolOpTest::test_yes_when_unknown", "tests/unittest_inference.py::TestCallable::test_callable", "tests/unittest_inference.py::TestCallable::test_callable_methods", "tests/unittest_inference.py::TestCallable::test_inference_errors", "tests/unittest_inference.py::TestCallable::test_not_callable", "tests/unittest_inference.py::TestBool::test_bool", "tests/unittest_inference.py::TestBool::test_bool_bool_special_method", "tests/unittest_inference.py::TestBool::test_bool_instance_not_callable", "tests/unittest_inference.py::TestType::test_type", "tests/unittest_inference.py::ArgumentsTest::test_args", "tests/unittest_inference.py::ArgumentsTest::test_defaults", "tests/unittest_inference.py::ArgumentsTest::test_fail_to_infer_args", "tests/unittest_inference.py::ArgumentsTest::test_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_access_by_name", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_and_other_named_parameters", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_are_overridden", "tests/unittest_inference.py::ArgumentsTest::test_kwonly_args", "tests/unittest_inference.py::ArgumentsTest::test_multiple_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_multiple_starred_args", "tests/unittest_inference.py::SliceTest::test_slice", "tests/unittest_inference.py::SliceTest::test_slice_attributes", "tests/unittest_inference.py::SliceTest::test_slice_inference_error", "tests/unittest_inference.py::SliceTest::test_slice_type", "tests/unittest_inference.py::CallSiteTest::test_call_site", "tests/unittest_inference.py::CallSiteTest::test_call_site_starred_args", "tests/unittest_inference.py::CallSiteTest::test_call_site_valid_arguments", "tests/unittest_inference.py::CallSiteTest::test_duplicated_keyword_arguments", "tests/unittest_inference.py::ObjectDunderNewTest::test_object_dunder_new_is_inferred_if_decorator", "tests/unittest_inference.py::test_infer_custom_inherit_from_property", "tests/unittest_inference.py::test_cannot_infer_call_result_for_builtin_methods", "tests/unittest_inference.py::test_unpack_dicts_in_assignment", "tests/unittest_inference.py::test_slice_inference_in_for_loops", "tests/unittest_inference.py::test_slice_inference_in_for_loops_not_working", "tests/unittest_inference.py::test_unpacking_starred_and_dicts_in_assignment", "tests/unittest_inference.py::test_unpacking_starred_empty_list_in_assignment", "tests/unittest_inference.py::test_regression_infinite_loop_decorator", "tests/unittest_inference.py::test_stop_iteration_in_int", "tests/unittest_inference.py::test_call_on_instance_with_inherited_dunder_call_method", "tests/unittest_inference.py::TestInferencePropagation::test_call_starargs_propagation", "tests/unittest_inference.py::TestInferencePropagation::test_call_kwargs_propagation", "tests/unittest_inference.py::test_limit_inference_result_amount", "tests/unittest_inference.py::test_attribute_inference_should_not_access_base_classes", "tests/unittest_inference.py::test_attribute_mro_object_inference", "tests/unittest_inference.py::test_inferred_sequence_unpacking_works", "tests/unittest_inference.py::test_recursion_error_inferring_slice", "tests/unittest_inference.py::test_exception_lookup_last_except_handler_wins", "tests/unittest_inference.py::test_exception_lookup_name_bound_in_except_handler", "tests/unittest_inference.py::test_builtin_inference_list_of_exceptions", "tests/unittest_inference.py::test_cannot_getattr_ann_assigns", "tests/unittest_inference.py::test_prevent_recursion_error_in_igetattr_and_context_manager_inference", "tests/unittest_inference.py::test_infer_context_manager_with_unknown_args", "tests/unittest_inference.py::test_subclass_of_exception[\\n", "tests/unittest_inference.py::test_ifexp_inference", "tests/unittest_inference.py::test_assert_last_function_returns_none_on_inference", "tests/unittest_inference.py::test_posonlyargs_inference", "tests/unittest_inference.py::test_infer_args_unpacking_of_self", "tests/unittest_inference.py::test_infer_exception_instance_attributes", "tests/unittest_inference.py::test_inference_is_limited_to_the_boundnode[\\n", "tests/unittest_inference.py::test_property_inference", "tests/unittest_inference.py::test_property_as_string", "tests/unittest_inference.py::test_property_callable_inference", "tests/unittest_inference.py::test_recursion_error_inferring_builtin_containers", "tests/unittest_inference.py::test_inferaugassign_picking_parent_instead_of_stmt", "tests/unittest_inference.py::test_classmethod_from_builtins_inferred_as_bound", "tests/unittest_inference.py::test_infer_dict_passes_context", "tests/unittest_inference.py::test_custom_decorators_for_classmethod_and_staticmethods[\\n", "tests/unittest_inference.py::test_dataclasses_subscript_inference_recursion_error_39", "tests/unittest_inference.py::test_self_reference_infer_does_not_trigger_recursion_error", "tests/unittest_inference.py::test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_times", "tests/unittest_inference.py::test_getattr_fails_on_empty_values", "tests/unittest_inference.py::test_infer_first_argument_of_static_method_in_metaclass", "tests/unittest_inference.py::test_recursion_error_metaclass_monkeypatching", "tests/unittest_inference.py::test_allow_retrieving_instance_attrs_and_special_attrs_for_functions", "tests/unittest_inference.py::test_implicit_parameters_bound_method", "tests/unittest_inference.py::test_super_inference_of_abstract_property", "tests/unittest_inference.py::test_infer_generated_setter", "tests/unittest_inference.py::test_infer_list_of_uninferables_does_not_crash", "tests/unittest_regrtest.py::NonRegressionTests::test_ancestors_missing_from_function", "tests/unittest_regrtest.py::NonRegressionTests::test_ancestors_patching_class_recursion", "tests/unittest_regrtest.py::NonRegressionTests::test_ancestors_yes_in_bases", "tests/unittest_regrtest.py::NonRegressionTests::test_binop_generates_nodes_with_parents", "tests/unittest_regrtest.py::NonRegressionTests::test_decorator_callchain_issue42", "tests/unittest_regrtest.py::NonRegressionTests::test_decorator_names_inference_error_leaking", "tests/unittest_regrtest.py::NonRegressionTests::test_filter_stmts_scoping", "tests/unittest_regrtest.py::NonRegressionTests::test_living_property", "tests/unittest_regrtest.py::NonRegressionTests::test_module_path", "tests/unittest_regrtest.py::NonRegressionTests::test_nameconstant", "tests/unittest_regrtest.py::NonRegressionTests::test_package_sidepackage", "tests/unittest_regrtest.py::NonRegressionTests::test_recursion_regression_issue25", "tests/unittest_regrtest.py::NonRegressionTests::test_recursive_property_method", "tests/unittest_regrtest.py::NonRegressionTests::test_regression_inference_of_self_in_lambda", "tests/unittest_regrtest.py::NonRegressionTests::test_ssl_protocol", "tests/unittest_regrtest.py::NonRegressionTests::test_unicode_in_docstring", "tests/unittest_regrtest.py::NonRegressionTests::test_uninferable_string_argument_of_namedtuple", "tests/unittest_regrtest.py::test_ancestor_looking_up_redefined_function", "tests/unittest_regrtest.py::test_crash_in_dunder_inference_prevented"], "environment_setup_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1866", "base_commit": "6cf238d089cf4b6753c94cfc089b4a47487711e5", "patch": "diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py\n--- a/astroid/brain/brain_builtin_inference.py\n+++ b/astroid/brain/brain_builtin_inference.py\n@@ -954,8 +954,10 @@ def _infer_str_format_call(\n \n try:\n formatted_string = format_template.format(*pos_values, **keyword_values)\n- except (IndexError, KeyError):\n- # If there is an IndexError there are too few arguments to interpolate\n+ except (IndexError, KeyError, TypeError, ValueError):\n+ # IndexError: there are too few arguments to interpolate\n+ # TypeError: Unsupported format string\n+ # ValueError: Unknown format code\n return iter([util.Uninferable])\n \n return iter([nodes.const_factory(formatted_string)])\n", "test_patch": "diff --git a/tests/unittest_brain_builtin.py b/tests/unittest_brain_builtin.py\n--- a/tests/unittest_brain_builtin.py\n+++ b/tests/unittest_brain_builtin.py\n@@ -103,6 +103,12 @@ def test_string_format(self, format_string: str) -> None:\n \"\"\"\n \"My name is {fname}, I'm {age}\".format(fsname = \"Daniel\", age = 12)\n \"\"\",\n+ \"\"\"\n+ \"My unicode character is {:c}\".format(None)\n+ \"\"\",\n+ \"\"\"\n+ \"My hex format is {:4x}\".format('1')\n+ \"\"\",\n ],\n )\n def test_string_format_uninferable(self, format_string: str) -> None:\n", "problem_statement": "\"TypeError: unsupported format string passed to NoneType.__format__\" while running type inference in version 2.12.x\n### Steps to reproduce\r\n\r\nI have no concise reproducer. Exception happens every time I run pylint on some internal code, with astroid 2.12.10 and 2.12.12 (debian bookworm). It does _not_ happen with earlier versions of astroid (not with version 2.9). The pylinted code itself is \"valid\", it runs in production here.\r\n\r\n### Current behavior\r\n\r\nWhen running pylint on some code, I get this exception:\r\n```\r\nTraceback (most recent call last):\r\n File \"/usr/lib/python3/dist-packages/pylint/utils/ast_walker.py\", line 90, in walk\r\n callback(astroid)\r\n File \"/usr/lib/python3/dist-packages/pylint/checkers/classes/special_methods_checker.py\", line 183, in visit_functiondef\r\n inferred = _safe_infer_call_result(node, node)\r\n File \"/usr/lib/python3/dist-packages/pylint/checkers/classes/special_methods_checker.py\", line 42, in _safe_infer_call_result\r\n value = next(inferit)\r\n File \"/usr/lib/python3/dist-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 1749, in infer_call_result\r\n yield from returnnode.value.infer(context)\r\n File \"/usr/lib/python3/dist-packages/astroid/nodes/node_ng.py\", line 159, in infer\r\n results = list(self._explicit_inference(self, context, **kwargs))\r\n File \"/usr/lib/python3/dist-packages/astroid/inference_tip.py\", line 45, in _inference_tip_cached\r\n result = _cache[func, node] = list(func(*args, **kwargs))\r\n File \"/usr/lib/python3/dist-packages/astroid/brain/brain_builtin_inference.py\", line 956, in _infer_str_format_call\r\n formatted_string = format_template.format(*pos_values, **keyword_values)\r\nTypeError: unsupported format string passed to NoneType.__format__\r\n```\r\n\r\n### Expected behavior\r\n\r\nTypeError exception should not happen\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.12.10,\r\n2.12.12\n", "hints_text": "Hi @crosser, thanks for the report.\r\n\r\n> I have no concise reproducer. \r\n\r\nWe might be able to help you distill one.\r\n\r\n`pylint` produces a crash report, and shows the link in your terminal, like this:\r\n```shell\r\n************* Module a\r\na.py:1:0: F0002: a.py: Fatal error while checking 'a.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/Users/.../Library/Caches/pylint/pylint-crash-2022-10-29-08-48-25.txt'. (astroid-error)\r\n```\r\nThe offending file is at the top of the crash report. If the code is too long, or contains sensitive information, you can use the knowledge that the crash happened in `_infer_str_format_call` to look for calls to `.format()` on strings. You should be able to then just provide us those calls--and enough surrounding code to rebuild the objects you provided to `format()`. \r\n\r\nDoing this would be a tremendous help!\n> `pylint` produces a crash report, and shows the link in your terminal, like this:\r\n\r\nNo, not really, it does not. I am attaching a (censored) stderr from running the test. The line in the source code that apparently triggers the problem is pretty innocuous:\r\n\r\n```\r\n @property\r\n def vnet_id(self): # <---- this is the line 266 that is mentioned in the \"Exception on node\" message\r\n if ...:\r\n```\r\nThere is very similar property definition right before this one, that does not trigger the problem.\r\n\r\n[pyerr.txt](https://github.com/PyCQA/astroid/files/9900190/pyerr.txt)\r\n\r\nPylint command was `python3 -m pylint --jobs=0 --rcfile=test/style/pylint.conf <project-dir>`\r\n\r\n```\r\n$ pylint --version\r\npylint 2.15.5\r\nastroid 2.12.12\r\nPython 3.10.8 (main, Oct 24 2022, 10:07:16) [GCC 12.2.0]\r\n```\r\n\r\nedit:\r\n> enough surrounding code to rebuild the objects you provided to format().\r\n\r\n_I_ did not provide any objects to `format()`, astroid did...\nThanks for providing the traceback.\r\n\r\n> No, not really, it does not. I am attaching a (censored) stderr from running the test. \r\n\r\nI see now that it's because you're invoking pylint from a unittest, so your test is managing the output.\r\n\r\n> The line in the source code that apparently triggers the problem is pretty innocuous:\r\n\r\nThe deeper failure is on the call in line 268, not the function def on line 266. Is there anything you can sanitize and tell us about line 268? Thanks again for providing the help.\n> I see now that it's because you're invoking pylint from a unittest, so your test is managing the output.\r\n\r\nWhen I run pylint by hand\r\n\r\n```\r\npylint --jobs=0 --rcfile=test/style/pylint.conf <module-name> | tee /tmp/pyerr.txt\r\n```\r\nthere is still no \"Fatal error while checking ...\" message in the output\r\n\r\n> > The line in the source code that apparently triggers the problem is pretty innocuous:\r\n> \r\n> The deeper failure is on the call in line 268, not the function def on line 266. Is there anything you can sanitize and tell us about line 268? Thanks again for providing the help.\r\n\r\nOh yes, there is a `something.format()` in that line! But the \"something\" is a literal string:\r\n```\r\n @property\r\n def vnet_id(self):\r\n if self.backend == \"something\":\r\n return \"{:04x}{:04x}n{:d}\".format( # <---- this is line 268\r\n self.<some-attr>, self.<another-attr>, self.<third-attr>\r\n )\r\n if self.backend == \"somethingelse\":\r\n return \"h{:08}n{:d}\".format(self.<more-attr>, self.<and more>)\r\n return None\r\n```\r\n\nThanks, that was very helpful. Here is a reproducer:\r\n```python\r\nx = \"{:c}\".format(None)\r\n```", "created_at": "2022-11-12T19:21:34Z", "version": "2.13", "FAIL_TO_PASS": ["tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\\n"], "PASS_TO_PASS": ["tests/unittest_brain_builtin.py::BuiltinsTest::test_infer_property", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[numbered-indexes-from-positional]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[named-indexes-from-keyword]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[mixed-indexes-from-mixed]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format[empty-indexes-on-variable]", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_uninferable[\"I", "tests/unittest_brain_builtin.py::TestStringNodes::test_string_format_with_specs"], "environment_setup_commit": "fe058bff95745371df5796286d33677c21137847"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1092", "base_commit": "c9c498348174b38ce35bfe001353c8ebea262802", "patch": "diff --git a/astroid/bases.py b/astroid/bases.py\n--- a/astroid/bases.py\n+++ b/astroid/bases.py\n@@ -26,7 +26,7 @@\n import collections\n \n from astroid import context as contextmod\n-from astroid import util\n+from astroid import decorators, util\n from astroid.const import BUILTINS, PY310_PLUS\n from astroid.exceptions import (\n AstroidTypeError,\n@@ -543,9 +543,14 @@ class Generator(BaseInstance):\n \n special_attributes = util.lazy_descriptor(objectmodel.GeneratorModel)\n \n- def __init__(self, parent=None):\n+ def __init__(self, parent=None, generator_initial_context=None):\n super().__init__()\n self.parent = parent\n+ self._call_context = contextmod.copy_context(generator_initial_context)\n+\n+ @decorators.cached\n+ def infer_yield_types(self):\n+ yield from self.parent.infer_yield_result(self._call_context)\n \n def callable(self):\n return False\ndiff --git a/astroid/protocols.py b/astroid/protocols.py\n--- a/astroid/protocols.py\n+++ b/astroid/protocols.py\n@@ -489,22 +489,8 @@ def _infer_context_manager(self, mgr, context):\n # It doesn't interest us.\n raise InferenceError(node=func)\n \n- # Get the first yield point. If it has multiple yields,\n- # then a RuntimeError will be raised.\n+ yield next(inferred.infer_yield_types())\n \n- possible_yield_points = func.nodes_of_class(nodes.Yield)\n- # Ignore yields in nested functions\n- yield_point = next(\n- (node for node in possible_yield_points if node.scope() == func), None\n- )\n- if yield_point:\n- if not yield_point.value:\n- const = nodes.Const(None)\n- const.parent = yield_point\n- const.lineno = yield_point.lineno\n- yield const\n- else:\n- yield from yield_point.value.infer(context=context)\n elif isinstance(inferred, bases.Instance):\n try:\n enter = next(inferred.igetattr(\"__enter__\", context=context))\ndiff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py\n--- a/astroid/scoped_nodes.py\n+++ b/astroid/scoped_nodes.py\n@@ -1708,6 +1708,21 @@ def is_generator(self):\n \"\"\"\n return bool(next(self._get_yield_nodes_skip_lambdas(), False))\n \n+ def infer_yield_result(self, context=None):\n+ \"\"\"Infer what the function yields when called\n+\n+ :returns: What the function yields\n+ :rtype: iterable(NodeNG or Uninferable) or None\n+ \"\"\"\n+ for yield_ in self.nodes_of_class(node_classes.Yield):\n+ if yield_.value is None:\n+ const = node_classes.Const(None)\n+ const.parent = yield_\n+ const.lineno = yield_.lineno\n+ yield const\n+ elif yield_.scope() == self:\n+ yield from yield_.value.infer(context=context)\n+\n def infer_call_result(self, caller=None, context=None):\n \"\"\"Infer what the function returns when called.\n \n@@ -1719,7 +1734,7 @@ def infer_call_result(self, caller=None, context=None):\n generator_cls = bases.AsyncGenerator\n else:\n generator_cls = bases.Generator\n- result = generator_cls(self)\n+ result = generator_cls(self, generator_initial_context=context)\n yield result\n return\n # This is really a gigantic hack to work around metaclass generators\n", "test_patch": "diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py\n--- a/tests/unittest_inference.py\n+++ b/tests/unittest_inference.py\n@@ -6154,5 +6154,26 @@ def test_issue926_binop_referencing_same_name_is_not_uninferable():\n assert inferred[0].value == 3\n \n \n+def test_issue_1090_infer_yield_type_base_class():\n+ code = \"\"\"\n+import contextlib\n+\n+class A:\n+ @contextlib.contextmanager\n+ def get(self):\n+ yield self\n+\n+class B(A):\n+ def play():\n+ pass\n+\n+with B().get() as b:\n+ b\n+b\n+ \"\"\"\n+ node = extract_node(code)\n+ assert next(node.infer()).pytype() == \".B\"\n+\n+\n if __name__ == \"__main__\":\n unittest.main()\n", "problem_statement": "Yield self is inferred to be of a mistaken type \n### Steps to reproduce\r\n\r\n1. Run the following\r\n```\r\nimport astroid\r\n\r\n\r\nprint(list(astroid.parse('''\r\nimport contextlib\r\n\r\nclass A:\r\n @contextlib.contextmanager\r\n def get(self):\r\n yield self\r\n\r\nclass B(A):\r\n def play():\r\n pass\r\n\r\nwith B().get() as b:\r\n b.play()\r\n''').ilookup('b')))\r\n```\r\n\r\n### Current behavior\r\n```Prints [<Instance of .A at 0x...>]```\r\n\r\n### Expected behavior\r\n```Prints [<Instance of .B at 0x...>]```\r\n\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n2.6.2\n", "hints_text": "Possible duplicate of #1008 \nThis problem is due to the fact `_infer_context_manager` takes caller function, using its current context, instead of the original callers context. This may be fixed for example by adding data to `Generator` instance, by `infer_call_result` that signifies its possible value types.\r\n\r\nI'm not familiar with the codebase, it seems to me that that this is not the correct approach, but, the correct approach is to pass this data inside the `context` structure. But it's not clear to me how to do that.", "created_at": "2021-07-10T10:44:32Z", "version": "2.6", "FAIL_TO_PASS": ["tests/unittest_inference.py::test_issue_1090_infer_yield_type_base_class"], "PASS_TO_PASS": ["tests/unittest_inference.py::InferenceUtilsTest::test_path_wrapper", "tests/unittest_inference.py::InferenceTest::test__new__", "tests/unittest_inference.py::InferenceTest::test__new__bound_methods", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference1", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference2", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference2", "tests/unittest_inference.py::InferenceTest::test_args_default_inference1", "tests/unittest_inference.py::InferenceTest::test_args_default_inference2", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented_rop_fallback", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_not_implemented_normal_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_aug_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_normal_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_augassign", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_none_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_normal_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_not_implemented_returned_for_all", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_reflected_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_bin_op_classes", "tests/unittest_inference.py::InferenceTest::test_bin_op_supertype_more_complicated_example", "tests/unittest_inference.py::InferenceTest::test_binary_op_custom_class", "tests/unittest_inference.py::InferenceTest::test_binary_op_float_div", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitand", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitxor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftleft", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftright", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_sub", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_int", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_none", "tests/unittest_inference.py::InferenceTest::test_binary_op_on_self", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type_using_reflected_operands", "tests/unittest_inference.py::InferenceTest::test_binary_op_reflected_and_not_implemented_is_type_error", "tests/unittest_inference.py::InferenceTest::test_binary_op_str_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_tuple_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_type_errors", "tests/unittest_inference.py::InferenceTest::test_binop_ambiguity", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_normal_not_implemented_and_reflected", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_and_normal_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_only", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_unknown_bases", "tests/unittest_inference.py::InferenceTest::test_binop_inference_errors", "tests/unittest_inference.py::InferenceTest::test_binop_list_with_elts", "tests/unittest_inference.py::InferenceTest::test_binop_same_types", "tests/unittest_inference.py::InferenceTest::test_binop_subtype", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_implemented_in_parent", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_rop_not_implemented", "tests/unittest_inference.py::InferenceTest::test_bool_value", "tests/unittest_inference.py::InferenceTest::test_bool_value_instances", "tests/unittest_inference.py::InferenceTest::test_bool_value_recursive", "tests/unittest_inference.py::InferenceTest::test_bool_value_variable", "tests/unittest_inference.py::InferenceTest::test_bound_method_inference", "tests/unittest_inference.py::InferenceTest::test_bt_ancestor_crash", "tests/unittest_inference.py::InferenceTest::test_builtin_help", "tests/unittest_inference.py::InferenceTest::test_builtin_inference_py3k", "tests/unittest_inference.py::InferenceTest::test_builtin_name_inference", "tests/unittest_inference.py::InferenceTest::test_builtin_open", "tests/unittest_inference.py::InferenceTest::test_builtin_types", "tests/unittest_inference.py::InferenceTest::test_bytes_subscript", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_func", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_lambda", "tests/unittest_inference.py::InferenceTest::test_callfunc_inference", "tests/unittest_inference.py::InferenceTest::test_class_inference", "tests/unittest_inference.py::InferenceTest::test_classmethod_inferred_by_context", "tests/unittest_inference.py::InferenceTest::test_context_call_for_context_managers", "tests/unittest_inference.py::InferenceTest::test_conversion_of_dict_methods", "tests/unittest_inference.py::InferenceTest::test_del1", "tests/unittest_inference.py::InferenceTest::test_del2", "tests/unittest_inference.py::InferenceTest::test_delayed_attributes_without_slots", "tests/unittest_inference.py::InferenceTest::test_dict_inference", "tests/unittest_inference.py::InferenceTest::test_dict_inference_for_multiple_starred", "tests/unittest_inference.py::InferenceTest::test_dict_inference_kwargs", "tests/unittest_inference.py::InferenceTest::test_dict_inference_unpack_repeated_key", "tests/unittest_inference.py::InferenceTest::test_dict_invalid_args", "tests/unittest_inference.py::InferenceTest::test_exc_ancestors", "tests/unittest_inference.py::InferenceTest::test_except_inference", "tests/unittest_inference.py::InferenceTest::test_f_arg_f", "tests/unittest_inference.py::InferenceTest::test_factory_method", "tests/unittest_inference.py::InferenceTest::test_factory_methods_cls_call", "tests/unittest_inference.py::InferenceTest::test_factory_methods_object_new_call", "tests/unittest_inference.py::InferenceTest::test_float_complex_ambiguity", "tests/unittest_inference.py::InferenceTest::test_frozenset_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_function_inference", "tests/unittest_inference.py::InferenceTest::test_genexpr_bool_value", "tests/unittest_inference.py::InferenceTest::test_getattr_inference1", "tests/unittest_inference.py::InferenceTest::test_getattr_inference2", "tests/unittest_inference.py::InferenceTest::test_getattr_inference3", "tests/unittest_inference.py::InferenceTest::test_getattr_inference4", "tests/unittest_inference.py::InferenceTest::test_getitem_of_class_raised_type_error", "tests/unittest_inference.py::InferenceTest::test_im_func_unwrap", "tests/unittest_inference.py::InferenceTest::test_import_as", "tests/unittest_inference.py::InferenceTest::test_infer_abstract_property_return_values", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_object_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_defined_in_outer_scope_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_subscript_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arguments", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_crash", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_invalid_dunder_call_on_instance", "tests/unittest_inference.py::InferenceTest::test_infer_cls_in_class_methods", "tests/unittest_inference.py::InferenceTest::test_infer_coercion_rules_for_floats_complex", "tests/unittest_inference.py::InferenceTest::test_infer_empty_nodes", "tests/unittest_inference.py::InferenceTest::test_infer_nested", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class_works_indirectly", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr_indirect", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_outer_class", "tests/unittest_inference.py::InferenceTest::test_infer_variable_arguments", "tests/unittest_inference.py::InferenceTest::test_inference_restrictions", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_skip_index_error", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_unpacking_inference_error", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager_failures", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement_failures", "tests/unittest_inference.py::InferenceTest::test_infinite_loop_for_decorators", "tests/unittest_inference.py::InferenceTest::test_inner_value_redefined_by_subclass", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_multiple_methods", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_parent", "tests/unittest_inference.py::InferenceTest::test_instance_slicing", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_fails", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_slices", "tests/unittest_inference.py::InferenceTest::test_invalid_slicing_primaries", "tests/unittest_inference.py::InferenceTest::test_invalid_subscripts", "tests/unittest_inference.py::InferenceTest::test_lambda_as_methods", "tests/unittest_inference.py::InferenceTest::test_list_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_list_inference", "tests/unittest_inference.py::InferenceTest::test_listassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_lookup_cond_branches", "tests/unittest_inference.py::InferenceTest::test_matmul", "tests/unittest_inference.py::InferenceTest::test_metaclass__getitem__", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call_boundnode", "tests/unittest_inference.py::InferenceTest::test_metaclass_subclasses_arguments_are_classes_not_instances", "tests/unittest_inference.py::InferenceTest::test_metaclass_with_keyword_args", "tests/unittest_inference.py::InferenceTest::test_method_argument", "tests/unittest_inference.py::InferenceTest::test_module_inference", "tests/unittest_inference.py::InferenceTest::test_mul_list_supports__index__", "tests/unittest_inference.py::InferenceTest::test_mulassign_inference", "tests/unittest_inference.py::InferenceTest::test_name_bool_value", "tests/unittest_inference.py::InferenceTest::test_nested_contextmanager", "tests/unittest_inference.py::InferenceTest::test_no_infinite_ancestor_loop", "tests/unittest_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference", "tests/unittest_inference.py::InferenceTest::test_nonregr_absolute_import", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_arg", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_global", "tests/unittest_inference.py::InferenceTest::test_nonregr_getitem_empty_tuple", "tests/unittest_inference.py::InferenceTest::test_nonregr_inference_modifying_col_offset", "tests/unittest_inference.py::InferenceTest::test_nonregr_instance_attrs", "tests/unittest_inference.py::InferenceTest::test_nonregr_lambda_arg", "tests/unittest_inference.py::InferenceTest::test_nonregr_layed_dictunpack", "tests/unittest_inference.py::InferenceTest::test_nonregr_multi_referential_addition", "tests/unittest_inference.py::InferenceTest::test_pluggable_inference", "tests/unittest_inference.py::InferenceTest::test_property", "tests/unittest_inference.py::InferenceTest::test_python25_no_relative_import", "tests/unittest_inference.py::InferenceTest::test_scope_lookup_same_attributes", "tests/unittest_inference.py::InferenceTest::test_set_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_simple_for", "tests/unittest_inference.py::InferenceTest::test_simple_for_genexpr", "tests/unittest_inference.py::InferenceTest::test_simple_subscript", "tests/unittest_inference.py::InferenceTest::test_simple_tuple", "tests/unittest_inference.py::InferenceTest::test_slicing_list", "tests/unittest_inference.py::InferenceTest::test_slicing_str", "tests/unittest_inference.py::InferenceTest::test_slicing_tuple", "tests/unittest_inference.py::InferenceTest::test_special_method_masquerading_as_another", "tests/unittest_inference.py::InferenceTest::test_starred_in_list_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_literals_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_no_inference_possible", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_non_const_keys_values", "tests/unittest_inference.py::InferenceTest::test_starred_in_set_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_tuple_literal", "tests/unittest_inference.py::InferenceTest::test_stop_iteration_leak", "tests/unittest_inference.py::InferenceTest::test_str_methods", "tests/unittest_inference.py::InferenceTest::test_subscript_inference_error", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_slice", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_value", "tests/unittest_inference.py::InferenceTest::test_subscript_supports__index__", "tests/unittest_inference.py::InferenceTest::test_swap_assign_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_then_list", "tests/unittest_inference.py::InferenceTest::test_tupleassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_two_parents_from_same_module", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_attrs", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_bases", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_mcs_argument", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_name", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_and_ancestors_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__not_enough_arguments", "tests/unittest_inference.py::InferenceTest::test_type__new__with_metaclass", "tests/unittest_inference.py::InferenceTest::test_unary_empty_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_not", "tests/unittest_inference.py::InferenceTest::test_unary_op_assignment", "tests/unittest_inference.py::InferenceTest::test_unary_op_classes", "tests/unittest_inference.py::InferenceTest::test_unary_op_instance_method_not_callable", "tests/unittest_inference.py::InferenceTest::test_unary_op_leaks_stop_iteration", "tests/unittest_inference.py::InferenceTest::test_unary_op_numbers", "tests/unittest_inference.py::InferenceTest::test_unary_operands", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors_for_non_instance_objects", "tests/unittest_inference.py::InferenceTest::test_unbound_method_inference", "tests/unittest_inference.py::InferenceTest::test_unicode_methods", "tests/unittest_inference.py::GetattrTest::test_attribute_missing", "tests/unittest_inference.py::GetattrTest::test_attrname_not_string", "tests/unittest_inference.py::GetattrTest::test_default", "tests/unittest_inference.py::GetattrTest::test_lambda", "tests/unittest_inference.py::GetattrTest::test_lookup", "tests/unittest_inference.py::GetattrTest::test_yes_when_unknown", "tests/unittest_inference.py::HasattrTest::test_attribute_is_missing", "tests/unittest_inference.py::HasattrTest::test_attribute_is_not_missing", "tests/unittest_inference.py::HasattrTest::test_inference_errors", "tests/unittest_inference.py::HasattrTest::test_lambda", "tests/unittest_inference.py::BoolOpTest::test_bool_ops", "tests/unittest_inference.py::BoolOpTest::test_other_nodes", "tests/unittest_inference.py::BoolOpTest::test_yes_when_unknown", "tests/unittest_inference.py::TestCallable::test_callable", "tests/unittest_inference.py::TestCallable::test_callable_methods", "tests/unittest_inference.py::TestCallable::test_inference_errors", "tests/unittest_inference.py::TestCallable::test_not_callable", "tests/unittest_inference.py::TestBool::test_bool", "tests/unittest_inference.py::TestBool::test_bool_bool_special_method", "tests/unittest_inference.py::TestBool::test_bool_instance_not_callable", "tests/unittest_inference.py::TestType::test_type", "tests/unittest_inference.py::ArgumentsTest::test_args", "tests/unittest_inference.py::ArgumentsTest::test_defaults", "tests/unittest_inference.py::ArgumentsTest::test_fail_to_infer_args", "tests/unittest_inference.py::ArgumentsTest::test_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_access_by_name", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_and_other_named_parameters", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_are_overridden", "tests/unittest_inference.py::ArgumentsTest::test_kwonly_args", "tests/unittest_inference.py::ArgumentsTest::test_multiple_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_multiple_starred_args", "tests/unittest_inference.py::SliceTest::test_slice", "tests/unittest_inference.py::SliceTest::test_slice_attributes", "tests/unittest_inference.py::SliceTest::test_slice_inference_error", "tests/unittest_inference.py::SliceTest::test_slice_type", "tests/unittest_inference.py::CallSiteTest::test_call_site", "tests/unittest_inference.py::CallSiteTest::test_call_site_starred_args", "tests/unittest_inference.py::CallSiteTest::test_call_site_valid_arguments", "tests/unittest_inference.py::CallSiteTest::test_duplicated_keyword_arguments", "tests/unittest_inference.py::ObjectDunderNewTest::test_object_dunder_new_is_inferred_if_decorator", "tests/unittest_inference.py::test_augassign_recursion", "tests/unittest_inference.py::test_infer_custom_inherit_from_property", "tests/unittest_inference.py::test_cannot_infer_call_result_for_builtin_methods", "tests/unittest_inference.py::test_unpack_dicts_in_assignment", "tests/unittest_inference.py::test_slice_inference_in_for_loops", "tests/unittest_inference.py::test_slice_inference_in_for_loops_not_working", "tests/unittest_inference.py::test_unpacking_starred_and_dicts_in_assignment", "tests/unittest_inference.py::test_unpacking_starred_empty_list_in_assignment", "tests/unittest_inference.py::test_regression_infinite_loop_decorator", "tests/unittest_inference.py::test_stop_iteration_in_int", "tests/unittest_inference.py::test_call_on_instance_with_inherited_dunder_call_method", "tests/unittest_inference.py::TestInferencePropagation::test_call_starargs_propagation", "tests/unittest_inference.py::TestInferencePropagation::test_call_kwargs_propagation", "tests/unittest_inference.py::test_limit_inference_result_amount", "tests/unittest_inference.py::test_attribute_inference_should_not_access_base_classes", "tests/unittest_inference.py::test_attribute_mro_object_inference", "tests/unittest_inference.py::test_inferred_sequence_unpacking_works", "tests/unittest_inference.py::test_recursion_error_inferring_slice", "tests/unittest_inference.py::test_exception_lookup_last_except_handler_wins", "tests/unittest_inference.py::test_exception_lookup_name_bound_in_except_handler", "tests/unittest_inference.py::test_builtin_inference_list_of_exceptions", "tests/unittest_inference.py::test_cannot_getattr_ann_assigns", "tests/unittest_inference.py::test_prevent_recursion_error_in_igetattr_and_context_manager_inference", "tests/unittest_inference.py::test_infer_context_manager_with_unknown_args", "tests/unittest_inference.py::test_subclass_of_exception[\\n", "tests/unittest_inference.py::test_ifexp_inference", "tests/unittest_inference.py::test_assert_last_function_returns_none_on_inference", "tests/unittest_inference.py::test_posonlyargs_inference", "tests/unittest_inference.py::test_infer_args_unpacking_of_self", "tests/unittest_inference.py::test_infer_exception_instance_attributes", "tests/unittest_inference.py::test_inference_is_limited_to_the_boundnode[\\n", "tests/unittest_inference.py::test_property_inference", "tests/unittest_inference.py::test_property_as_string", "tests/unittest_inference.py::test_property_callable_inference", "tests/unittest_inference.py::test_recursion_error_inferring_builtin_containers", "tests/unittest_inference.py::test_inferaugassign_picking_parent_instead_of_stmt", "tests/unittest_inference.py::test_classmethod_from_builtins_inferred_as_bound", "tests/unittest_inference.py::test_infer_dict_passes_context", "tests/unittest_inference.py::test_custom_decorators_for_classmethod_and_staticmethods[\\n", "tests/unittest_inference.py::test_dataclasses_subscript_inference_recursion_error_39", "tests/unittest_inference.py::test_self_reference_infer_does_not_trigger_recursion_error", "tests/unittest_inference.py::test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_times", "tests/unittest_inference.py::test_getattr_fails_on_empty_values", "tests/unittest_inference.py::test_infer_first_argument_of_static_method_in_metaclass", "tests/unittest_inference.py::test_recursion_error_metaclass_monkeypatching", "tests/unittest_inference.py::test_allow_retrieving_instance_attrs_and_special_attrs_for_functions", "tests/unittest_inference.py::test_implicit_parameters_bound_method", "tests/unittest_inference.py::test_super_inference_of_abstract_property", "tests/unittest_inference.py::test_infer_generated_setter", "tests/unittest_inference.py::test_infer_list_of_uninferables_does_not_crash", "tests/unittest_inference.py::test_issue926_infer_stmts_referencing_same_name_is_not_uninferable", "tests/unittest_inference.py::test_issue926_binop_referencing_same_name_is_not_uninferable"], "environment_setup_commit": "c9c498348174b38ce35bfe001353c8ebea262802"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-2309", "base_commit": "29b42e5e9745b172d5980511d14efeac745a5a82", "patch": "diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py\n--- a/astroid/brain/brain_typing.py\n+++ b/astroid/brain/brain_typing.py\n@@ -15,6 +15,7 @@\n from astroid.builder import _extract_single_node\n from astroid.const import PY38_PLUS, PY39_PLUS\n from astroid.exceptions import (\n+ AstroidSyntaxError,\n AttributeInferenceError,\n InferenceError,\n UseInferenceDefault,\n@@ -139,14 +140,10 @@ def infer_typing_typevar_or_newtype(\n raise UseInferenceDefault\n \n typename = node.args[0].as_string().strip(\"'\")\n- node = ClassDef(\n- name=typename,\n- lineno=node.lineno,\n- col_offset=node.col_offset,\n- parent=node.parent,\n- end_lineno=node.end_lineno,\n- end_col_offset=node.end_col_offset,\n- )\n+ try:\n+ node = extract_node(TYPING_TYPE_TEMPLATE.format(typename))\n+ except AstroidSyntaxError as exc:\n+ raise InferenceError from exc\n return node.infer(context=context_itton)\n \n \n", "test_patch": "diff --git a/tests/brain/test_typing.py b/tests/brain/test_typing.py\n--- a/tests/brain/test_typing.py\n+++ b/tests/brain/test_typing.py\n@@ -5,7 +5,10 @@\n # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE\n # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt\n \n-from astroid import builder, nodes\n+import pytest\n+\n+from astroid import builder\n+from astroid.exceptions import InferenceError\n \n \n def test_infer_typevar() -> None:\n@@ -15,13 +18,11 @@ def test_infer_typevar() -> None:\n Test that an inferred `typing.TypeVar()` call produces a `nodes.ClassDef`\n node.\n \"\"\"\n- assign_node = builder.extract_node(\n+ call_node = builder.extract_node(\n \"\"\"\n from typing import TypeVar\n- MyType = TypeVar('My.Type')\n+ TypeVar('My.Type')\n \"\"\"\n )\n- call = assign_node.value\n- inferred = next(call.infer())\n- assert isinstance(inferred, nodes.ClassDef)\n- assert inferred.name == \"My.Type\"\n+ with pytest.raises(InferenceError):\n+ call_node.inferred()\n", "problem_statement": "Regression in Astroid version 2.15.7 in handling subscriptable type parameters\nAstroid version 2.15.7 fails to correctly handle a subscriptable type parameter most likely due to the change in this [PR](https://github.com/pylint-dev/astroid/pull/2239). \r\n\r\n### Steps to reproduce\r\n\r\n```python\r\nfrom collections.abc import Mapping\r\nfrom typing import Generic, TypeVar, TypedDict\r\nfrom dataclasses import dataclass\r\n\r\nclass Identity(TypedDict):\r\n \"\"\"It's the identity.\"\"\"\r\n\r\n name: str\r\n\r\nT = TypeVar(\"T\", bound=Mapping)\r\n\r\n@dataclass\r\nclass Animal(Generic[T]):\r\n \"\"\"It's an animal.\"\"\"\r\n\r\n identity: T\r\n\r\nclass Dog(Animal[Identity]):\r\n \"\"\"It's a Dog.\"\"\"\r\n\r\ndog = Dog(identity=Identity(name=\"Dog\"))\r\nprint(dog.identity[\"name\"])\r\n```\r\n\r\n### Current behavior\r\nPylint (running Astroid 2.15.7) gives the following error for the example above:\r\n```\r\nE1136: Value 'dog.identity' is unsubscriptable (unsubscriptable-object)\r\n```\r\n### Expected behavior\r\nAstroid should correctly handle a subscriptable type parameter.\r\n\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n2.15.7\n", "hints_text": "Thanks for the report.\n@mbyrnepr2 Would you be willing to take a look?", "created_at": "2023-09-26T12:05:24Z", "version": "2.15", "FAIL_TO_PASS": ["tests/brain/test_typing.py::test_infer_typevar"], "PASS_TO_PASS": [], "environment_setup_commit": "29b42e5e9745b172d5980511d14efeac745a5a82"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-2219", "base_commit": "efb34f2b84c9f019ffceacef3448d8351563b6a2", "patch": "diff --git a/astroid/brain/brain_datetime.py b/astroid/brain/brain_datetime.py\nnew file mode 100644\n--- /dev/null\n+++ b/astroid/brain/brain_datetime.py\n@@ -0,0 +1,31 @@\n+# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n+# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE\n+# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt\n+\n+import textwrap\n+\n+from astroid.brain.helpers import register_module_extender\n+from astroid.builder import AstroidBuilder\n+from astroid.const import PY312_PLUS\n+from astroid.manager import AstroidManager\n+\n+\n+def datetime_transform():\n+ \"\"\"The datetime module was C-accelerated in Python 3.12, so we\n+ lack a Python source.\"\"\"\n+ return AstroidBuilder(AstroidManager()).string_build(\n+ textwrap.dedent(\n+ \"\"\"\n+ class date: ...\n+ class time: ...\n+ class datetime(date): ...\n+ class timedelta: ...\n+ class tzinfo: ...\n+ class timezone(tzinfo): ...\n+ \"\"\"\n+ )\n+ )\n+\n+\n+if PY312_PLUS:\n+ register_module_extender(AstroidManager(), \"datetime\", datetime_transform)\ndiff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py\n--- a/astroid/brain/brain_typing.py\n+++ b/astroid/brain/brain_typing.py\n@@ -6,14 +6,16 @@\n \n from __future__ import annotations\n \n+import textwrap\n import typing\n from collections.abc import Iterator\n from functools import partial\n from typing import Final\n \n from astroid import context, extract_node, inference_tip\n-from astroid.builder import _extract_single_node\n-from astroid.const import PY39_PLUS\n+from astroid.brain.helpers import register_module_extender\n+from astroid.builder import AstroidBuilder, _extract_single_node\n+from astroid.const import PY39_PLUS, PY312_PLUS\n from astroid.exceptions import (\n AttributeInferenceError,\n InferenceError,\n@@ -231,7 +233,8 @@ def _looks_like_typing_alias(node: Call) -> bool:\n \"\"\"\n return (\n isinstance(node.func, Name)\n- and node.func.name == \"_alias\"\n+ # TODO: remove _DeprecatedGenericAlias when Py3.14 min\n+ and node.func.name in {\"_alias\", \"_DeprecatedGenericAlias\"}\n and (\n # _alias function works also for builtins object such as list and dict\n isinstance(node.args[0], (Attribute, Name))\n@@ -273,6 +276,8 @@ def infer_typing_alias(\n \n :param node: call node\n :param context: inference context\n+\n+ # TODO: evaluate if still necessary when Py3.12 is minimum\n \"\"\"\n if (\n not isinstance(node.parent, Assign)\n@@ -415,6 +420,29 @@ def infer_typing_cast(\n return node.args[1].infer(context=ctx)\n \n \n+def _typing_transform():\n+ return AstroidBuilder(AstroidManager()).string_build(\n+ textwrap.dedent(\n+ \"\"\"\n+ class Generic:\n+ @classmethod\n+ def __class_getitem__(cls, item): return cls\n+ class ParamSpec: ...\n+ class ParamSpecArgs: ...\n+ class ParamSpecKwargs: ...\n+ class TypeAlias: ...\n+ class Type:\n+ @classmethod\n+ def __class_getitem__(cls, item): return cls\n+ class TypeVar:\n+ @classmethod\n+ def __class_getitem__(cls, item): return cls\n+ class TypeVarTuple: ...\n+ \"\"\"\n+ )\n+ )\n+\n+\n AstroidManager().register_transform(\n Call,\n inference_tip(infer_typing_typevar_or_newtype),\n@@ -442,3 +470,6 @@ def infer_typing_cast(\n AstroidManager().register_transform(\n Call, inference_tip(infer_special_alias), _looks_like_special_alias\n )\n+\n+if PY312_PLUS:\n+ register_module_extender(AstroidManager(), \"typing\", _typing_transform)\ndiff --git a/astroid/const.py b/astroid/const.py\n--- a/astroid/const.py\n+++ b/astroid/const.py\n@@ -10,6 +10,7 @@\n PY39_PLUS = sys.version_info >= (3, 9)\n PY310_PLUS = sys.version_info >= (3, 10)\n PY311_PLUS = sys.version_info >= (3, 11)\n+PY312_PLUS = sys.version_info >= (3, 12)\n \n WIN32 = sys.platform == \"win32\"\n \ndiff --git a/astroid/inference.py b/astroid/inference.py\n--- a/astroid/inference.py\n+++ b/astroid/inference.py\n@@ -92,6 +92,10 @@ def infer_end(\n nodes.Lambda._infer = infer_end # type: ignore[assignment]\n nodes.Const._infer = infer_end # type: ignore[assignment]\n nodes.Slice._infer = infer_end # type: ignore[assignment]\n+nodes.TypeAlias._infer = infer_end # type: ignore[assignment]\n+nodes.TypeVar._infer = infer_end # type: ignore[assignment]\n+nodes.ParamSpec._infer = infer_end # type: ignore[assignment]\n+nodes.TypeVarTuple._infer = infer_end # type: ignore[assignment]\n \n \n def _infer_sequence_helper(\ndiff --git a/astroid/nodes/__init__.py b/astroid/nodes/__init__.py\n--- a/astroid/nodes/__init__.py\n+++ b/astroid/nodes/__init__.py\n@@ -71,6 +71,7 @@\n NamedExpr,\n NodeNG,\n Nonlocal,\n+ ParamSpec,\n Pass,\n Pattern,\n Raise,\n@@ -83,6 +84,9 @@\n TryFinally,\n TryStar,\n Tuple,\n+ TypeAlias,\n+ TypeVar,\n+ TypeVarTuple,\n UnaryOp,\n Unknown,\n While,\n@@ -180,6 +184,8 @@\n NamedExpr,\n NodeNG,\n Nonlocal,\n+ ParamSpec,\n+ TypeVarTuple,\n Pass,\n Pattern,\n Raise,\n@@ -193,6 +199,8 @@\n TryFinally,\n TryStar,\n Tuple,\n+ TypeAlias,\n+ TypeVar,\n UnaryOp,\n Unknown,\n While,\n@@ -271,6 +279,7 @@\n \"NamedExpr\",\n \"NodeNG\",\n \"Nonlocal\",\n+ \"ParamSpec\",\n \"Pass\",\n \"Position\",\n \"Raise\",\n@@ -285,6 +294,9 @@\n \"TryFinally\",\n \"TryStar\",\n \"Tuple\",\n+ \"TypeAlias\",\n+ \"TypeVar\",\n+ \"TypeVarTuple\",\n \"UnaryOp\",\n \"Unknown\",\n \"unpack_infer\",\ndiff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py\n--- a/astroid/nodes/as_string.py\n+++ b/astroid/nodes/as_string.py\n@@ -178,6 +178,7 @@ def visit_classdef(self, node) -> str:\n args += [n.accept(self) for n in node.keywords]\n args_str = f\"({', '.join(args)})\" if args else \"\"\n docs = self._docs_dedent(node.doc_node)\n+ # TODO: handle type_params\n return \"\\n\\n{}class {}{}:{}\\n{}\\n\".format(\n decorate, node.name, args_str, docs, self._stmt_list(node.body)\n )\n@@ -330,6 +331,7 @@ def handle_functiondef(self, node, keyword) -> str:\n if node.returns:\n return_annotation = \" -> \" + node.returns.as_string()\n trailer = return_annotation + \":\"\n+ # TODO: handle type_params\n def_format = \"\\n%s%s %s(%s)%s%s\\n%s\"\n return def_format % (\n decorate,\n@@ -431,6 +433,10 @@ def visit_nonlocal(self, node) -> str:\n \"\"\"return an astroid.Nonlocal node as string\"\"\"\n return f\"nonlocal {', '.join(node.names)}\"\n \n+ def visit_paramspec(self, node: nodes.ParamSpec) -> str:\n+ \"\"\"return an astroid.ParamSpec node as string\"\"\"\n+ return node.name.accept(self)\n+\n def visit_pass(self, node) -> str:\n \"\"\"return an astroid.Pass node as string\"\"\"\n return \"pass\"\n@@ -517,6 +523,18 @@ def visit_tuple(self, node) -> str:\n return f\"({node.elts[0].accept(self)}, )\"\n return f\"({', '.join(child.accept(self) for child in node.elts)})\"\n \n+ def visit_typealias(self, node: nodes.TypeAlias) -> str:\n+ \"\"\"return an astroid.TypeAlias node as string\"\"\"\n+ return node.name.accept(self) if node.name else \"_\"\n+\n+ def visit_typevar(self, node: nodes.TypeVar) -> str:\n+ \"\"\"return an astroid.TypeVar node as string\"\"\"\n+ return node.name.accept(self) if node.name else \"_\"\n+\n+ def visit_typevartuple(self, node: nodes.TypeVarTuple) -> str:\n+ \"\"\"return an astroid.TypeVarTuple node as string\"\"\"\n+ return \"*\" + node.name.accept(self) if node.name else \"\"\n+\n def visit_unaryop(self, node) -> str:\n \"\"\"return an astroid.UnaryOp node as string\"\"\"\n if node.op == \"not\":\ndiff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py\n--- a/astroid/nodes/node_classes.py\n+++ b/astroid/nodes/node_classes.py\n@@ -19,7 +19,6 @@\n ClassVar,\n Literal,\n Optional,\n- TypeVar,\n Union,\n )\n \n@@ -62,8 +61,8 @@ def _is_const(value) -> bool:\n return isinstance(value, tuple(CONST_CLS))\n \n \n-_NodesT = TypeVar(\"_NodesT\", bound=NodeNG)\n-_BadOpMessageT = TypeVar(\"_BadOpMessageT\", bound=util.BadOperationMessage)\n+_NodesT = typing.TypeVar(\"_NodesT\", bound=NodeNG)\n+_BadOpMessageT = typing.TypeVar(\"_BadOpMessageT\", bound=util.BadOperationMessage)\n \n AssignedStmtsPossibleNode = Union[\"List\", \"Tuple\", \"AssignName\", \"AssignAttr\", None]\n AssignedStmtsCall = Callable[\n@@ -2696,6 +2695,37 @@ def _infer_name(self, frame, name):\n return name\n \n \n+class ParamSpec(_base_nodes.AssignTypeNode):\n+ \"\"\"Class representing a :class:`ast.ParamSpec` node.\n+\n+ >>> import astroid\n+ >>> node = astroid.extract_node('type Alias[**P] = Callable[P, int]')\n+ >>> node.type_params[0]\n+ <ParamSpec l.1 at 0x7f23b2e4e198>\n+ \"\"\"\n+\n+ def __init__(\n+ self,\n+ lineno: int,\n+ col_offset: int,\n+ parent: NodeNG,\n+ *,\n+ end_lineno: int | None = None,\n+ end_col_offset: int | None = None,\n+ ) -> None:\n+ self.name: AssignName | None\n+ super().__init__(\n+ lineno=lineno,\n+ col_offset=col_offset,\n+ end_lineno=end_lineno,\n+ end_col_offset=end_col_offset,\n+ parent=parent,\n+ )\n+\n+ def postinit(self, *, name: AssignName | None) -> None:\n+ self.name = name\n+\n+\n class Pass(_base_nodes.NoChildrenNode, _base_nodes.Statement):\n \"\"\"Class representing an :class:`ast.Pass` node.\n \n@@ -3310,6 +3340,115 @@ def getitem(self, index, context: InferenceContext | None = None):\n return _container_getitem(self, self.elts, index, context=context)\n \n \n+class TypeAlias(_base_nodes.AssignTypeNode):\n+ \"\"\"Class representing a :class:`ast.TypeAlias` node.\n+\n+ >>> import astroid\n+ >>> node = astroid.extract_node('type Point = tuple[float, float]')\n+ >>> node\n+ <TypeAlias l.1 at 0x7f23b2e4e198>\n+ \"\"\"\n+\n+ _astroid_fields = (\"type_params\", \"value\")\n+\n+ def __init__(\n+ self,\n+ lineno: int,\n+ col_offset: int,\n+ parent: NodeNG,\n+ *,\n+ end_lineno: int | None = None,\n+ end_col_offset: int | None = None,\n+ ) -> None:\n+ self.name: AssignName | None\n+ self.type_params: list[TypeVar, ParamSpec, TypeVarTuple]\n+ self.value: NodeNG\n+ super().__init__(\n+ lineno=lineno,\n+ col_offset=col_offset,\n+ end_lineno=end_lineno,\n+ end_col_offset=end_col_offset,\n+ parent=parent,\n+ )\n+\n+ def postinit(\n+ self,\n+ *,\n+ name: AssignName | None,\n+ type_params: list[TypeVar, ParamSpec, TypeVarTuple],\n+ value: NodeNG,\n+ ) -> None:\n+ self.name = name\n+ self.type_params = type_params\n+ self.value = value\n+\n+\n+class TypeVar(_base_nodes.AssignTypeNode):\n+ \"\"\"Class representing a :class:`ast.TypeVar` node.\n+\n+ >>> import astroid\n+ >>> node = astroid.extract_node('type Point[T] = tuple[float, float]')\n+ >>> node.type_params[0]\n+ <TypeVar l.1 at 0x7f23b2e4e198>\n+ \"\"\"\n+\n+ _astroid_fields = (\"bound\",)\n+\n+ def __init__(\n+ self,\n+ lineno: int,\n+ col_offset: int,\n+ parent: NodeNG,\n+ *,\n+ end_lineno: int | None = None,\n+ end_col_offset: int | None = None,\n+ ) -> None:\n+ self.name: AssignName | None\n+ self.bound: NodeNG | None\n+ super().__init__(\n+ lineno=lineno,\n+ col_offset=col_offset,\n+ end_lineno=end_lineno,\n+ end_col_offset=end_col_offset,\n+ parent=parent,\n+ )\n+\n+ def postinit(self, *, name: AssignName | None, bound: NodeNG | None) -> None:\n+ self.name = name\n+ self.bound = bound\n+\n+\n+class TypeVarTuple(_base_nodes.AssignTypeNode):\n+ \"\"\"Class representing a :class:`ast.TypeVarTuple` node.\n+\n+ >>> import astroid\n+ >>> node = astroid.extract_node('type Alias[*Ts] = tuple[*Ts]')\n+ >>> node.type_params[0]\n+ <TypeVarTuple l.1 at 0x7f23b2e4e198>\n+ \"\"\"\n+\n+ def __init__(\n+ self,\n+ lineno: int,\n+ col_offset: int,\n+ parent: NodeNG,\n+ *,\n+ end_lineno: int | None = None,\n+ end_col_offset: int | None = None,\n+ ) -> None:\n+ self.name: AssignName | None\n+ super().__init__(\n+ lineno=lineno,\n+ col_offset=col_offset,\n+ end_lineno=end_lineno,\n+ end_col_offset=end_col_offset,\n+ parent=parent,\n+ )\n+\n+ def postinit(self, *, name: AssignName | None) -> None:\n+ self.name = name\n+\n+\n class UnaryOp(NodeNG):\n \"\"\"Class representing an :class:`ast.UnaryOp` node.\n \ndiff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py\n--- a/astroid/nodes/scoped_nodes/scoped_nodes.py\n+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py\n@@ -1055,7 +1055,14 @@ class FunctionDef(\n <FunctionDef.my_func l.2 at 0x7f23b2e71e10>\n \"\"\"\n \n- _astroid_fields = (\"decorators\", \"args\", \"returns\", \"doc_node\", \"body\")\n+ _astroid_fields = (\n+ \"decorators\",\n+ \"args\",\n+ \"returns\",\n+ \"type_params\",\n+ \"doc_node\",\n+ \"body\",\n+ )\n _multi_line_block_fields = (\"body\",)\n returns = None\n \n@@ -1123,6 +1130,9 @@ def __init__(\n self.body: list[NodeNG] = []\n \"\"\"The contents of the function body.\"\"\"\n \n+ self.type_params: list[nodes.TypeVar, nodes.ParamSpec, nodes.TypeVarTuple] = []\n+ \"\"\"PEP 695 (Python 3.12+) type params, e.g. first 'T' in def func[T]() -> T: ...\"\"\"\n+\n self.instance_attrs: dict[str, list[NodeNG]] = {}\n \n super().__init__(\n@@ -1147,6 +1157,7 @@ def postinit(\n *,\n position: Position | None = None,\n doc_node: Const | None = None,\n+ type_params: list[nodes.TypeVar] | None = None,\n ):\n \"\"\"Do some setup after initialisation.\n \n@@ -1164,6 +1175,8 @@ def postinit(\n Position of function keyword(s) and name.\n :param doc_node:\n The doc node associated with this node.\n+ :param type_params:\n+ The type_params associated with this node.\n \"\"\"\n self.args = args\n self.body = body\n@@ -1173,6 +1186,7 @@ def postinit(\n self.type_comment_args = type_comment_args\n self.position = position\n self.doc_node = doc_node\n+ self.type_params = type_params or []\n \n @cached_property\n def extra_decorators(self) -> list[node_classes.Call]:\n@@ -1739,7 +1753,7 @@ def get_wrapping_class(node):\n return klass\n \n \n-class ClassDef(\n+class ClassDef( # pylint: disable=too-many-instance-attributes\n _base_nodes.FilterStmtsBaseNode, LocalsDictNodeNG, _base_nodes.Statement\n ):\n \"\"\"Class representing an :class:`ast.ClassDef` node.\n@@ -1758,7 +1772,14 @@ def my_meth(self, arg):\n # by a raw factories\n \n # a dictionary of class instances attributes\n- _astroid_fields = (\"decorators\", \"bases\", \"keywords\", \"doc_node\", \"body\") # name\n+ _astroid_fields = (\n+ \"decorators\",\n+ \"bases\",\n+ \"keywords\",\n+ \"doc_node\",\n+ \"body\",\n+ \"type_params\",\n+ ) # name\n \n decorators = None\n \"\"\"The decorators that are applied to this class.\n@@ -1825,6 +1846,9 @@ def __init__(\n self.is_dataclass: bool = False\n \"\"\"Whether this class is a dataclass.\"\"\"\n \n+ self.type_params: list[nodes.TypeVar, nodes.ParamSpec, nodes.TypeVarTuple] = []\n+ \"\"\"PEP 695 (Python 3.12+) type params, e.g. class MyClass[T]: ...\"\"\"\n+\n super().__init__(\n lineno=lineno,\n col_offset=col_offset,\n@@ -1866,6 +1890,7 @@ def postinit(\n *,\n position: Position | None = None,\n doc_node: Const | None = None,\n+ type_params: list[nodes.TypeVar] | None = None,\n ) -> None:\n if keywords is not None:\n self.keywords = keywords\n@@ -1876,6 +1901,7 @@ def postinit(\n self._metaclass = metaclass\n self.position = position\n self.doc_node = doc_node\n+ self.type_params = type_params or []\n \n def _newstyle_impl(self, context: InferenceContext | None = None):\n if context is None:\ndiff --git a/astroid/rebuilder.py b/astroid/rebuilder.py\n--- a/astroid/rebuilder.py\n+++ b/astroid/rebuilder.py\n@@ -18,7 +18,7 @@\n \n from astroid import nodes\n from astroid._ast import ParserModule, get_parser_module, parse_function_type_comment\n-from astroid.const import IS_PYPY, PY38, PY39_PLUS, Context\n+from astroid.const import IS_PYPY, PY38, PY39_PLUS, PY312_PLUS, Context\n from astroid.manager import AstroidManager\n from astroid.nodes import NodeNG\n from astroid.nodes.utils import Position\n@@ -384,6 +384,12 @@ def visit(self, node: ast.Nonlocal, parent: NodeNG) -> nodes.Nonlocal:\n def visit(self, node: ast.Constant, parent: NodeNG) -> nodes.Const:\n ...\n \n+ if sys.version_info >= (3, 12):\n+\n+ @overload\n+ def visit(self, node: ast.ParamSpec, parent: NodeNG) -> nodes.ParamSpec:\n+ ...\n+\n @overload\n def visit(self, node: ast.Pass, parent: NodeNG) -> nodes.Pass:\n ...\n@@ -432,6 +438,22 @@ def visit(self, node: ast.TryStar, parent: NodeNG) -> nodes.TryStar:\n def visit(self, node: ast.Tuple, parent: NodeNG) -> nodes.Tuple:\n ...\n \n+ if sys.version_info >= (3, 12):\n+\n+ @overload\n+ def visit(self, node: ast.TypeAlias, parent: NodeNG) -> nodes.TypeAlias:\n+ ...\n+\n+ @overload\n+ def visit(self, node: ast.TypeVar, parent: NodeNG) -> nodes.TypeVar:\n+ ...\n+\n+ @overload\n+ def visit(\n+ self, node: ast.TypeVarTuple, parent: NodeNG\n+ ) -> nodes.TypeVarTuple:\n+ ...\n+\n @overload\n def visit(self, node: ast.UnaryOp, parent: NodeNG) -> nodes.UnaryOp:\n ...\n@@ -870,6 +892,9 @@ def visit_classdef(\n ],\n position=self._get_position_info(node, newnode),\n doc_node=self.visit(doc_ast_node, newnode),\n+ type_params=[self.visit(param, newnode) for param in node.type_params]\n+ if PY312_PLUS\n+ else [],\n )\n return newnode\n \n@@ -1170,6 +1195,9 @@ def _visit_functiondef(\n type_comment_args=type_comment_args,\n position=self._get_position_info(node, newnode),\n doc_node=self.visit(doc_ast_node, newnode),\n+ type_params=[self.visit(param, newnode) for param in node.type_params]\n+ if PY312_PLUS\n+ else [],\n )\n self._global_names.pop()\n return newnode\n@@ -1477,6 +1505,20 @@ def visit_constant(self, node: ast.Constant, parent: NodeNG) -> nodes.Const:\n parent=parent,\n )\n \n+ def visit_paramspec(self, node: ast.ParamSpec, parent: NodeNG) -> nodes.ParamSpec:\n+ \"\"\"Visit a ParamSpec node by returning a fresh instance of it.\"\"\"\n+ newnode = nodes.ParamSpec(\n+ lineno=node.lineno,\n+ col_offset=node.col_offset,\n+ end_lineno=node.end_lineno,\n+ end_col_offset=node.end_col_offset,\n+ parent=parent,\n+ )\n+ # Add AssignName node for 'node.name'\n+ # https://bugs.python.org/issue43994\n+ newnode.postinit(name=self.visit_assignname(node, newnode, node.name))\n+ return newnode\n+\n def visit_pass(self, node: ast.Pass, parent: NodeNG) -> nodes.Pass:\n \"\"\"Visit a Pass node by returning a fresh instance of it.\"\"\"\n return nodes.Pass(\n@@ -1669,6 +1711,55 @@ def visit_tuple(self, node: ast.Tuple, parent: NodeNG) -> nodes.Tuple:\n newnode.postinit([self.visit(child, newnode) for child in node.elts])\n return newnode\n \n+ def visit_typealias(self, node: ast.TypeAlias, parent: NodeNG) -> nodes.TypeAlias:\n+ \"\"\"Visit a TypeAlias node by returning a fresh instance of it.\"\"\"\n+ newnode = nodes.TypeAlias(\n+ lineno=node.lineno,\n+ col_offset=node.col_offset,\n+ end_lineno=node.end_lineno,\n+ end_col_offset=node.end_col_offset,\n+ parent=parent,\n+ )\n+ newnode.postinit(\n+ name=self.visit(node.name, newnode),\n+ type_params=[self.visit(p, newnode) for p in node.type_params],\n+ value=self.visit(node.value, newnode),\n+ )\n+ return newnode\n+\n+ def visit_typevar(self, node: ast.TypeVar, parent: NodeNG) -> nodes.TypeVar:\n+ \"\"\"Visit a TypeVar node by returning a fresh instance of it.\"\"\"\n+ newnode = nodes.TypeVar(\n+ lineno=node.lineno,\n+ col_offset=node.col_offset,\n+ end_lineno=node.end_lineno,\n+ end_col_offset=node.end_col_offset,\n+ parent=parent,\n+ )\n+ # Add AssignName node for 'node.name'\n+ # https://bugs.python.org/issue43994\n+ newnode.postinit(\n+ name=self.visit_assignname(node, newnode, node.name),\n+ bound=self.visit(node.bound, newnode),\n+ )\n+ return newnode\n+\n+ def visit_typevartuple(\n+ self, node: ast.TypeVarTuple, parent: NodeNG\n+ ) -> nodes.TypeVarTuple:\n+ \"\"\"Visit a TypeVarTuple node by returning a fresh instance of it.\"\"\"\n+ newnode = nodes.TypeVarTuple(\n+ lineno=node.lineno,\n+ col_offset=node.col_offset,\n+ end_lineno=node.end_lineno,\n+ end_col_offset=node.end_col_offset,\n+ parent=parent,\n+ )\n+ # Add AssignName node for 'node.name'\n+ # https://bugs.python.org/issue43994\n+ newnode.postinit(name=self.visit_assignname(node, newnode, node.name))\n+ return newnode\n+\n def visit_unaryop(self, node: ast.UnaryOp, parent: NodeNG) -> nodes.UnaryOp:\n \"\"\"Visit a UnaryOp node by returning a fresh instance of it.\"\"\"\n newnode = nodes.UnaryOp(\n", "test_patch": "diff --git a/tests/brain/test_brain.py b/tests/brain/test_brain.py\n--- a/tests/brain/test_brain.py\n+++ b/tests/brain/test_brain.py\n@@ -15,6 +15,7 @@\n from astroid import MANAGER, builder, nodes, objects, test_utils, util\n from astroid.bases import Instance\n from astroid.brain.brain_namedtuple_enum import _get_namedtuple_fields\n+from astroid.const import PY312_PLUS\n from astroid.exceptions import (\n AttributeInferenceError,\n InferenceError,\n@@ -186,9 +187,16 @@ def test_builtin_subscriptable(self):\n \n \n def check_metaclass_is_abc(node: nodes.ClassDef):\n- meta = node.metaclass()\n- assert isinstance(meta, nodes.ClassDef)\n- assert meta.name == \"ABCMeta\"\n+ if PY312_PLUS and node.name == \"ByteString\":\n+ # .metaclass() finds the first metaclass in the mro(),\n+ # which, from 3.12, is _DeprecateByteStringMeta (unhelpful)\n+ # until ByteString is removed in 3.14.\n+ # Jump over the first two ByteString classes in the mro().\n+ check_metaclass_is_abc(node.mro()[2])\n+ else:\n+ meta = node.metaclass()\n+ assert isinstance(meta, nodes.ClassDef)\n+ assert meta.name == \"ABCMeta\"\n \n \n class CollectionsBrain(unittest.TestCase):\n@@ -323,7 +331,7 @@ def test_collections_object_not_yet_subscriptable_2(self):\n \n @test_utils.require_version(minver=\"3.9\")\n def test_collections_object_subscriptable_3(self):\n- \"\"\"With Python 3.9 the ByteString class of the collections module is subscritable\n+ \"\"\"With Python 3.9 the ByteString class of the collections module is subscriptable\n (but not the same class from typing module)\"\"\"\n right_node = builder.extract_node(\n \"\"\"\ndiff --git a/tests/brain/test_qt.py b/tests/brain/test_qt.py\n--- a/tests/brain/test_qt.py\n+++ b/tests/brain/test_qt.py\n@@ -8,6 +8,7 @@\n \n from astroid import Uninferable, extract_node\n from astroid.bases import UnboundMethod\n+from astroid.const import PY312_PLUS\n from astroid.manager import AstroidManager\n from astroid.nodes import FunctionDef\n \n@@ -15,6 +16,8 @@\n \n \n @pytest.mark.skipif(HAS_PYQT6 is None, reason=\"These tests require the PyQt6 library.\")\n+# TODO: enable for Python 3.12 as soon as PyQt6 release is compatible\[email protected](PY312_PLUS, reason=\"This test was segfaulting with Python 3.12.\")\n class TestBrainQt:\n AstroidManager.brain[\"extension_package_whitelist\"] = {\"PyQt6\"}\n \ndiff --git a/tests/test_inference.py b/tests/test_inference.py\n--- a/tests/test_inference.py\n+++ b/tests/test_inference.py\n@@ -6,6 +6,7 @@\n \n from __future__ import annotations\n \n+import sys\n import textwrap\n import unittest\n from abc import ABCMeta\n@@ -32,7 +33,7 @@\n from astroid.arguments import CallSite\n from astroid.bases import BoundMethod, Instance, UnboundMethod, UnionType\n from astroid.builder import AstroidBuilder, _extract_single_node, extract_node, parse\n-from astroid.const import IS_PYPY, PY39_PLUS, PY310_PLUS\n+from astroid.const import IS_PYPY, PY39_PLUS, PY310_PLUS, PY312_PLUS\n from astroid.context import CallContext, InferenceContext\n from astroid.exceptions import (\n AstroidTypeError,\n@@ -988,7 +989,12 @@ def test_import_as(self) -> None:\n self.assertIsInstance(inferred[0], nodes.Module)\n self.assertEqual(inferred[0].name, \"os.path\")\n inferred = list(ast.igetattr(\"e\"))\n- self.assertEqual(len(inferred), 1)\n+ if PY312_PLUS and sys.platform.startswith(\"win\"):\n+ # There are two os.path.exists exported, likely due to\n+ # https://github.com/python/cpython/pull/101324\n+ self.assertEqual(len(inferred), 2)\n+ else:\n+ self.assertEqual(len(inferred), 1)\n self.assertIsInstance(inferred[0], nodes.FunctionDef)\n self.assertEqual(inferred[0].name, \"exists\")\n \ndiff --git a/tests/test_nodes.py b/tests/test_nodes.py\n--- a/tests/test_nodes.py\n+++ b/tests/test_nodes.py\n@@ -28,7 +28,7 @@\n transforms,\n util,\n )\n-from astroid.const import PY310_PLUS, Context\n+from astroid.const import PY310_PLUS, PY312_PLUS, Context\n from astroid.context import InferenceContext\n from astroid.exceptions import (\n AstroidBuildingError,\n@@ -279,6 +279,33 @@ def test_as_string_unknown() -> None:\n assert nodes.Unknown(lineno=1, col_offset=0).as_string() == \"Unknown.Unknown()\"\n \n \[email protected](not PY312_PLUS, reason=\"Uses 3.12 type param nodes\")\n+class AsStringTypeParamNodes(unittest.TestCase):\n+ @staticmethod\n+ def test_as_string_type_alias() -> None:\n+ ast = abuilder.string_build(\"type Point = tuple[float, float]\")\n+ type_alias = ast.body[0]\n+ assert type_alias.as_string().strip() == \"Point\"\n+\n+ @staticmethod\n+ def test_as_string_type_var() -> None:\n+ ast = abuilder.string_build(\"type Point[T] = tuple[float, float]\")\n+ type_var = ast.body[0].type_params[0]\n+ assert type_var.as_string().strip() == \"T\"\n+\n+ @staticmethod\n+ def test_as_string_type_var_tuple() -> None:\n+ ast = abuilder.string_build(\"type Alias[*Ts] = tuple[*Ts]\")\n+ type_var_tuple = ast.body[0].type_params[0]\n+ assert type_var_tuple.as_string().strip() == \"*Ts\"\n+\n+ @staticmethod\n+ def test_as_string_param_spec() -> None:\n+ ast = abuilder.string_build(\"type Alias[**P] = Callable[P, int]\")\n+ param_spec = ast.body[0].type_params[0]\n+ assert param_spec.as_string().strip() == \"P\"\n+\n+\n class _NodeTest(unittest.TestCase):\n \"\"\"Test transformation of If Node.\"\"\"\n \ndiff --git a/tests/test_nodes_lineno.py b/tests/test_nodes_lineno.py\n--- a/tests/test_nodes_lineno.py\n+++ b/tests/test_nodes_lineno.py\n@@ -8,7 +8,7 @@\n \n import astroid\n from astroid import builder, nodes\n-from astroid.const import IS_PYPY, PY38, PY39_PLUS, PY310_PLUS\n+from astroid.const import IS_PYPY, PY38, PY39_PLUS, PY310_PLUS, PY312_PLUS\n \n \n @pytest.mark.skipif(\n@@ -977,13 +977,24 @@ def test_end_lineno_string() -> None:\n assert isinstance(s1.values[0], nodes.Const)\n assert (s1.lineno, s1.col_offset) == (1, 0)\n assert (s1.end_lineno, s1.end_col_offset) == (1, 29)\n- assert (s1.values[0].lineno, s1.values[0].col_offset) == (1, 0)\n- assert (s1.values[0].end_lineno, s1.values[0].end_col_offset) == (1, 29)\n+ if PY312_PLUS:\n+ assert (s1.values[0].lineno, s1.values[0].col_offset) == (1, 2)\n+ assert (s1.values[0].end_lineno, s1.values[0].end_col_offset) == (1, 15)\n+ else:\n+ # Bug in Python 3.11\n+ # https://github.com/python/cpython/issues/81639\n+ assert (s1.values[0].lineno, s1.values[0].col_offset) == (1, 0)\n+ assert (s1.values[0].end_lineno, s1.values[0].end_col_offset) == (1, 29)\n \n s2 = s1.values[1]\n assert isinstance(s2, nodes.FormattedValue)\n- assert (s2.lineno, s2.col_offset) == (1, 0)\n- assert (s2.end_lineno, s2.end_col_offset) == (1, 29)\n+ if PY312_PLUS:\n+ assert (s2.lineno, s2.col_offset) == (1, 15)\n+ assert (s2.end_lineno, s2.end_col_offset) == (1, 28)\n+ else:\n+ assert (s2.lineno, s2.col_offset) == (1, 0)\n+ assert (s2.end_lineno, s2.end_col_offset) == (1, 29)\n+\n assert isinstance(s2.value, nodes.Const) # 42.1234\n if PY39_PLUS:\n assert (s2.value.lineno, s2.value.col_offset) == (1, 16)\n@@ -993,22 +1004,35 @@ def test_end_lineno_string() -> None:\n # https://bugs.python.org/issue44885\n assert (s2.value.lineno, s2.value.col_offset) == (1, 1)\n assert (s2.value.end_lineno, s2.value.end_col_offset) == (1, 8)\n- assert isinstance(s2.format_spec, nodes.JoinedStr) # '02d'\n- assert (s2.format_spec.lineno, s2.format_spec.col_offset) == (1, 0)\n- assert (s2.format_spec.end_lineno, s2.format_spec.end_col_offset) == (1, 29)\n+ assert isinstance(s2.format_spec, nodes.JoinedStr) # ':02d'\n+ if PY312_PLUS:\n+ assert (s2.format_spec.lineno, s2.format_spec.col_offset) == (1, 23)\n+ assert (s2.format_spec.end_lineno, s2.format_spec.end_col_offset) == (1, 27)\n+ else:\n+ assert (s2.format_spec.lineno, s2.format_spec.col_offset) == (1, 0)\n+ assert (s2.format_spec.end_lineno, s2.format_spec.end_col_offset) == (1, 29)\n \n s3 = ast_nodes[1]\n assert isinstance(s3, nodes.JoinedStr)\n assert isinstance(s3.values[0], nodes.Const)\n assert (s3.lineno, s3.col_offset) == (2, 0)\n assert (s3.end_lineno, s3.end_col_offset) == (2, 17)\n- assert (s3.values[0].lineno, s3.values[0].col_offset) == (2, 0)\n- assert (s3.values[0].end_lineno, s3.values[0].end_col_offset) == (2, 17)\n+ if PY312_PLUS:\n+ assert (s3.values[0].lineno, s3.values[0].col_offset) == (2, 2)\n+ assert (s3.values[0].end_lineno, s3.values[0].end_col_offset) == (2, 15)\n+ else:\n+ assert (s3.values[0].lineno, s3.values[0].col_offset) == (2, 0)\n+ assert (s3.values[0].end_lineno, s3.values[0].end_col_offset) == (2, 17)\n \n s4 = s3.values[1]\n assert isinstance(s4, nodes.FormattedValue)\n- assert (s4.lineno, s4.col_offset) == (2, 0)\n- assert (s4.end_lineno, s4.end_col_offset) == (2, 17)\n+ if PY312_PLUS:\n+ assert (s4.lineno, s4.col_offset) == (2, 9)\n+ assert (s4.end_lineno, s4.end_col_offset) == (2, 16)\n+ else:\n+ assert (s4.lineno, s4.col_offset) == (2, 0)\n+ assert (s4.end_lineno, s4.end_col_offset) == (2, 17)\n+\n assert isinstance(s4.value, nodes.Name) # 'name'\n if PY39_PLUS:\n assert (s4.value.lineno, s4.value.col_offset) == (2, 10)\ndiff --git a/tests/test_raw_building.py b/tests/test_raw_building.py\n--- a/tests/test_raw_building.py\n+++ b/tests/test_raw_building.py\n@@ -24,7 +24,7 @@\n import tests.testdata.python3.data.fake_module_with_broken_getattr as fm_getattr\n import tests.testdata.python3.data.fake_module_with_warnings as fm\n from astroid.builder import AstroidBuilder\n-from astroid.const import IS_PYPY\n+from astroid.const import IS_PYPY, PY312_PLUS\n from astroid.raw_building import (\n attach_dummy_node,\n build_class,\n@@ -86,7 +86,7 @@ def test_build_from_import(self) -> None:\n \n @unittest.skipIf(IS_PYPY, \"Only affects CPython\")\n def test_io_is__io(self):\n- # _io module calls itself io. This leads\n+ # _io module calls itself io before Python 3.12. This leads\n # to cyclic dependencies when astroid tries to resolve\n # what io.BufferedReader is. The code that handles this\n # is in astroid.raw_building.imported_member, which verifies\n@@ -94,7 +94,8 @@ def test_io_is__io(self):\n builder = AstroidBuilder()\n module = builder.inspect_build(_io)\n buffered_reader = module.getattr(\"BufferedReader\")[0]\n- self.assertEqual(buffered_reader.root().name, \"io\")\n+ expected = \"_io\" if PY312_PLUS else \"io\"\n+ self.assertEqual(buffered_reader.root().name, expected)\n \n def test_build_function_deepinspect_deprecation(self) -> None:\n # Tests https://github.com/pylint-dev/astroid/issues/1717\ndiff --git a/tests/test_scoped_nodes.py b/tests/test_scoped_nodes.py\n--- a/tests/test_scoped_nodes.py\n+++ b/tests/test_scoped_nodes.py\n@@ -8,7 +8,7 @@\n \n from __future__ import annotations\n \n-import datetime\n+import difflib\n import os\n import sys\n import textwrap\n@@ -2141,8 +2141,8 @@ class ParentGetattr(Getattr):\n # Test that objects analyzed through the live introspection\n # aren't considered to have dynamic getattr implemented.\n astroid_builder = builder.AstroidBuilder()\n- module = astroid_builder.module_build(datetime)\n- self.assertFalse(module[\"timedelta\"].has_dynamic_getattr())\n+ module = astroid_builder.module_build(difflib)\n+ self.assertFalse(module[\"SequenceMatcher\"].has_dynamic_getattr())\n \n def test_duplicate_bases_namedtuple(self) -> None:\n module = builder.parse(\ndiff --git a/tests/test_type_params.py b/tests/test_type_params.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/test_type_params.py\n@@ -0,0 +1,68 @@\n+# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n+# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE\n+# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt\n+\n+import pytest\n+\n+from astroid import extract_node\n+from astroid.const import PY312_PLUS\n+from astroid.nodes import (\n+ AssignName,\n+ ParamSpec,\n+ Subscript,\n+ TypeAlias,\n+ TypeVar,\n+ TypeVarTuple,\n+)\n+\n+if not PY312_PLUS:\n+ pytest.skip(\"Requires Python 3.12 or higher\", allow_module_level=True)\n+\n+\n+def test_type_alias() -> None:\n+ node = extract_node(\"type Point[T] = list[float, float]\")\n+ assert isinstance(node, TypeAlias)\n+ assert isinstance(node.type_params[0], TypeVar)\n+ assert isinstance(node.type_params[0].name, AssignName)\n+ assert node.type_params[0].name.name == \"T\"\n+ assert node.type_params[0].bound is None\n+\n+ assert isinstance(node.value, Subscript)\n+ assert node.value.value.name == \"list\"\n+ assert node.value.slice.name == \"tuple\"\n+ assert all(elt.name == \"float\" for elt in node.value.slice.elts)\n+\n+ assert node.inferred()[0] is node\n+ assert node.type_params[0].inferred()[0] is node.type_params[0]\n+\n+\n+def test_type_param_spec() -> None:\n+ node = extract_node(\"type Alias[**P] = Callable[P, int]\")\n+ params = node.type_params[0]\n+ assert isinstance(params, ParamSpec)\n+ assert isinstance(params.name, AssignName)\n+ assert params.name.name == \"P\"\n+\n+ assert node.inferred()[0] is node\n+\n+\n+def test_type_var_tuple() -> None:\n+ node = extract_node(\"type Alias[*Ts] = tuple[*Ts]\")\n+ params = node.type_params[0]\n+ assert isinstance(params, TypeVarTuple)\n+ assert isinstance(params.name, AssignName)\n+ assert params.name.name == \"Ts\"\n+\n+ assert node.inferred()[0] is node\n+\n+\n+def test_type_param() -> None:\n+ func_node = extract_node(\"def func[T]() -> T: ...\")\n+ assert isinstance(func_node.type_params[0], TypeVar)\n+ assert func_node.type_params[0].name.name == \"T\"\n+ assert func_node.type_params[0].bound is None\n+\n+ class_node = extract_node(\"class MyClass[T]: ...\")\n+ assert isinstance(class_node.type_params[0], TypeVar)\n+ assert class_node.type_params[0].name.name == \"T\"\n+ assert class_node.type_params[0].bound is None\n", "problem_statement": "Implement new nodes for PEP 695: Type Parameter Syntax\nThere's a new syntax in python 3.12, we need to handle it before claiming we support 3.12, see https://docs.python.org/3.12/whatsnew/3.12.html#pep-695-type-parameter-syntax\n", "hints_text": "", "created_at": "2023-06-22T03:00:19Z", "version": "3.0", "FAIL_TO_PASS": ["tests/brain/test_brain.py::CollectionsDequeTests::test_deque", "tests/brain/test_brain.py::CollectionsDequeTests::test_deque_py35methods", "tests/brain/test_brain.py::CollectionsDequeTests::test_deque_py39methods", "tests/brain/test_brain.py::OrderedDictTest::test_ordered_dict_py34method", "tests/brain/test_brain.py::DefaultDictTest::test_1", "tests/brain/test_brain.py::ModuleExtenderTest::test_extension_modules", "tests/brain/test_brain.py::TypeBrain::test_builtin_subscriptable", "tests/brain/test_brain.py::TypeBrain::test_invalid_type_subscript", "tests/brain/test_brain.py::TypeBrain::test_type_subscript", "tests/brain/test_brain.py::CollectionsBrain::test_collections_object_not_subscriptable", "tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable", "tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable_2", "tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable_3", "tests/brain/test_brain.py::CollectionsBrain::test_collections_object_subscriptable_4", "tests/brain/test_brain.py::TypingBrain::test_callable_type", "tests/brain/test_brain.py::TypingBrain::test_collections_generic_alias_slots", "tests/brain/test_brain.py::TypingBrain::test_has_dunder_args", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_base", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_bug_pylint_4383", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_can_correctly_access_methods", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_class_form", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_few_args", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_few_fields", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_inference", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_inference_nonliteral", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_inferred_as_class", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_instance_attrs", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_nested_class", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_simple", "tests/brain/test_brain.py::TypingBrain::test_namedtuple_uninferable_member", "tests/brain/test_brain.py::TypingBrain::test_tuple_type", "tests/brain/test_brain.py::TypingBrain::test_typed_dict", "tests/brain/test_brain.py::TypingBrain::test_typing_alias_type", "tests/brain/test_brain.py::TypingBrain::test_typing_alias_type_2", "tests/brain/test_brain.py::TypingBrain::test_typing_annotated_subscriptable", "tests/brain/test_brain.py::TypingBrain::test_typing_cast", "tests/brain/test_brain.py::TypingBrain::test_typing_cast_attribute", "tests/brain/test_brain.py::TypingBrain::test_typing_cast_multiple_inference_calls", "tests/brain/test_brain.py::TypingBrain::test_typing_generic_slots", "tests/brain/test_brain.py::TypingBrain::test_typing_generic_subscriptable", "tests/brain/test_brain.py::TypingBrain::test_typing_namedtuple_dont_crash_on_no_fields", "tests/brain/test_brain.py::TypingBrain::test_typing_no_duplicates", "tests/brain/test_brain.py::TypingBrain::test_typing_object_builtin_subscriptable", "tests/brain/test_brain.py::TypingBrain::test_typing_object_not_subscriptable", "tests/brain/test_brain.py::TypingBrain::test_typing_object_notsubscriptable_3", "tests/brain/test_brain.py::TypingBrain::test_typing_object_subscriptable", "tests/brain/test_brain.py::TypingBrain::test_typing_object_subscriptable_2", "tests/brain/test_brain.py::TypingBrain::test_typing_type_subscriptable", "tests/brain/test_brain.py::TypingBrain::test_typing_type_without_tip", "tests/brain/test_brain.py::TypingBrain::test_typing_types", "tests/brain/test_brain.py::ReBrainTest::test_re_pattern_subscriptable", "tests/brain/test_brain.py::ReBrainTest::test_regex_flags", "tests/brain/test_brain.py::BrainFStrings::test_no_crash_on_const_reconstruction", "tests/brain/test_brain.py::BrainNamedtupleAnnAssignTest::test_no_crash_on_ann_assign_in_namedtuple", "tests/brain/test_brain.py::BrainUUIDTest::test_uuid_has_int_member", "tests/brain/test_brain.py::RandomSampleTest::test_arguments_inferred_successfully", "tests/brain/test_brain.py::RandomSampleTest::test_inferred_successfully", "tests/brain/test_brain.py::RandomSampleTest::test_no_crash_on_evaluatedobject", "tests/brain/test_brain.py::SubprocessTest::test_popen_does_not_have_class_getitem", "tests/brain/test_brain.py::SubprocessTest::test_subprcess_check_output", "tests/brain/test_brain.py::SubprocessTest::test_subprocess_args", "tests/brain/test_brain.py::TestIsinstanceInference::test_type_type", "tests/brain/test_brain.py::TestIsinstanceInference::test_object_type", "tests/brain/test_brain.py::TestIsinstanceInference::test_type_object", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_int_true", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_int_false", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_object_true", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_object_true3", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_class_false", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_type_false", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_str_true", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_str_false", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_tuple_argument", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_type_false2", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_object_true2", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_type_true", "tests/brain/test_brain.py::TestIsinstanceInference::test_isinstance_edge_case", "tests/brain/test_brain.py::TestIsinstanceInference::test_uninferable_bad_type", "tests/brain/test_brain.py::TestIsinstanceInference::test_uninferable_keywords", "tests/brain/test_brain.py::TestIsinstanceInference::test_too_many_args", "tests/brain/test_brain.py::TestIsinstanceInference::test_first_param_is_uninferable", "tests/brain/test_brain.py::TestIssubclassBrain::test_type_type", "tests/brain/test_brain.py::TestIssubclassBrain::test_object_type", "tests/brain/test_brain.py::TestIssubclassBrain::test_type_object", "tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_same_class", "tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_not_the_same_class", "tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_object_true", "tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_same_user_defined_class", "tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_different_user_defined_classes", "tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_type_false", "tests/brain/test_brain.py::TestIssubclassBrain::test_isinstance_tuple_argument", "tests/brain/test_brain.py::TestIssubclassBrain::test_isinstance_object_true2", "tests/brain/test_brain.py::TestIssubclassBrain::test_issubclass_short_circuit", "tests/brain/test_brain.py::TestIssubclassBrain::test_uninferable_bad_type", "tests/brain/test_brain.py::TestIssubclassBrain::test_uninferable_keywords", "tests/brain/test_brain.py::TestIssubclassBrain::test_too_many_args", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_list", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_tuple", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_var", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_dict", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_set", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_object", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_class_with_metaclass", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_object_failure", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_string", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_generator_failure", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_failure_missing_variable", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_bytes", "tests/brain/test_brain.py::TestLenBuiltinInference::test_int_subclass_result", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_builtin_inference_attribute_error_str", "tests/brain/test_brain.py::TestLenBuiltinInference::test_len_builtin_inference_recursion_error_self_referential_attribute", "tests/brain/test_brain.py::test_infer_str", "tests/brain/test_brain.py::test_infer_int", "tests/brain/test_brain.py::test_infer_dict_from_keys", "tests/brain/test_brain.py::TestFunctoolsPartial::test_infer_partial", "tests/brain/test_brain.py::TestFunctoolsPartial::test_invalid_functools_partial_calls", "tests/brain/test_brain.py::TestFunctoolsPartial::test_inferred_partial_function_calls", "tests/brain/test_brain.py::TestFunctoolsPartial::test_partial_assignment", "tests/brain/test_brain.py::TestFunctoolsPartial::test_partial_does_not_affect_scope", "tests/brain/test_brain.py::TestFunctoolsPartial::test_multiple_partial_args", "tests/brain/test_brain.py::test_http_client_brain", "tests/brain/test_brain.py::test_http_status_brain", "tests/brain/test_brain.py::test_http_status_brain_iterable", "tests/brain/test_brain.py::test_oserror_model", "tests/brain/test_brain.py::test_crypt_brain", "tests/brain/test_brain.py::test_str_and_bytes['hey'.encode()-Const-]", "tests/brain/test_brain.py::test_str_and_bytes[b'hey'.decode()-Const-]", "tests/brain/test_brain.py::test_str_and_bytes['hey'.encode().decode()-Const-]", "tests/brain/test_brain.py::test_no_recursionerror_on_self_referential_length_check", "tests/brain/test_brain.py::test_inference_on_outer_referential_length_check", "tests/brain/test_brain.py::test_no_attributeerror_on_self_referential_length_check", "tests/test_inference.py::InferenceUtilsTest::test_path_wrapper", "tests/test_inference.py::InferenceTest::test__new__", "tests/test_inference.py::InferenceTest::test__new__bound_methods", "tests/test_inference.py::InferenceTest::test_advanced_tupleassign_name_inference1", "tests/test_inference.py::InferenceTest::test_advanced_tupleassign_name_inference2", "tests/test_inference.py::InferenceTest::test_ancestors_inference", "tests/test_inference.py::InferenceTest::test_ancestors_inference2", "tests/test_inference.py::InferenceTest::test_args_default_inference1", "tests/test_inference.py::InferenceTest::test_args_default_inference2", "tests/test_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented", "tests/test_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented_rop_fallback", "tests/test_inference.py::InferenceTest::test_aug_different_types_augop_implemented", "tests/test_inference.py::InferenceTest::test_aug_different_types_no_method_implemented", "tests/test_inference.py::InferenceTest::test_aug_op_same_type_aug_implemented", "tests/test_inference.py::InferenceTest::test_aug_op_same_type_aug_not_implemented_normal_implemented", "tests/test_inference.py::InferenceTest::test_aug_op_same_type_not_implemented", "tests/test_inference.py::InferenceTest::test_aug_op_subtype_aug_op_is_implemented", "tests/test_inference.py::InferenceTest::test_aug_op_subtype_both_not_implemented", "tests/test_inference.py::InferenceTest::test_aug_op_subtype_normal_op_is_implemented", "tests/test_inference.py::InferenceTest::test_augassign", "tests/test_inference.py::InferenceTest::test_augop_supertypes_augop_implemented", "tests/test_inference.py::InferenceTest::test_augop_supertypes_none_implemented", "tests/test_inference.py::InferenceTest::test_augop_supertypes_normal_binop_implemented", "tests/test_inference.py::InferenceTest::test_augop_supertypes_not_implemented_returned_for_all", "tests/test_inference.py::InferenceTest::test_augop_supertypes_reflected_binop_implemented", "tests/test_inference.py::InferenceTest::test_bin_op_classes", "tests/test_inference.py::InferenceTest::test_bin_op_supertype_more_complicated_example", "tests/test_inference.py::InferenceTest::test_binary_op_custom_class", "tests/test_inference.py::InferenceTest::test_binary_op_float_div", "tests/test_inference.py::InferenceTest::test_binary_op_int_add", "tests/test_inference.py::InferenceTest::test_binary_op_int_bitand", "tests/test_inference.py::InferenceTest::test_binary_op_int_bitor", "tests/test_inference.py::InferenceTest::test_binary_op_int_bitxor", "tests/test_inference.py::InferenceTest::test_binary_op_int_shiftleft", "tests/test_inference.py::InferenceTest::test_binary_op_int_shiftright", "tests/test_inference.py::InferenceTest::test_binary_op_int_sub", "tests/test_inference.py::InferenceTest::test_binary_op_list_mul", "tests/test_inference.py::InferenceTest::test_binary_op_list_mul_int", "tests/test_inference.py::InferenceTest::test_binary_op_list_mul_none", "tests/test_inference.py::InferenceTest::test_binary_op_not_used_in_boolean_context", "tests/test_inference.py::InferenceTest::test_binary_op_on_self", "tests/test_inference.py::InferenceTest::test_binary_op_or_union_type", "tests/test_inference.py::InferenceTest::test_binary_op_other_type", "tests/test_inference.py::InferenceTest::test_binary_op_other_type_using_reflected_operands", "tests/test_inference.py::InferenceTest::test_binary_op_reflected_and_not_implemented_is_type_error", "tests/test_inference.py::InferenceTest::test_binary_op_str_mul", "tests/test_inference.py::InferenceTest::test_binary_op_tuple_add", "tests/test_inference.py::InferenceTest::test_binary_op_type_errors", "tests/test_inference.py::InferenceTest::test_binop_ambiguity", "tests/test_inference.py::InferenceTest::test_binop_different_types_no_method_implemented", "tests/test_inference.py::InferenceTest::test_binop_different_types_normal_not_implemented_and_reflected", "tests/test_inference.py::InferenceTest::test_binop_different_types_reflected_and_normal_not_implemented", "tests/test_inference.py::InferenceTest::test_binop_different_types_reflected_only", "tests/test_inference.py::InferenceTest::test_binop_different_types_unknown_bases", "tests/test_inference.py::InferenceTest::test_binop_inference_errors", "tests/test_inference.py::InferenceTest::test_binop_list_with_elts", "tests/test_inference.py::InferenceTest::test_binop_same_types", "tests/test_inference.py::InferenceTest::test_binop_self_in_list", "tests/test_inference.py::InferenceTest::test_binop_subtype", "tests/test_inference.py::InferenceTest::test_binop_subtype_implemented_in_parent", "tests/test_inference.py::InferenceTest::test_binop_subtype_not_implemented", "tests/test_inference.py::InferenceTest::test_binop_supertype", "tests/test_inference.py::InferenceTest::test_binop_supertype_both_not_implemented", "tests/test_inference.py::InferenceTest::test_binop_supertype_rop_not_implemented", "tests/test_inference.py::InferenceTest::test_bool_value", "tests/test_inference.py::InferenceTest::test_bool_value_instances", "tests/test_inference.py::InferenceTest::test_bool_value_recursive", "tests/test_inference.py::InferenceTest::test_bool_value_variable", "tests/test_inference.py::InferenceTest::test_bound_method_inference", "tests/test_inference.py::InferenceTest::test_bt_ancestor_crash", "tests/test_inference.py::InferenceTest::test_builtin_help", "tests/test_inference.py::InferenceTest::test_builtin_inference_py3k", "tests/test_inference.py::InferenceTest::test_builtin_name_inference", "tests/test_inference.py::InferenceTest::test_builtin_new", "tests/test_inference.py::InferenceTest::test_builtin_open", "tests/test_inference.py::InferenceTest::test_builtin_types", "tests/test_inference.py::InferenceTest::test_bytes_subscript", "tests/test_inference.py::InferenceTest::test_callfunc_context_func", "tests/test_inference.py::InferenceTest::test_callfunc_context_lambda", "tests/test_inference.py::InferenceTest::test_callfunc_inference", "tests/test_inference.py::InferenceTest::test_class_inference", "tests/test_inference.py::InferenceTest::test_classmethod_inferred_by_context", "tests/test_inference.py::InferenceTest::test_context_call_for_context_managers", "tests/test_inference.py::InferenceTest::test_conversion_of_dict_methods", "tests/test_inference.py::InferenceTest::test_copy_method_inference", "tests/test_inference.py::InferenceTest::test_del1", "tests/test_inference.py::InferenceTest::test_del2", "tests/test_inference.py::InferenceTest::test_delayed_attributes_without_slots", "tests/test_inference.py::InferenceTest::test_dict_inference", "tests/test_inference.py::InferenceTest::test_dict_inference_for_multiple_starred", "tests/test_inference.py::InferenceTest::test_dict_inference_kwargs", "tests/test_inference.py::InferenceTest::test_dict_inference_unpack_repeated_key", "tests/test_inference.py::InferenceTest::test_dict_invalid_args", "tests/test_inference.py::InferenceTest::test_do_import_module_performance", "tests/test_inference.py::InferenceTest::test_exc_ancestors", "tests/test_inference.py::InferenceTest::test_except_inference", "tests/test_inference.py::InferenceTest::test_f_arg_f", "tests/test_inference.py::InferenceTest::test_factory_method", "tests/test_inference.py::InferenceTest::test_factory_methods_cls_call", "tests/test_inference.py::InferenceTest::test_factory_methods_object_new_call", "tests/test_inference.py::InferenceTest::test_float_complex_ambiguity", "tests/test_inference.py::InferenceTest::test_for_dict", "tests/test_inference.py::InferenceTest::test_frozenset_builtin_inference", "tests/test_inference.py::InferenceTest::test_function_inference", "tests/test_inference.py::InferenceTest::test_genexpr_bool_value", "tests/test_inference.py::InferenceTest::test_getattr_inference1", "tests/test_inference.py::InferenceTest::test_getattr_inference2", "tests/test_inference.py::InferenceTest::test_getattr_inference3", "tests/test_inference.py::InferenceTest::test_getattr_inference4", "tests/test_inference.py::InferenceTest::test_getitem_of_class_raised_type_error", "tests/test_inference.py::InferenceTest::test_im_func_unwrap", "tests/test_inference.py::InferenceTest::test_import_as", "tests/test_inference.py::InferenceTest::test_infer_abstract_property_return_values", "tests/test_inference.py::InferenceTest::test_infer_arg_called_object_when_used_as_index_is_uninferable", "tests/test_inference.py::InferenceTest::test_infer_arg_called_type_defined_in_outer_scope_is_uninferable", "tests/test_inference.py::InferenceTest::test_infer_arg_called_type_is_uninferable", "tests/test_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_index_is_uninferable", "tests/test_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_subscript_is_uninferable", "tests/test_inference.py::InferenceTest::test_infer_arguments", "tests/test_inference.py::InferenceTest::test_infer_call_result_crash", "tests/test_inference.py::InferenceTest::test_infer_call_result_invalid_dunder_call_on_instance", "tests/test_inference.py::InferenceTest::test_infer_call_result_with_metaclass", "tests/test_inference.py::InferenceTest::test_infer_cls_in_class_methods", "tests/test_inference.py::InferenceTest::test_infer_coercion_rules_for_floats_complex", "tests/test_inference.py::InferenceTest::test_infer_empty_nodes", "tests/test_inference.py::InferenceTest::test_infer_nested", "tests/test_inference.py::InferenceTest::test_infer_subclass_attr_inner_class", "tests/test_inference.py::InferenceTest::test_infer_subclass_attr_inner_class_works_indirectly", "tests/test_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr", "tests/test_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr_indirect", "tests/test_inference.py::InferenceTest::test_infer_subclass_attr_outer_class", "tests/test_inference.py::InferenceTest::test_infer_variable_arguments", "tests/test_inference.py::InferenceTest::test_inference_restrictions", "tests/test_inference.py::InferenceTest::test_inferring_context_manager_skip_index_error", "tests/test_inference.py::InferenceTest::test_inferring_context_manager_unpacking_inference_error", "tests/test_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager", "tests/test_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager_failures", "tests/test_inference.py::InferenceTest::test_inferring_with_statement", "tests/test_inference.py::InferenceTest::test_inferring_with_statement_failures", "tests/test_inference.py::InferenceTest::test_infinite_loop_for_decorators", "tests/test_inference.py::InferenceTest::test_inner_value_redefined_by_subclass", "tests/test_inference.py::InferenceTest::test_inner_value_redefined_by_subclass_with_mro", "tests/test_inference.py::InferenceTest::test_instance_binary_operations", "tests/test_inference.py::InferenceTest::test_instance_binary_operations_multiple_methods", "tests/test_inference.py::InferenceTest::test_instance_binary_operations_parent", "tests/test_inference.py::InferenceTest::test_instance_slicing", "tests/test_inference.py::InferenceTest::test_instance_slicing_fails", "tests/test_inference.py::InferenceTest::test_instance_slicing_slices", "tests/test_inference.py::InferenceTest::test_invalid_slicing_primaries", "tests/test_inference.py::InferenceTest::test_invalid_subscripts", "tests/test_inference.py::InferenceTest::test_lambda_as_methods", "tests/test_inference.py::InferenceTest::test_list_builtin_inference", "tests/test_inference.py::InferenceTest::test_list_inference", "tests/test_inference.py::InferenceTest::test_listassign_name_inference", "tests/test_inference.py::InferenceTest::test_lookup_cond_branches", "tests/test_inference.py::InferenceTest::test_matmul", "tests/test_inference.py::InferenceTest::test_metaclass__getitem__", "tests/test_inference.py::InferenceTest::test_metaclass_custom_dunder_call", "tests/test_inference.py::InferenceTest::test_metaclass_custom_dunder_call_boundnode", "tests/test_inference.py::InferenceTest::test_metaclass_subclasses_arguments_are_classes_not_instances", "tests/test_inference.py::InferenceTest::test_metaclass_with_keyword_args", "tests/test_inference.py::InferenceTest::test_method_argument", "tests/test_inference.py::InferenceTest::test_module_inference", "tests/test_inference.py::InferenceTest::test_mul_list_supports__index__", "tests/test_inference.py::InferenceTest::test_mulassign_inference", "tests/test_inference.py::InferenceTest::test_name_bool_value", "tests/test_inference.py::InferenceTest::test_nested_contextmanager", "tests/test_inference.py::InferenceTest::test_no_infinite_ancestor_loop", "tests/test_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference", "tests/test_inference.py::InferenceTest::test_nonregr_absolute_import", "tests/test_inference.py::InferenceTest::test_nonregr_func_arg", "tests/test_inference.py::InferenceTest::test_nonregr_func_global", "tests/test_inference.py::InferenceTest::test_nonregr_getitem_empty_tuple", "tests/test_inference.py::InferenceTest::test_nonregr_inference_modifying_col_offset", "tests/test_inference.py::InferenceTest::test_nonregr_instance_attrs", "tests/test_inference.py::InferenceTest::test_nonregr_lambda_arg", "tests/test_inference.py::InferenceTest::test_nonregr_layed_dictunpack", "tests/test_inference.py::InferenceTest::test_nonregr_multi_referential_addition", "tests/test_inference.py::InferenceTest::test_pluggable_inference", "tests/test_inference.py::InferenceTest::test_property", "tests/test_inference.py::InferenceTest::test_python25_no_relative_import", "tests/test_inference.py::InferenceTest::test_scope_lookup_same_attributes", "tests/test_inference.py::InferenceTest::test_set_builtin_inference", "tests/test_inference.py::InferenceTest::test_simple_for", "tests/test_inference.py::InferenceTest::test_simple_for_genexpr", "tests/test_inference.py::InferenceTest::test_simple_subscript", "tests/test_inference.py::InferenceTest::test_simple_tuple", "tests/test_inference.py::InferenceTest::test_slicing_list", "tests/test_inference.py::InferenceTest::test_slicing_str", "tests/test_inference.py::InferenceTest::test_slicing_tuple", "tests/test_inference.py::InferenceTest::test_special_method_masquerading_as_another", "tests/test_inference.py::InferenceTest::test_starred_in_list_literal", "tests/test_inference.py::InferenceTest::test_starred_in_literals_inference_issues", "tests/test_inference.py::InferenceTest::test_starred_in_mapping_inference_issues", "tests/test_inference.py::InferenceTest::test_starred_in_mapping_literal", "tests/test_inference.py::InferenceTest::test_starred_in_mapping_literal_no_inference_possible", "tests/test_inference.py::InferenceTest::test_starred_in_mapping_literal_non_const_keys_values", "tests/test_inference.py::InferenceTest::test_starred_in_set_literal", "tests/test_inference.py::InferenceTest::test_starred_in_tuple_literal", "tests/test_inference.py::InferenceTest::test_stop_iteration_leak", "tests/test_inference.py::InferenceTest::test_str_methods", "tests/test_inference.py::InferenceTest::test_string_interpolation", "tests/test_inference.py::InferenceTest::test_subscript_inference_error", "tests/test_inference.py::InferenceTest::test_subscript_multi_slice", "tests/test_inference.py::InferenceTest::test_subscript_multi_value", "tests/test_inference.py::InferenceTest::test_subscript_supports__index__", "tests/test_inference.py::InferenceTest::test_swap_assign_inference", "tests/test_inference.py::InferenceTest::test_tuple_builtin_inference", "tests/test_inference.py::InferenceTest::test_tuple_then_list", "tests/test_inference.py::InferenceTest::test_tupleassign_name_inference", "tests/test_inference.py::InferenceTest::test_two_parents_from_same_module", "tests/test_inference.py::InferenceTest::test_type__new__invalid_attrs", "tests/test_inference.py::InferenceTest::test_type__new__invalid_bases", "tests/test_inference.py::InferenceTest::test_type__new__invalid_mcs_argument", "tests/test_inference.py::InferenceTest::test_type__new__invalid_name", "tests/test_inference.py::InferenceTest::test_type__new__metaclass_and_ancestors_lookup", "tests/test_inference.py::InferenceTest::test_type__new__metaclass_lookup", "tests/test_inference.py::InferenceTest::test_type__new__not_enough_arguments", "tests/test_inference.py::InferenceTest::test_type__new__with_metaclass", "tests/test_inference.py::InferenceTest::test_unary_empty_type_errors", "tests/test_inference.py::InferenceTest::test_unary_not", "tests/test_inference.py::InferenceTest::test_unary_op_assignment", "tests/test_inference.py::InferenceTest::test_unary_op_classes", "tests/test_inference.py::InferenceTest::test_unary_op_instance_method_not_callable", "tests/test_inference.py::InferenceTest::test_unary_op_leaks_stop_iteration", "tests/test_inference.py::InferenceTest::test_unary_op_numbers", "tests/test_inference.py::InferenceTest::test_unary_operands", "tests/test_inference.py::InferenceTest::test_unary_type_errors", "tests/test_inference.py::InferenceTest::test_unary_type_errors_for_non_instance_objects", "tests/test_inference.py::InferenceTest::test_unbound_method_inference", "tests/test_inference.py::InferenceTest::test_unicode_methods", "tests/test_inference.py::InferenceTest::test_uninferable_type_subscript", "tests/test_inference.py::GetattrTest::test_attribute_missing", "tests/test_inference.py::GetattrTest::test_attrname_not_string", "tests/test_inference.py::GetattrTest::test_default", "tests/test_inference.py::GetattrTest::test_lambda", "tests/test_inference.py::GetattrTest::test_lookup", "tests/test_inference.py::GetattrTest::test_yes_when_unknown", "tests/test_inference.py::HasattrTest::test_attribute_is_missing", "tests/test_inference.py::HasattrTest::test_attribute_is_not_missing", "tests/test_inference.py::HasattrTest::test_inference_errors", "tests/test_inference.py::HasattrTest::test_lambda", "tests/test_inference.py::BoolOpTest::test_bool_ops", "tests/test_inference.py::BoolOpTest::test_other_nodes", "tests/test_inference.py::BoolOpTest::test_yes_when_unknown", "tests/test_inference.py::TestCallable::test_callable", "tests/test_inference.py::TestCallable::test_callable_methods", "tests/test_inference.py::TestCallable::test_inference_errors", "tests/test_inference.py::TestCallable::test_not_callable", "tests/test_inference.py::TestBool::test_bool", "tests/test_inference.py::TestBool::test_bool_bool_special_method", "tests/test_inference.py::TestBool::test_bool_instance_not_callable", "tests/test_inference.py::TestBool::test_class_subscript", "tests/test_inference.py::TestBool::test_class_subscript_inference_context", "tests/test_inference.py::TestType::test_type", "tests/test_inference.py::ArgumentsTest::test_args", "tests/test_inference.py::ArgumentsTest::test_args_overwritten", "tests/test_inference.py::ArgumentsTest::test_defaults", "tests/test_inference.py::ArgumentsTest::test_fail_to_infer_args", "tests/test_inference.py::ArgumentsTest::test_kwargs", "tests/test_inference.py::ArgumentsTest::test_kwargs_access_by_name", "tests/test_inference.py::ArgumentsTest::test_kwargs_and_other_named_parameters", "tests/test_inference.py::ArgumentsTest::test_kwargs_are_overridden", "tests/test_inference.py::ArgumentsTest::test_kwonly_args", "tests/test_inference.py::ArgumentsTest::test_multiple_kwargs", "tests/test_inference.py::ArgumentsTest::test_multiple_starred_args", "tests/test_inference.py::SliceTest::test_slice", "tests/test_inference.py::SliceTest::test_slice_attributes", "tests/test_inference.py::SliceTest::test_slice_inference_error", "tests/test_inference.py::SliceTest::test_slice_type", "tests/test_inference.py::CallSiteTest::test_call_site", "tests/test_inference.py::CallSiteTest::test_call_site_starred_args", "tests/test_inference.py::CallSiteTest::test_call_site_uninferable", "tests/test_inference.py::CallSiteTest::test_call_site_valid_arguments", "tests/test_inference.py::CallSiteTest::test_duplicated_keyword_arguments", "tests/test_inference.py::ObjectDunderNewTest::test_object_dunder_new_is_inferred_if_decorator", "tests/test_inference.py::test_augassign_recursion", "tests/test_inference.py::test_infer_custom_inherit_from_property", "tests/test_inference.py::test_cannot_infer_call_result_for_builtin_methods", "tests/test_inference.py::test_unpack_dicts_in_assignment", "tests/test_inference.py::test_slice_inference_in_for_loops", "tests/test_inference.py::test_slice_inference_in_for_loops_not_working", "tests/test_inference.py::test_slice_zero_step_does_not_raise_ValueError", "tests/test_inference.py::test_slice_zero_step_on_str_does_not_raise_ValueError", "tests/test_inference.py::test_unpacking_starred_and_dicts_in_assignment", "tests/test_inference.py::test_unpacking_starred_empty_list_in_assignment", "tests/test_inference.py::test_regression_infinite_loop_decorator", "tests/test_inference.py::test_stop_iteration_in_int", "tests/test_inference.py::test_call_on_instance_with_inherited_dunder_call_method", "tests/test_inference.py::TestInferencePropagation::test_call_starargs_propagation", "tests/test_inference.py::TestInferencePropagation::test_call_kwargs_propagation", "tests/test_inference.py::test_compare[<-False]", "tests/test_inference.py::test_compare[<=-True]", "tests/test_inference.py::test_compare[==-True]", "tests/test_inference.py::test_compare[>=-True]", "tests/test_inference.py::test_compare[>-False]", "tests/test_inference.py::test_compare[!=-False]", "tests/test_inference.py::test_compare_membership[in-True]", "tests/test_inference.py::test_compare_membership[not", "tests/test_inference.py::test_compare_lesseq_types[1-1-True]", "tests/test_inference.py::test_compare_lesseq_types[1-1.1-True]", "tests/test_inference.py::test_compare_lesseq_types[1.1-1-False]", "tests/test_inference.py::test_compare_lesseq_types[1.0-1.0-True]", "tests/test_inference.py::test_compare_lesseq_types[abc-def-True]", "tests/test_inference.py::test_compare_lesseq_types[abc--False]", "tests/test_inference.py::test_compare_lesseq_types[lhs6-rhs6-True]", "tests/test_inference.py::test_compare_lesseq_types[lhs7-rhs7-True]", "tests/test_inference.py::test_compare_lesseq_types[lhs8-rhs8-False]", "tests/test_inference.py::test_compare_lesseq_types[True-True-True]", "tests/test_inference.py::test_compare_lesseq_types[True-False-False]", "tests/test_inference.py::test_compare_lesseq_types[False-1-True]", "tests/test_inference.py::test_compare_lesseq_types[(1+0j)-(2+0j)-result12]", "tests/test_inference.py::test_compare_lesseq_types[0.0--0.0-True]", "tests/test_inference.py::test_compare_lesseq_types[0-1-result14]", "tests/test_inference.py::test_compare_lesseq_types[\\x00-\\x01-True]", "tests/test_inference.py::test_compare_chained", "tests/test_inference.py::test_compare_inferred_members", "tests/test_inference.py::test_compare_instance_members", "tests/test_inference.py::test_compare_uninferable_member", "tests/test_inference.py::test_compare_chained_comparisons_shortcircuit_on_false", "tests/test_inference.py::test_compare_chained_comparisons_continue_on_true", "tests/test_inference.py::test_compare_ifexp_constant", "tests/test_inference.py::test_compare_typeerror", "tests/test_inference.py::test_compare_multiple_possibilites", "tests/test_inference.py::test_compare_ambiguous_multiple_possibilites", "tests/test_inference.py::test_compare_nonliteral", "tests/test_inference.py::test_compare_unknown", "tests/test_inference.py::test_limit_inference_result_amount", "tests/test_inference.py::test_attribute_inference_should_not_access_base_classes", "tests/test_inference.py::test_attribute_mro_object_inference", "tests/test_inference.py::test_inferred_sequence_unpacking_works", "tests/test_inference.py::test_recursion_error_inferring_slice", "tests/test_inference.py::test_exception_lookup_last_except_handler_wins", "tests/test_inference.py::test_exception_lookup_name_bound_in_except_handler", "tests/test_inference.py::test_builtin_inference_list_of_exceptions", "tests/test_inference.py::test_cannot_getattr_ann_assigns", "tests/test_inference.py::test_prevent_recursion_error_in_igetattr_and_context_manager_inference", "tests/test_inference.py::test_igetattr_idempotent", "tests/test_inference.py::test_infer_context_manager_with_unknown_args", "tests/test_inference.py::test_subclass_of_exception[\\n", "tests/test_inference.py::test_ifexp_inference", "tests/test_inference.py::test_assert_last_function_returns_none_on_inference", "tests/test_inference.py::test_posonlyargs_inference", "tests/test_inference.py::test_infer_args_unpacking_of_self", "tests/test_inference.py::test_infer_exception_instance_attributes", "tests/test_inference.py::test_inference_is_limited_to_the_boundnode[\\n", "tests/test_inference.py::test_property_inference", "tests/test_inference.py::test_property_as_string", "tests/test_inference.py::test_property_callable_inference", "tests/test_inference.py::test_property_docstring", "tests/test_inference.py::test_recursion_error_inferring_builtin_containers", "tests/test_inference.py::test_inferaugassign_picking_parent_instead_of_stmt", "tests/test_inference.py::test_classmethod_from_builtins_inferred_as_bound", "tests/test_inference.py::test_infer_dict_passes_context", "tests/test_inference.py::test_custom_decorators_for_classmethod_and_staticmethods[\\n", "tests/test_inference.py::test_dataclasses_subscript_inference_recursion_error_39", "tests/test_inference.py::test_self_reference_infer_does_not_trigger_recursion_error", "tests/test_inference.py::test_inferring_properties_multiple_time_does_not_mutate_locals", "tests/test_inference.py::test_getattr_fails_on_empty_values", "tests/test_inference.py::test_infer_first_argument_of_static_method_in_metaclass", "tests/test_inference.py::test_recursion_error_metaclass_monkeypatching", "tests/test_inference.py::test_allow_retrieving_instance_attrs_and_special_attrs_for_functions", "tests/test_inference.py::test_implicit_parameters_bound_method", "tests/test_inference.py::test_super_inference_of_abstract_property", "tests/test_inference.py::test_infer_generated_setter", "tests/test_inference.py::test_infer_list_of_uninferables_does_not_crash", "tests/test_inference.py::test_issue926_infer_stmts_referencing_same_name_is_not_uninferable", "tests/test_inference.py::test_issue926_binop_referencing_same_name_is_not_uninferable", "tests/test_inference.py::test_pylint_issue_4692_attribute_inference_error_in_infer_import_from", "tests/test_inference.py::test_issue_1090_infer_yield_type_base_class", "tests/test_inference.py::test_namespace_package", "tests/test_inference.py::test_namespace_package_same_name", "tests/test_inference.py::test_relative_imports_init_package", "tests/test_inference.py::test_inference_of_items_on_module_dict", "tests/test_inference.py::test_imported_module_var_inferable", "tests/test_inference.py::test_imported_module_var_inferable2", "tests/test_inference.py::test_imported_module_var_inferable3", "tests/test_inference.py::test_recursion_on_inference_tip", "tests/test_inference.py::test_function_def_cached_generator", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[numbered-indexes]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-from-positional]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[numbered-indexes-from-positionl]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[named-indexes-from-keyword]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-on-variable]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-from-variable0]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting[empty-indexes-from-variable1]", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[\\n", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[\"I", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[20", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_uninferable[(\"%\"", "tests/test_inference.py::TestOldStyleStringFormatting::test_old_style_string_formatting_with_specs", "tests/test_nodes.py::AsStringTest::test_3k_annotations_and_metaclass", "tests/test_nodes.py::AsStringTest::test_3k_as_string", "tests/test_nodes.py::AsStringTest::test_as_string", "tests/test_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable", "tests/test_nodes.py::AsStringTest::test_as_string_unknown", "tests/test_nodes.py::AsStringTest::test_class_def", "tests/test_nodes.py::AsStringTest::test_ellipsis", "tests/test_nodes.py::AsStringTest::test_f_strings", "tests/test_nodes.py::AsStringTest::test_frozenset_as_string", "tests/test_nodes.py::AsStringTest::test_func_signature_issue_185", "tests/test_nodes.py::AsStringTest::test_int_attribute", "tests/test_nodes.py::AsStringTest::test_module2_as_string", "tests/test_nodes.py::AsStringTest::test_module_as_string", "tests/test_nodes.py::AsStringTest::test_operator_precedence", "tests/test_nodes.py::AsStringTest::test_slice_and_subscripts", "tests/test_nodes.py::AsStringTest::test_slices", "tests/test_nodes.py::AsStringTest::test_tuple_as_string", "tests/test_nodes.py::AsStringTest::test_varargs_kwargs_as_string", "tests/test_nodes.py::IfNodeTest::test_block_range", "tests/test_nodes.py::IfNodeTest::test_if_elif_else_node", "tests/test_nodes.py::TryExceptNodeTest::test_block_range", "tests/test_nodes.py::TryFinallyNodeTest::test_block_range", "tests/test_nodes.py::TryExceptFinallyNodeTest::test_block_range", "tests/test_nodes.py::ImportNodeTest::test_absolute_import", "tests/test_nodes.py::ImportNodeTest::test_as_string", "tests/test_nodes.py::ImportNodeTest::test_bad_import_inference", "tests/test_nodes.py::ImportNodeTest::test_conditional", "tests/test_nodes.py::ImportNodeTest::test_conditional_import", "tests/test_nodes.py::ImportNodeTest::test_from_self_resolve", "tests/test_nodes.py::ImportNodeTest::test_import_self_resolve", "tests/test_nodes.py::ImportNodeTest::test_more_absolute_import", "tests/test_nodes.py::ImportNodeTest::test_real_name", "tests/test_nodes.py::CmpNodeTest::test_as_string", "tests/test_nodes.py::ConstNodeTest::test_bool", "tests/test_nodes.py::ConstNodeTest::test_complex", "tests/test_nodes.py::ConstNodeTest::test_copy", "tests/test_nodes.py::ConstNodeTest::test_float", "tests/test_nodes.py::ConstNodeTest::test_int", "tests/test_nodes.py::ConstNodeTest::test_none", "tests/test_nodes.py::ConstNodeTest::test_str", "tests/test_nodes.py::ConstNodeTest::test_str_kind", "tests/test_nodes.py::ConstNodeTest::test_unicode", "tests/test_nodes.py::NameNodeTest::test_assign_to_true", "tests/test_nodes.py::TestNamedExprNode::test_frame", "tests/test_nodes.py::TestNamedExprNode::test_scope", "tests/test_nodes.py::AnnAssignNodeTest::test_as_string", "tests/test_nodes.py::AnnAssignNodeTest::test_complex", "tests/test_nodes.py::AnnAssignNodeTest::test_primitive", "tests/test_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value", "tests/test_nodes.py::ArgumentsNodeTC::test_kwoargs", "tests/test_nodes.py::ArgumentsNodeTC::test_linenumbering", "tests/test_nodes.py::ArgumentsNodeTC::test_positional_only", "tests/test_nodes.py::UnboundMethodNodeTest::test_no_super_getattr", "tests/test_nodes.py::BoundMethodNodeTest::test_is_property", "tests/test_nodes.py::AliasesTest::test_aliases", "tests/test_nodes.py::Python35AsyncTest::test_async_await_keywords", "tests/test_nodes.py::Python35AsyncTest::test_asyncfor_as_string", "tests/test_nodes.py::Python35AsyncTest::test_asyncwith_as_string", "tests/test_nodes.py::Python35AsyncTest::test_await_as_string", "tests/test_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string", "tests/test_nodes.py::ContextTest::test_list_del", "tests/test_nodes.py::ContextTest::test_list_load", "tests/test_nodes.py::ContextTest::test_list_store", "tests/test_nodes.py::ContextTest::test_starred_load", "tests/test_nodes.py::ContextTest::test_starred_store", "tests/test_nodes.py::ContextTest::test_subscript_del", "tests/test_nodes.py::ContextTest::test_subscript_load", "tests/test_nodes.py::ContextTest::test_subscript_store", "tests/test_nodes.py::ContextTest::test_tuple_load", "tests/test_nodes.py::ContextTest::test_tuple_store", "tests/test_nodes.py::test_unknown", "tests/test_nodes.py::test_type_comments_with", "tests/test_nodes.py::test_type_comments_for", "tests/test_nodes.py::test_type_coments_assign", "tests/test_nodes.py::test_type_comments_invalid_expression", "tests/test_nodes.py::test_type_comments_invalid_function_comments", "tests/test_nodes.py::test_type_comments_function", "tests/test_nodes.py::test_type_comments_arguments", "tests/test_nodes.py::test_type_comments_posonly_arguments", "tests/test_nodes.py::test_correct_function_type_comment_parent", "tests/test_nodes.py::test_is_generator_for_yield_assignments", "tests/test_nodes.py::test_f_string_correct_line_numbering", "tests/test_nodes.py::test_assignment_expression", "tests/test_nodes.py::test_assignment_expression_in_functiondef", "tests/test_nodes.py::test_get_doc", "tests/test_nodes.py::test_parse_fstring_debug_mode", "tests/test_nodes.py::test_parse_type_comments_with_proper_parent", "tests/test_nodes.py::test_const_itered", "tests/test_nodes.py::test_is_generator_for_yield_in_while", "tests/test_nodes.py::test_is_generator_for_yield_in_if", "tests/test_nodes.py::test_is_generator_for_yield_in_aug_assign", "tests/test_nodes.py::test_str_repr_no_warnings[AnnAssign]", "tests/test_nodes.py::test_str_repr_no_warnings[Arguments]", "tests/test_nodes.py::test_str_repr_no_warnings[Assert]", "tests/test_nodes.py::test_str_repr_no_warnings[Assign]", "tests/test_nodes.py::test_str_repr_no_warnings[AssignAttr]", "tests/test_nodes.py::test_str_repr_no_warnings[AssignName]", "tests/test_nodes.py::test_str_repr_no_warnings[AsyncFor]", "tests/test_nodes.py::test_str_repr_no_warnings[AsyncFunctionDef]", "tests/test_nodes.py::test_str_repr_no_warnings[AsyncWith]", "tests/test_nodes.py::test_str_repr_no_warnings[Attribute]", "tests/test_nodes.py::test_str_repr_no_warnings[AugAssign]", "tests/test_nodes.py::test_str_repr_no_warnings[Await]", "tests/test_nodes.py::test_str_repr_no_warnings[BinOp]", "tests/test_nodes.py::test_str_repr_no_warnings[BoolOp]", "tests/test_nodes.py::test_str_repr_no_warnings[Break]", "tests/test_nodes.py::test_str_repr_no_warnings[Call]", "tests/test_nodes.py::test_str_repr_no_warnings[ClassDef]", "tests/test_nodes.py::test_str_repr_no_warnings[Compare]", "tests/test_nodes.py::test_str_repr_no_warnings[Comprehension]", "tests/test_nodes.py::test_str_repr_no_warnings[ComprehensionScope]", "tests/test_nodes.py::test_str_repr_no_warnings[Const]", "tests/test_nodes.py::test_str_repr_no_warnings[Continue]", "tests/test_nodes.py::test_str_repr_no_warnings[Decorators]", "tests/test_nodes.py::test_str_repr_no_warnings[DelAttr]", "tests/test_nodes.py::test_str_repr_no_warnings[Delete]", "tests/test_nodes.py::test_str_repr_no_warnings[DelName]", "tests/test_nodes.py::test_str_repr_no_warnings[Dict]", "tests/test_nodes.py::test_str_repr_no_warnings[DictComp]", "tests/test_nodes.py::test_str_repr_no_warnings[DictUnpack]", "tests/test_nodes.py::test_str_repr_no_warnings[EmptyNode]", "tests/test_nodes.py::test_str_repr_no_warnings[EvaluatedObject]", "tests/test_nodes.py::test_str_repr_no_warnings[ExceptHandler]", "tests/test_nodes.py::test_str_repr_no_warnings[Expr]", "tests/test_nodes.py::test_str_repr_no_warnings[For]", "tests/test_nodes.py::test_str_repr_no_warnings[FormattedValue]", "tests/test_nodes.py::test_str_repr_no_warnings[FunctionDef]", "tests/test_nodes.py::test_str_repr_no_warnings[GeneratorExp]", "tests/test_nodes.py::test_str_repr_no_warnings[Global]", "tests/test_nodes.py::test_str_repr_no_warnings[If]", "tests/test_nodes.py::test_str_repr_no_warnings[IfExp]", "tests/test_nodes.py::test_str_repr_no_warnings[Import]", "tests/test_nodes.py::test_str_repr_no_warnings[ImportFrom]", "tests/test_nodes.py::test_str_repr_no_warnings[JoinedStr]", "tests/test_nodes.py::test_str_repr_no_warnings[Keyword]", "tests/test_nodes.py::test_str_repr_no_warnings[Lambda]", "tests/test_nodes.py::test_str_repr_no_warnings[List]", "tests/test_nodes.py::test_str_repr_no_warnings[ListComp]", "tests/test_nodes.py::test_str_repr_no_warnings[LocalsDictNodeNG]", "tests/test_nodes.py::test_str_repr_no_warnings[Match]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchAs]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchCase]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchClass]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchMapping]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchOr]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchSequence]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchSingleton]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchStar]", "tests/test_nodes.py::test_str_repr_no_warnings[MatchValue]", "tests/test_nodes.py::test_str_repr_no_warnings[Module]", "tests/test_nodes.py::test_str_repr_no_warnings[Name]", "tests/test_nodes.py::test_str_repr_no_warnings[NamedExpr]", "tests/test_nodes.py::test_str_repr_no_warnings[Nonlocal]", "tests/test_nodes.py::test_str_repr_no_warnings[ParamSpec]", "tests/test_nodes.py::test_str_repr_no_warnings[TypeVarTuple]", "tests/test_nodes.py::test_str_repr_no_warnings[Pass]", "tests/test_nodes.py::test_str_repr_no_warnings[Pattern]", "tests/test_nodes.py::test_str_repr_no_warnings[Raise]", "tests/test_nodes.py::test_str_repr_no_warnings[Return]", "tests/test_nodes.py::test_str_repr_no_warnings[Set]", "tests/test_nodes.py::test_str_repr_no_warnings[SetComp]", "tests/test_nodes.py::test_str_repr_no_warnings[Slice]", "tests/test_nodes.py::test_str_repr_no_warnings[Starred]", "tests/test_nodes.py::test_str_repr_no_warnings[Subscript]", "tests/test_nodes.py::test_str_repr_no_warnings[TryExcept]", "tests/test_nodes.py::test_str_repr_no_warnings[TryFinally]", "tests/test_nodes.py::test_str_repr_no_warnings[TryStar]", "tests/test_nodes.py::test_str_repr_no_warnings[Tuple]", "tests/test_nodes.py::test_str_repr_no_warnings[TypeAlias]", "tests/test_nodes.py::test_str_repr_no_warnings[TypeVar]", "tests/test_nodes.py::test_str_repr_no_warnings[UnaryOp]", "tests/test_nodes.py::test_str_repr_no_warnings[Unknown]", "tests/test_nodes.py::test_str_repr_no_warnings[While]", "tests/test_nodes.py::test_str_repr_no_warnings[With]", "tests/test_nodes.py::test_str_repr_no_warnings[Yield]", "tests/test_nodes.py::test_str_repr_no_warnings[YieldFrom]", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_container", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_name", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_attribute", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_call", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_assignment", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_stmts", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_nodes", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_ops", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_if", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_for", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_const", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_function", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_dict", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_try", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_subscript", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_import", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_with", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_while", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_string", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_comprehension", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_class", "tests/test_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_module", "tests/test_raw_building.py::RawBuildingTC::test_attach_dummy_node", "tests/test_raw_building.py::RawBuildingTC::test_build_class", "tests/test_raw_building.py::RawBuildingTC::test_build_from_import", "tests/test_raw_building.py::RawBuildingTC::test_build_function", "tests/test_raw_building.py::RawBuildingTC::test_build_function_args", "tests/test_raw_building.py::RawBuildingTC::test_build_function_deepinspect_deprecation", "tests/test_raw_building.py::RawBuildingTC::test_build_function_defaults", "tests/test_raw_building.py::RawBuildingTC::test_build_function_kwonlyargs", "tests/test_raw_building.py::RawBuildingTC::test_build_function_posonlyargs", "tests/test_raw_building.py::RawBuildingTC::test_build_module", "tests/test_raw_building.py::RawBuildingTC::test_io_is__io", "tests/test_raw_building.py::RawBuildingTC::test_module_object_with_broken_getattr", "tests/test_raw_building.py::test_build_module_getattr_catch_output", "tests/test_scoped_nodes.py::ModuleNodeTest::test_comment_before_docstring", "tests/test_scoped_nodes.py::ModuleNodeTest::test_dict_interface", "tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_api", "tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory", "tests/test_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical", "tests/test_scoped_nodes.py::ModuleNodeTest::test_getattr", "tests/test_scoped_nodes.py::ModuleNodeTest::test_import_1", "tests/test_scoped_nodes.py::ModuleNodeTest::test_import_2", "tests/test_scoped_nodes.py::ModuleNodeTest::test_module_getattr", "tests/test_scoped_nodes.py::ModuleNodeTest::test_multiline_docstring", "tests/test_scoped_nodes.py::ModuleNodeTest::test_public_names", "tests/test_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name", "tests/test_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level", "tests/test_scoped_nodes.py::ModuleNodeTest::test_singleline_docstring", "tests/test_scoped_nodes.py::ModuleNodeTest::test_special_attributes", "tests/test_scoped_nodes.py::ModuleNodeTest::test_stream_api", "tests/test_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names", "tests/test_scoped_nodes.py::ModuleNodeTest::test_without_docstring", "tests/test_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none", "tests/test_scoped_nodes.py::FunctionNodeTest::test_argnames", "tests/test_scoped_nodes.py::FunctionNodeTest::test_argnames_lambda", "tests/test_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors", "tests/test_scoped_nodes.py::FunctionNodeTest::test_default_value", "tests/test_scoped_nodes.py::FunctionNodeTest::test_dict_interface", "tests/test_scoped_nodes.py::FunctionNodeTest::test_display_type", "tests/test_scoped_nodes.py::FunctionNodeTest::test_docstring_special_cases", "tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod", "tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function", "tests/test_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method", "tests/test_scoped_nodes.py::FunctionNodeTest::test_format_args", "tests/test_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args", "tests/test_scoped_nodes.py::FunctionNodeTest::test_four_args", "tests/test_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr", "tests/test_scoped_nodes.py::FunctionNodeTest::test_func_is_bound", "tests/test_scoped_nodes.py::FunctionNodeTest::test_igetattr", "tests/test_scoped_nodes.py::FunctionNodeTest::test_inference_error", "tests/test_scoped_nodes.py::FunctionNodeTest::test_is_abstract", "tests/test_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated", "tests/test_scoped_nodes.py::FunctionNodeTest::test_is_generator", "tests/test_scoped_nodes.py::FunctionNodeTest::test_is_method", "tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_getattr", "tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype", "tests/test_scoped_nodes.py::FunctionNodeTest::test_lambda_qname", "tests/test_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass", "tests/test_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring", "tests/test_scoped_nodes.py::FunctionNodeTest::test_multiline_docstring_async", "tests/test_scoped_nodes.py::FunctionNodeTest::test_navigation", "tests/test_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none", "tests/test_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none", "tests/test_scoped_nodes.py::FunctionNodeTest::test_positional_only_argnames", "tests/test_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last", "tests/test_scoped_nodes.py::FunctionNodeTest::test_return_nothing", "tests/test_scoped_nodes.py::FunctionNodeTest::test_singleline_docstring", "tests/test_scoped_nodes.py::FunctionNodeTest::test_special_attributes", "tests/test_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses", "tests/test_scoped_nodes.py::FunctionNodeTest::test_without_docstring", "tests/test_scoped_nodes.py::ClassNodeTest::test__bases__attribute", "tests/test_scoped_nodes.py::ClassNodeTest::test__mro__attribute", "tests/test_scoped_nodes.py::ClassNodeTest::test_add_metaclass", "tests/test_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots", "tests/test_scoped_nodes.py::ClassNodeTest::test_ancestors", "tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators", "tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class", "tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered", "tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered", "tests/test_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered", "tests/test_scoped_nodes.py::ClassNodeTest::test_class_getattr", "tests/test_scoped_nodes.py::ClassNodeTest::test_class_keywords", "tests/test_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes", "tests/test_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1", "tests/test_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2", "tests/test_scoped_nodes.py::ClassNodeTest::test_dict_interface", "tests/test_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple", "tests/test_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments", "tests/test_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno", "tests/test_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent", "tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa", "tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform", "tests/test_scoped_nodes.py::ClassNodeTest::test_getattr_with_enpty_annassign", "tests/test_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr", "tests/test_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass", "tests/test_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup", "tests/test_scoped_nodes.py::ClassNodeTest::test_inner_classes", "tests/test_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors", "tests/test_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas", "tests/test_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2", "tests/test_scoped_nodes.py::ClassNodeTest::test_instance_getattr", "tests/test_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr", "tests/test_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes", "tests/test_scoped_nodes.py::ClassNodeTest::test_kite_graph", "tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors", "tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro", "tests/test_scoped_nodes.py::ClassNodeTest::test_local_attr_mro", "tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_error", "tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup", "tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors", "tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class", "tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_type", "tests/test_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak", "tests/test_scoped_nodes.py::ClassNodeTest::test_methods", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_1", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_2", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_3", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_4", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_5", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_6", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_7", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_typing_extensions", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes", "tests/test_scoped_nodes.py::ClassNodeTest::test_mro_with_factories", "tests/test_scoped_nodes.py::ClassNodeTest::test_multiline_docstring", "tests/test_scoped_nodes.py::ClassNodeTest::test_navigation", "tests/test_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop", "tests/test_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine", "tests/test_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult", "tests/test_scoped_nodes.py::ClassNodeTest::test_singleline_docstring", "tests/test_scoped_nodes.py::ClassNodeTest::test_slots", "tests/test_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred", "tests/test_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots", "tests/test_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys", "tests/test_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents", "tests/test_scoped_nodes.py::ClassNodeTest::test_type", "tests/test_scoped_nodes.py::ClassNodeTest::test_type_three_arguments", "tests/test_scoped_nodes.py::ClassNodeTest::test_with_invalid_metaclass", "tests/test_scoped_nodes.py::ClassNodeTest::test_without_docstring", "tests/test_scoped_nodes.py::test_issue940_metaclass_subclass_property", "tests/test_scoped_nodes.py::test_issue940_property_grandchild", "tests/test_scoped_nodes.py::test_issue940_metaclass_property", "tests/test_scoped_nodes.py::test_issue940_with_metaclass_class_context_property", "tests/test_scoped_nodes.py::test_issue940_metaclass_values_funcdef", "tests/test_scoped_nodes.py::test_issue940_metaclass_derived_funcdef", "tests/test_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor", "tests/test_scoped_nodes.py::test_property_in_body_of_try", "tests/test_scoped_nodes.py::test_property_in_body_of_if", "tests/test_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase", "tests/test_scoped_nodes.py::test_enums_type_annotation_str_member", "tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[bool]", "tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[dict]", "tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[int]", "tests/test_scoped_nodes.py::test_enums_type_annotation_no_value[str]", "tests/test_scoped_nodes.py::test_enums_value2member_map_", "tests/test_scoped_nodes.py::test_enums_type_annotation_non_str_member[int-42]", "tests/test_scoped_nodes.py::test_enums_type_annotation_non_str_member[bytes-]", "tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[dict-value0]", "tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[list-value1]", "tests/test_scoped_nodes.py::test_enums_type_annotations_non_const_member[TypedDict-value2]", "tests/test_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance", "tests/test_scoped_nodes.py::test_posonlyargs_python_38[\\ndef", "tests/test_scoped_nodes.py::test_posonlyargs_default_value", "tests/test_scoped_nodes.py::test_ancestor_with_generic", "tests/test_scoped_nodes.py::test_slots_duplicate_bases_issue_1089", "tests/test_scoped_nodes.py::TestFrameNodes::test_frame_node", "tests/test_scoped_nodes.py::TestFrameNodes::test_non_frame_node"], "PASS_TO_PASS": [], "environment_setup_commit": "1113d490ec4a94cdc1b35f45abfdaca9f19fa31e"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-983", "base_commit": "53a20335357bbd734d74c3bfe22e3518f74f4d11", "patch": "diff --git a/astroid/bases.py b/astroid/bases.py\n--- a/astroid/bases.py\n+++ b/astroid/bases.py\n@@ -329,6 +329,12 @@ def getitem(self, index, context=None):\n raise exceptions.InferenceError(\n \"Could not find __getitem__ for {node!r}.\", node=self, context=context\n )\n+ if len(method.args.arguments) != 2: # (self, index)\n+ raise exceptions.AstroidTypeError(\n+ \"__getitem__ for {node!r} does not have correct signature\",\n+ node=self,\n+ context=context,\n+ )\n return next(method.infer_call_result(self, new_context))\n \n \ndiff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py\n--- a/astroid/scoped_nodes.py\n+++ b/astroid/scoped_nodes.py\n@@ -1661,11 +1661,12 @@ def is_bound(self):\n \"\"\"\n return self.type == \"classmethod\"\n \n- def is_abstract(self, pass_is_abstract=True):\n+ def is_abstract(self, pass_is_abstract=True, any_raise_is_abstract=False):\n \"\"\"Check if the method is abstract.\n \n A method is considered abstract if any of the following is true:\n * The only statement is 'raise NotImplementedError'\n+ * The only statement is 'raise <SomeException>' and any_raise_is_abstract is True\n * The only statement is 'pass' and pass_is_abstract is True\n * The method is annotated with abc.astractproperty/abc.abstractmethod\n \n@@ -1686,6 +1687,8 @@ def is_abstract(self, pass_is_abstract=True):\n \n for child_node in self.body:\n if isinstance(child_node, node_classes.Raise):\n+ if any_raise_is_abstract:\n+ return True\n if child_node.raises_not_implemented():\n return True\n return pass_is_abstract and isinstance(child_node, node_classes.Pass)\n@@ -1744,8 +1747,11 @@ def infer_call_result(self, caller=None, context=None):\n \n first_return = next(returns, None)\n if not first_return:\n- if self.body and isinstance(self.body[-1], node_classes.Assert):\n- yield node_classes.Const(None)\n+ if self.body:\n+ if self.is_abstract(pass_is_abstract=True, any_raise_is_abstract=True):\n+ yield util.Uninferable\n+ else:\n+ yield node_classes.Const(None)\n return\n \n raise exceptions.InferenceError(\n", "test_patch": "diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py\n--- a/tests/unittest_inference.py\n+++ b/tests/unittest_inference.py\n@@ -706,14 +706,6 @@ class InvalidGetitem2(object):\n NoGetitem()[4] #@\n InvalidGetitem()[5] #@\n InvalidGetitem2()[10] #@\n- \"\"\"\n- )\n- for node in ast_nodes[:3]:\n- self.assertRaises(InferenceError, next, node.infer())\n- for node in ast_nodes[3:]:\n- self.assertEqual(next(node.infer()), util.Uninferable)\n- ast_nodes = extract_node(\n- \"\"\"\n [1, 2, 3][None] #@\n 'lala'['bala'] #@\n \"\"\"\n@@ -5404,26 +5396,25 @@ class Cls:\n def test_prevent_recursion_error_in_igetattr_and_context_manager_inference():\n code = \"\"\"\n class DummyContext(object):\n- def method(self, msg): # pylint: disable=C0103\n- pass\n def __enter__(self):\n- pass\n+ return self\n def __exit__(self, ex_type, ex_value, ex_tb):\n return True\n \n- class CallMeMaybe(object):\n- def __call__(self):\n- while False:\n- with DummyContext() as con:\n- f_method = con.method\n- break\n+ if False:\n+ with DummyContext() as con:\n+ pass\n \n- with DummyContext() as con:\n- con #@\n- f_method = con.method\n+ with DummyContext() as con:\n+ con.__enter__ #@\n \"\"\"\n node = extract_node(code)\n- assert next(node.infer()) is util.Uninferable\n+ # According to the original issue raised that introduced this test\n+ # (https://github.com/PyCQA/astroid/663, see 55076ca), this test was a\n+ # non-regression check for StopIteration leaking out of inference and\n+ # causing a RuntimeError. Hence, here just consume the inferred value\n+ # without checking it and rely on pytest to fail on raise\n+ next(node.infer())\n \n \n def test_infer_context_manager_with_unknown_args():\ndiff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py\n--- a/tests/unittest_scoped_nodes.py\n+++ b/tests/unittest_scoped_nodes.py\n@@ -466,6 +466,55 @@ def func():\n self.assertIsInstance(func_vals[0], nodes.Const)\n self.assertIsNone(func_vals[0].value)\n \n+ def test_no_returns_is_implicitly_none(self):\n+ code = \"\"\"\n+ def f():\n+ print('non-empty, non-pass, no return statements')\n+ value = f()\n+ value\n+ \"\"\"\n+ node = builder.extract_node(code)\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.Const)\n+ assert inferred.value is None\n+\n+ def test_only_raises_is_not_implicitly_none(self):\n+ code = \"\"\"\n+ def f():\n+ raise SystemExit()\n+ f()\n+ \"\"\"\n+ node = builder.extract_node(code) # type: nodes.Call\n+ inferred = next(node.infer())\n+ assert inferred is util.Uninferable\n+\n+ def test_abstract_methods_are_not_implicitly_none(self):\n+ code = \"\"\"\n+ from abc import ABCMeta, abstractmethod\n+\n+ class Abstract(metaclass=ABCMeta):\n+ @abstractmethod\n+ def foo(self):\n+ pass\n+ def bar(self):\n+ print('non-empty, non-pass, no return statements')\n+ Abstract().foo() #@\n+ Abstract().bar() #@\n+\n+ class Concrete(Abstract):\n+ def foo(self):\n+ return 123\n+ Concrete().foo() #@\n+ Concrete().bar() #@\n+ \"\"\"\n+ afoo, abar, cfoo, cbar = builder.extract_node(code)\n+\n+ assert next(afoo.infer()) is util.Uninferable\n+ for node, value in [(abar, None), (cfoo, 123), (cbar, None)]:\n+ inferred = next(node.infer())\n+ assert isinstance(inferred, nodes.Const)\n+ assert inferred.value == value\n+\n def test_func_instance_attr(self):\n \"\"\"test instance attributes for functions\"\"\"\n data = \"\"\"\n", "problem_statement": "Cannot infer empty functions\n### Steps to reproduce\r\n```python\r\nimport astroid\r\nastroid.extract_node(\"\"\"\r\ndef f():\r\n pass\r\nf()\r\n\"\"\").inferred()\r\n```\r\n### Current behavior\r\nraises `StopIteration`\r\n\r\n### Expected behavior\r\nReturns `[const.NoneType]`\r\n\r\n### ``python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"`` output\r\n\r\n2.0.0\r\n\r\nThis also applies to procedural functions which don't explicitly return any values.\n", "hints_text": "Makes sense.\r\n\r\nThis happens because the inference for functions looks through each return value here (https://github.com/PyCQA/astroid/blob/629c92db2dc1b016f4bf47645c95c42e65fd3bd6/astroid/scoped_nodes.py#L1558) and tries to infer the result from there. But since functions like this don't have an explicit return value, the inference gets into `raise_if_nothing_inferred` over here (https://github.com/PyCQA/astroid/blob/ac3e82e9bd8678086325a71a927a06bbc43d415e/astroid/decorators.py#L140), resulting in the exception you see. \nWhat should we infer for a function that always raises an exception? I don't think it should be `None`. Uninferable I guess?\r\n\r\n---\r\n\r\nI tried to add this, but It caused a cascade of errors where we are looking for Uninferable instead of const.None\n@brycepg I would say it should return `Uninferable`, as raising exceptions is not necessarily returning a value from the function. Although we'd want some mechanism to get what exceptions a function could raise.\r\n\r\nRegarding your last statement, you mean you added `Uninferable` for functions that raise exceptions or for functions that return `None`? Which of these failed with the cascade of errors?\n@PCManticore I made functions that do not have any return/yield nodes infer to `None` instead of `Uninferable`, and it broke a lot of tests.", "created_at": "2021-05-01T03:28:27Z", "version": "2.5", "FAIL_TO_PASS": ["tests/unittest_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none"], "PASS_TO_PASS": ["tests/unittest_inference.py::InferenceUtilsTest::test_path_wrapper", "tests/unittest_inference.py::InferenceTest::test__new__", "tests/unittest_inference.py::InferenceTest::test__new__bound_methods", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference1", "tests/unittest_inference.py::InferenceTest::test_advanced_tupleassign_name_inference2", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference", "tests/unittest_inference.py::InferenceTest::test_ancestors_inference2", "tests/unittest_inference.py::InferenceTest::test_args_default_inference1", "tests/unittest_inference.py::InferenceTest::test_args_default_inference2", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_aug_not_implemented_rop_fallback", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_aug_not_implemented_normal_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_same_type_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_aug_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_aug_op_subtype_normal_op_is_implemented", "tests/unittest_inference.py::InferenceTest::test_augassign", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_augop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_none_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_normal_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_not_implemented_returned_for_all", "tests/unittest_inference.py::InferenceTest::test_augop_supertypes_reflected_binop_implemented", "tests/unittest_inference.py::InferenceTest::test_bin_op_classes", "tests/unittest_inference.py::InferenceTest::test_bin_op_supertype_more_complicated_example", "tests/unittest_inference.py::InferenceTest::test_binary_op_custom_class", "tests/unittest_inference.py::InferenceTest::test_binary_op_float_div", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitand", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_bitxor", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftleft", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_shiftright", "tests/unittest_inference.py::InferenceTest::test_binary_op_int_sub", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_int", "tests/unittest_inference.py::InferenceTest::test_binary_op_list_mul_none", "tests/unittest_inference.py::InferenceTest::test_binary_op_on_self", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type", "tests/unittest_inference.py::InferenceTest::test_binary_op_other_type_using_reflected_operands", "tests/unittest_inference.py::InferenceTest::test_binary_op_reflected_and_not_implemented_is_type_error", "tests/unittest_inference.py::InferenceTest::test_binary_op_str_mul", "tests/unittest_inference.py::InferenceTest::test_binary_op_tuple_add", "tests/unittest_inference.py::InferenceTest::test_binary_op_type_errors", "tests/unittest_inference.py::InferenceTest::test_binop_ambiguity", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_no_method_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_normal_not_implemented_and_reflected", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_and_normal_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_reflected_only", "tests/unittest_inference.py::InferenceTest::test_binop_different_types_unknown_bases", "tests/unittest_inference.py::InferenceTest::test_binop_inference_errors", "tests/unittest_inference.py::InferenceTest::test_binop_list_with_elts", "tests/unittest_inference.py::InferenceTest::test_binop_same_types", "tests/unittest_inference.py::InferenceTest::test_binop_subtype", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_implemented_in_parent", "tests/unittest_inference.py::InferenceTest::test_binop_subtype_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_both_not_implemented", "tests/unittest_inference.py::InferenceTest::test_binop_supertype_rop_not_implemented", "tests/unittest_inference.py::InferenceTest::test_bool_value", "tests/unittest_inference.py::InferenceTest::test_bool_value_instances", "tests/unittest_inference.py::InferenceTest::test_bool_value_recursive", "tests/unittest_inference.py::InferenceTest::test_bool_value_variable", "tests/unittest_inference.py::InferenceTest::test_bound_method_inference", "tests/unittest_inference.py::InferenceTest::test_bt_ancestor_crash", "tests/unittest_inference.py::InferenceTest::test_builtin_help", "tests/unittest_inference.py::InferenceTest::test_builtin_inference_py3k", "tests/unittest_inference.py::InferenceTest::test_builtin_name_inference", "tests/unittest_inference.py::InferenceTest::test_builtin_open", "tests/unittest_inference.py::InferenceTest::test_builtin_types", "tests/unittest_inference.py::InferenceTest::test_bytes_subscript", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_func", "tests/unittest_inference.py::InferenceTest::test_callfunc_context_lambda", "tests/unittest_inference.py::InferenceTest::test_callfunc_inference", "tests/unittest_inference.py::InferenceTest::test_class_inference", "tests/unittest_inference.py::InferenceTest::test_classmethod_inferred_by_context", "tests/unittest_inference.py::InferenceTest::test_context_call_for_context_managers", "tests/unittest_inference.py::InferenceTest::test_conversion_of_dict_methods", "tests/unittest_inference.py::InferenceTest::test_del1", "tests/unittest_inference.py::InferenceTest::test_del2", "tests/unittest_inference.py::InferenceTest::test_delayed_attributes_without_slots", "tests/unittest_inference.py::InferenceTest::test_dict_inference", "tests/unittest_inference.py::InferenceTest::test_dict_inference_for_multiple_starred", "tests/unittest_inference.py::InferenceTest::test_dict_inference_kwargs", "tests/unittest_inference.py::InferenceTest::test_dict_inference_unpack_repeated_key", "tests/unittest_inference.py::InferenceTest::test_dict_invalid_args", "tests/unittest_inference.py::InferenceTest::test_exc_ancestors", "tests/unittest_inference.py::InferenceTest::test_except_inference", "tests/unittest_inference.py::InferenceTest::test_f_arg_f", "tests/unittest_inference.py::InferenceTest::test_factory_method", "tests/unittest_inference.py::InferenceTest::test_factory_methods_cls_call", "tests/unittest_inference.py::InferenceTest::test_factory_methods_object_new_call", "tests/unittest_inference.py::InferenceTest::test_float_complex_ambiguity", "tests/unittest_inference.py::InferenceTest::test_frozenset_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_function_inference", "tests/unittest_inference.py::InferenceTest::test_genexpr_bool_value", "tests/unittest_inference.py::InferenceTest::test_getattr_inference1", "tests/unittest_inference.py::InferenceTest::test_getattr_inference2", "tests/unittest_inference.py::InferenceTest::test_getattr_inference3", "tests/unittest_inference.py::InferenceTest::test_getattr_inference4", "tests/unittest_inference.py::InferenceTest::test_getitem_of_class_raised_type_error", "tests/unittest_inference.py::InferenceTest::test_im_func_unwrap", "tests/unittest_inference.py::InferenceTest::test_import_as", "tests/unittest_inference.py::InferenceTest::test_infer_abstract_property_return_values", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_object_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_defined_in_outer_scope_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_index_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arg_called_type_when_used_as_subscript_is_uninferable", "tests/unittest_inference.py::InferenceTest::test_infer_arguments", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_crash", "tests/unittest_inference.py::InferenceTest::test_infer_call_result_invalid_dunder_call_on_instance", "tests/unittest_inference.py::InferenceTest::test_infer_cls_in_class_methods", "tests/unittest_inference.py::InferenceTest::test_infer_coercion_rules_for_floats_complex", "tests/unittest_inference.py::InferenceTest::test_infer_empty_nodes", "tests/unittest_inference.py::InferenceTest::test_infer_nested", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_inner_class_works_indirectly", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_instance_attr_indirect", "tests/unittest_inference.py::InferenceTest::test_infer_subclass_attr_outer_class", "tests/unittest_inference.py::InferenceTest::test_infer_variable_arguments", "tests/unittest_inference.py::InferenceTest::test_inference_restrictions", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_skip_index_error", "tests/unittest_inference.py::InferenceTest::test_inferring_context_manager_unpacking_inference_error", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager", "tests/unittest_inference.py::InferenceTest::test_inferring_with_contextlib_contextmanager_failures", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement", "tests/unittest_inference.py::InferenceTest::test_inferring_with_statement_failures", "tests/unittest_inference.py::InferenceTest::test_infinite_loop_for_decorators", "tests/unittest_inference.py::InferenceTest::test_inner_value_redefined_by_subclass", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_multiple_methods", "tests/unittest_inference.py::InferenceTest::test_instance_binary_operations_parent", "tests/unittest_inference.py::InferenceTest::test_instance_slicing", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_fails", "tests/unittest_inference.py::InferenceTest::test_instance_slicing_slices", "tests/unittest_inference.py::InferenceTest::test_invalid_slicing_primaries", "tests/unittest_inference.py::InferenceTest::test_invalid_subscripts", "tests/unittest_inference.py::InferenceTest::test_lambda_as_methods", "tests/unittest_inference.py::InferenceTest::test_list_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_list_inference", "tests/unittest_inference.py::InferenceTest::test_listassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_lookup_cond_branches", "tests/unittest_inference.py::InferenceTest::test_matmul", "tests/unittest_inference.py::InferenceTest::test_metaclass__getitem__", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call", "tests/unittest_inference.py::InferenceTest::test_metaclass_custom_dunder_call_boundnode", "tests/unittest_inference.py::InferenceTest::test_metaclass_subclasses_arguments_are_classes_not_instances", "tests/unittest_inference.py::InferenceTest::test_metaclass_with_keyword_args", "tests/unittest_inference.py::InferenceTest::test_method_argument", "tests/unittest_inference.py::InferenceTest::test_module_inference", "tests/unittest_inference.py::InferenceTest::test_mul_list_supports__index__", "tests/unittest_inference.py::InferenceTest::test_mulassign_inference", "tests/unittest_inference.py::InferenceTest::test_name_bool_value", "tests/unittest_inference.py::InferenceTest::test_nested_contextmanager", "tests/unittest_inference.py::InferenceTest::test_no_infinite_ancestor_loop", "tests/unittest_inference.py::InferenceTest::test_no_runtime_error_in_repeat_inference", "tests/unittest_inference.py::InferenceTest::test_nonregr_absolute_import", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_arg", "tests/unittest_inference.py::InferenceTest::test_nonregr_func_global", "tests/unittest_inference.py::InferenceTest::test_nonregr_getitem_empty_tuple", "tests/unittest_inference.py::InferenceTest::test_nonregr_inference_modifying_col_offset", "tests/unittest_inference.py::InferenceTest::test_nonregr_instance_attrs", "tests/unittest_inference.py::InferenceTest::test_nonregr_lambda_arg", "tests/unittest_inference.py::InferenceTest::test_nonregr_layed_dictunpack", "tests/unittest_inference.py::InferenceTest::test_nonregr_multi_referential_addition", "tests/unittest_inference.py::InferenceTest::test_pluggable_inference", "tests/unittest_inference.py::InferenceTest::test_property", "tests/unittest_inference.py::InferenceTest::test_python25_no_relative_import", "tests/unittest_inference.py::InferenceTest::test_scope_lookup_same_attributes", "tests/unittest_inference.py::InferenceTest::test_set_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_simple_for", "tests/unittest_inference.py::InferenceTest::test_simple_for_genexpr", "tests/unittest_inference.py::InferenceTest::test_simple_subscript", "tests/unittest_inference.py::InferenceTest::test_simple_tuple", "tests/unittest_inference.py::InferenceTest::test_slicing_list", "tests/unittest_inference.py::InferenceTest::test_slicing_str", "tests/unittest_inference.py::InferenceTest::test_slicing_tuple", "tests/unittest_inference.py::InferenceTest::test_special_method_masquerading_as_another", "tests/unittest_inference.py::InferenceTest::test_starred_in_list_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_literals_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_inference_issues", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_no_inference_possible", "tests/unittest_inference.py::InferenceTest::test_starred_in_mapping_literal_non_const_keys_values", "tests/unittest_inference.py::InferenceTest::test_starred_in_set_literal", "tests/unittest_inference.py::InferenceTest::test_starred_in_tuple_literal", "tests/unittest_inference.py::InferenceTest::test_stop_iteration_leak", "tests/unittest_inference.py::InferenceTest::test_str_methods", "tests/unittest_inference.py::InferenceTest::test_subscript_inference_error", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_slice", "tests/unittest_inference.py::InferenceTest::test_subscript_multi_value", "tests/unittest_inference.py::InferenceTest::test_subscript_supports__index__", "tests/unittest_inference.py::InferenceTest::test_swap_assign_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_builtin_inference", "tests/unittest_inference.py::InferenceTest::test_tuple_then_list", "tests/unittest_inference.py::InferenceTest::test_tupleassign_name_inference", "tests/unittest_inference.py::InferenceTest::test_two_parents_from_same_module", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_attrs", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_bases", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_mcs_argument", "tests/unittest_inference.py::InferenceTest::test_type__new__invalid_name", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_and_ancestors_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__metaclass_lookup", "tests/unittest_inference.py::InferenceTest::test_type__new__not_enough_arguments", "tests/unittest_inference.py::InferenceTest::test_type__new__with_metaclass", "tests/unittest_inference.py::InferenceTest::test_unary_empty_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_not", "tests/unittest_inference.py::InferenceTest::test_unary_op_assignment", "tests/unittest_inference.py::InferenceTest::test_unary_op_classes", "tests/unittest_inference.py::InferenceTest::test_unary_op_instance_method_not_callable", "tests/unittest_inference.py::InferenceTest::test_unary_op_leaks_stop_iteration", "tests/unittest_inference.py::InferenceTest::test_unary_op_numbers", "tests/unittest_inference.py::InferenceTest::test_unary_operands", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors", "tests/unittest_inference.py::InferenceTest::test_unary_type_errors_for_non_instance_objects", "tests/unittest_inference.py::InferenceTest::test_unbound_method_inference", "tests/unittest_inference.py::InferenceTest::test_unicode_methods", "tests/unittest_inference.py::GetattrTest::test_attribute_missing", "tests/unittest_inference.py::GetattrTest::test_attrname_not_string", "tests/unittest_inference.py::GetattrTest::test_default", "tests/unittest_inference.py::GetattrTest::test_lambda", "tests/unittest_inference.py::GetattrTest::test_lookup", "tests/unittest_inference.py::GetattrTest::test_yes_when_unknown", "tests/unittest_inference.py::HasattrTest::test_attribute_is_missing", "tests/unittest_inference.py::HasattrTest::test_attribute_is_not_missing", "tests/unittest_inference.py::HasattrTest::test_inference_errors", "tests/unittest_inference.py::HasattrTest::test_lambda", "tests/unittest_inference.py::BoolOpTest::test_bool_ops", "tests/unittest_inference.py::BoolOpTest::test_other_nodes", "tests/unittest_inference.py::BoolOpTest::test_yes_when_unknown", "tests/unittest_inference.py::TestCallable::test_callable", "tests/unittest_inference.py::TestCallable::test_callable_methods", "tests/unittest_inference.py::TestCallable::test_inference_errors", "tests/unittest_inference.py::TestCallable::test_not_callable", "tests/unittest_inference.py::TestBool::test_bool", "tests/unittest_inference.py::TestBool::test_bool_bool_special_method", "tests/unittest_inference.py::TestBool::test_bool_instance_not_callable", "tests/unittest_inference.py::TestType::test_type", "tests/unittest_inference.py::ArgumentsTest::test_args", "tests/unittest_inference.py::ArgumentsTest::test_defaults", "tests/unittest_inference.py::ArgumentsTest::test_fail_to_infer_args", "tests/unittest_inference.py::ArgumentsTest::test_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_access_by_name", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_and_other_named_parameters", "tests/unittest_inference.py::ArgumentsTest::test_kwargs_are_overridden", "tests/unittest_inference.py::ArgumentsTest::test_kwonly_args", "tests/unittest_inference.py::ArgumentsTest::test_multiple_kwargs", "tests/unittest_inference.py::ArgumentsTest::test_multiple_starred_args", "tests/unittest_inference.py::SliceTest::test_slice", "tests/unittest_inference.py::SliceTest::test_slice_attributes", "tests/unittest_inference.py::SliceTest::test_slice_inference_error", "tests/unittest_inference.py::SliceTest::test_slice_type", "tests/unittest_inference.py::CallSiteTest::test_call_site", "tests/unittest_inference.py::CallSiteTest::test_call_site_starred_args", "tests/unittest_inference.py::CallSiteTest::test_call_site_valid_arguments", "tests/unittest_inference.py::CallSiteTest::test_duplicated_keyword_arguments", "tests/unittest_inference.py::ObjectDunderNewTest::test_object_dunder_new_is_inferred_if_decorator", "tests/unittest_inference.py::test_augassign_recursion", "tests/unittest_inference.py::test_infer_custom_inherit_from_property", "tests/unittest_inference.py::test_cannot_infer_call_result_for_builtin_methods", "tests/unittest_inference.py::test_unpack_dicts_in_assignment", "tests/unittest_inference.py::test_slice_inference_in_for_loops", "tests/unittest_inference.py::test_slice_inference_in_for_loops_not_working", "tests/unittest_inference.py::test_unpacking_starred_and_dicts_in_assignment", "tests/unittest_inference.py::test_unpacking_starred_empty_list_in_assignment", "tests/unittest_inference.py::test_regression_infinite_loop_decorator", "tests/unittest_inference.py::test_stop_iteration_in_int", "tests/unittest_inference.py::test_call_on_instance_with_inherited_dunder_call_method", "tests/unittest_inference.py::TestInferencePropagation::test_call_starargs_propagation", "tests/unittest_inference.py::TestInferencePropagation::test_call_kwargs_propagation", "tests/unittest_inference.py::test_limit_inference_result_amount", "tests/unittest_inference.py::test_attribute_inference_should_not_access_base_classes", "tests/unittest_inference.py::test_attribute_mro_object_inference", "tests/unittest_inference.py::test_inferred_sequence_unpacking_works", "tests/unittest_inference.py::test_recursion_error_inferring_slice", "tests/unittest_inference.py::test_exception_lookup_last_except_handler_wins", "tests/unittest_inference.py::test_exception_lookup_name_bound_in_except_handler", "tests/unittest_inference.py::test_builtin_inference_list_of_exceptions", "tests/unittest_inference.py::test_cannot_getattr_ann_assigns", "tests/unittest_inference.py::test_prevent_recursion_error_in_igetattr_and_context_manager_inference", "tests/unittest_inference.py::test_infer_context_manager_with_unknown_args", "tests/unittest_inference.py::test_subclass_of_exception[\\n", "tests/unittest_inference.py::test_ifexp_inference", "tests/unittest_inference.py::test_assert_last_function_returns_none_on_inference", "tests/unittest_inference.py::test_posonlyargs_inference", "tests/unittest_inference.py::test_infer_args_unpacking_of_self", "tests/unittest_inference.py::test_infer_exception_instance_attributes", "tests/unittest_inference.py::test_inference_is_limited_to_the_boundnode[\\n", "tests/unittest_inference.py::test_property_inference", "tests/unittest_inference.py::test_property_as_string", "tests/unittest_inference.py::test_property_callable_inference", "tests/unittest_inference.py::test_recursion_error_inferring_builtin_containers", "tests/unittest_inference.py::test_inferaugassign_picking_parent_instead_of_stmt", "tests/unittest_inference.py::test_classmethod_from_builtins_inferred_as_bound", "tests/unittest_inference.py::test_infer_dict_passes_context", "tests/unittest_inference.py::test_custom_decorators_for_classmethod_and_staticmethods[\\n", "tests/unittest_inference.py::test_dataclasses_subscript_inference_recursion_error_39", "tests/unittest_inference.py::test_self_reference_infer_does_not_trigger_recursion_error", "tests/unittest_inference.py::test_inferring_properties_multiple_time_does_not_mutate_locals_multiple_times", "tests/unittest_inference.py::test_getattr_fails_on_empty_values", "tests/unittest_inference.py::test_infer_first_argument_of_static_method_in_metaclass", "tests/unittest_inference.py::test_recursion_error_metaclass_monkeypatching", "tests/unittest_inference.py::test_allow_retrieving_instance_attrs_and_special_attrs_for_functions", "tests/unittest_inference.py::test_implicit_parameters_bound_method", "tests/unittest_inference.py::test_super_inference_of_abstract_property", "tests/unittest_inference.py::test_infer_generated_setter", "tests/unittest_inference.py::test_infer_list_of_uninferables_does_not_crash", "tests/unittest_inference.py::test_issue926_infer_stmts_referencing_same_name_is_not_uninferable", "tests/unittest_inference.py::test_issue926_binop_referencing_same_name_is_not_uninferable", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_subclass_property", "tests/unittest_scoped_nodes.py::test_issue940_property_grandchild", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_property", "tests/unittest_scoped_nodes.py::test_issue940_with_metaclass_class_context_property", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_values_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_derived_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor", "tests/unittest_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase", "tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance", "tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef", "tests/unittest_scoped_nodes.py::test_posonlyargs_default_value", "tests/unittest_scoped_nodes.py::test_ancestor_with_generic"], "environment_setup_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1268", "base_commit": "ce5cbce5ba11cdc2f8139ade66feea1e181a7944", "patch": "diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py\n--- a/astroid/nodes/as_string.py\n+++ b/astroid/nodes/as_string.py\n@@ -36,6 +36,7 @@\n MatchSingleton,\n MatchStar,\n MatchValue,\n+ Unknown,\n )\n \n # pylint: disable=unused-argument\n@@ -643,6 +644,9 @@ def visit_property(self, node):\n def visit_evaluatedobject(self, node):\n return node.original.accept(self)\n \n+ def visit_unknown(self, node: \"Unknown\") -> str:\n+ return str(node)\n+\n \n def _import_string(names):\n \"\"\"return a list of (name, asname) formatted as a string\"\"\"\n", "test_patch": "diff --git a/tests/unittest_nodes.py b/tests/unittest_nodes.py\n--- a/tests/unittest_nodes.py\n+++ b/tests/unittest_nodes.py\n@@ -306,6 +306,11 @@ def test_f_strings(self):\n ast = abuilder.string_build(code)\n self.assertEqual(ast.as_string().strip(), code.strip())\n \n+ @staticmethod\n+ def test_as_string_unknown() -> None:\n+ assert nodes.Unknown().as_string() == \"Unknown.Unknown()\"\n+ assert nodes.Unknown(lineno=1, col_offset=0).as_string() == \"Unknown.Unknown()\"\n+\n \n class _NodeTest(unittest.TestCase):\n \"\"\"test transformation of If Node\"\"\"\n", "problem_statement": "'AsStringVisitor' object has no attribute 'visit_unknown'\n```python\r\n>>> import astroid\r\n>>> astroid.nodes.Unknown().as_string()\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 609, in as_string\r\n return AsStringVisitor()(self)\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/as_string.py\", line 56, in __call__\r\n return node.accept(self).replace(DOC_NEWLINE, \"\\n\")\r\n File \"/Users/tusharsadhwani/code/marvin-python/venv/lib/python3.9/site-packages/astroid/nodes/node_ng.py\", line 220, in accept\r\n func = getattr(visitor, \"visit_\" + self.__class__.__name__.lower())\r\nAttributeError: 'AsStringVisitor' object has no attribute 'visit_unknown'\r\n>>> \r\n```\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.8.6-dev0\n", "hints_text": "Thank you for opening the issue.\nI don't believe `Unknown().as_string()` is ever called regularly. AFAIK it's only used during inference. What should the string representation of an `Unknown` node be? So not sure this needs to be addressed.\nProbably just `'Unknown'`.\nIt's mostly only a problem when we do something like this:\n\n```python\ninferred = infer(node)\nif inferred is not Uninferable:\n if inferred.as_string().contains(some_value):\n ...\n```\nSo for the most part, as long as it doesn't crash we're good.", "created_at": "2021-11-21T16:15:23Z", "version": "2.9", "FAIL_TO_PASS": ["tests/unittest_nodes.py::AsStringTest::test_as_string_unknown"], "PASS_TO_PASS": ["tests/unittest_nodes.py::AsStringTest::test_3k_annotations_and_metaclass", "tests/unittest_nodes.py::AsStringTest::test_3k_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string", "tests/unittest_nodes.py::AsStringTest::test_as_string_for_list_containing_uninferable", "tests/unittest_nodes.py::AsStringTest::test_class_def", "tests/unittest_nodes.py::AsStringTest::test_ellipsis", "tests/unittest_nodes.py::AsStringTest::test_f_strings", "tests/unittest_nodes.py::AsStringTest::test_frozenset_as_string", "tests/unittest_nodes.py::AsStringTest::test_func_signature_issue_185", "tests/unittest_nodes.py::AsStringTest::test_int_attribute", "tests/unittest_nodes.py::AsStringTest::test_module2_as_string", "tests/unittest_nodes.py::AsStringTest::test_module_as_string", "tests/unittest_nodes.py::AsStringTest::test_operator_precedence", "tests/unittest_nodes.py::AsStringTest::test_slice_and_subscripts", "tests/unittest_nodes.py::AsStringTest::test_slices", "tests/unittest_nodes.py::AsStringTest::test_tuple_as_string", "tests/unittest_nodes.py::AsStringTest::test_varargs_kwargs_as_string", "tests/unittest_nodes.py::IfNodeTest::test_block_range", "tests/unittest_nodes.py::IfNodeTest::test_if_elif_else_node", "tests/unittest_nodes.py::IfNodeTest::test_if_sys_guard", "tests/unittest_nodes.py::IfNodeTest::test_if_typing_guard", "tests/unittest_nodes.py::TryExceptNodeTest::test_block_range", "tests/unittest_nodes.py::TryFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::TryExceptFinallyNodeTest::test_block_range", "tests/unittest_nodes.py::ImportNodeTest::test_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_as_string", "tests/unittest_nodes.py::ImportNodeTest::test_bad_import_inference", "tests/unittest_nodes.py::ImportNodeTest::test_conditional", "tests/unittest_nodes.py::ImportNodeTest::test_conditional_import", "tests/unittest_nodes.py::ImportNodeTest::test_from_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_import_self_resolve", "tests/unittest_nodes.py::ImportNodeTest::test_more_absolute_import", "tests/unittest_nodes.py::ImportNodeTest::test_real_name", "tests/unittest_nodes.py::CmpNodeTest::test_as_string", "tests/unittest_nodes.py::ConstNodeTest::test_bool", "tests/unittest_nodes.py::ConstNodeTest::test_complex", "tests/unittest_nodes.py::ConstNodeTest::test_copy", "tests/unittest_nodes.py::ConstNodeTest::test_float", "tests/unittest_nodes.py::ConstNodeTest::test_int", "tests/unittest_nodes.py::ConstNodeTest::test_none", "tests/unittest_nodes.py::ConstNodeTest::test_str", "tests/unittest_nodes.py::ConstNodeTest::test_str_kind", "tests/unittest_nodes.py::ConstNodeTest::test_unicode", "tests/unittest_nodes.py::NameNodeTest::test_assign_to_true", "tests/unittest_nodes.py::TestNamedExprNode::test_frame", "tests/unittest_nodes.py::TestNamedExprNode::test_scope", "tests/unittest_nodes.py::AnnAssignNodeTest::test_as_string", "tests/unittest_nodes.py::AnnAssignNodeTest::test_complex", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive", "tests/unittest_nodes.py::AnnAssignNodeTest::test_primitive_without_initial_value", "tests/unittest_nodes.py::ArgumentsNodeTC::test_kwoargs", "tests/unittest_nodes.py::ArgumentsNodeTC::test_positional_only", "tests/unittest_nodes.py::UnboundMethodNodeTest::test_no_super_getattr", "tests/unittest_nodes.py::BoundMethodNodeTest::test_is_property", "tests/unittest_nodes.py::AliasesTest::test_aliases", "tests/unittest_nodes.py::Python35AsyncTest::test_async_await_keywords", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncfor_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_asyncwith_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_await_as_string", "tests/unittest_nodes.py::Python35AsyncTest::test_decorated_async_def_as_string", "tests/unittest_nodes.py::ContextTest::test_list_del", "tests/unittest_nodes.py::ContextTest::test_list_load", "tests/unittest_nodes.py::ContextTest::test_list_store", "tests/unittest_nodes.py::ContextTest::test_starred_load", "tests/unittest_nodes.py::ContextTest::test_starred_store", "tests/unittest_nodes.py::ContextTest::test_subscript_del", "tests/unittest_nodes.py::ContextTest::test_subscript_load", "tests/unittest_nodes.py::ContextTest::test_subscript_store", "tests/unittest_nodes.py::ContextTest::test_tuple_load", "tests/unittest_nodes.py::ContextTest::test_tuple_store", "tests/unittest_nodes.py::test_unknown", "tests/unittest_nodes.py::test_type_comments_with", "tests/unittest_nodes.py::test_type_comments_for", "tests/unittest_nodes.py::test_type_coments_assign", "tests/unittest_nodes.py::test_type_comments_invalid_expression", "tests/unittest_nodes.py::test_type_comments_invalid_function_comments", "tests/unittest_nodes.py::test_type_comments_function", "tests/unittest_nodes.py::test_type_comments_arguments", "tests/unittest_nodes.py::test_type_comments_posonly_arguments", "tests/unittest_nodes.py::test_correct_function_type_comment_parent", "tests/unittest_nodes.py::test_is_generator_for_yield_assignments", "tests/unittest_nodes.py::test_f_string_correct_line_numbering", "tests/unittest_nodes.py::test_assignment_expression", "tests/unittest_nodes.py::test_assignment_expression_in_functiondef", "tests/unittest_nodes.py::test_get_doc", "tests/unittest_nodes.py::test_parse_fstring_debug_mode", "tests/unittest_nodes.py::test_parse_type_comments_with_proper_parent", "tests/unittest_nodes.py::test_const_itered", "tests/unittest_nodes.py::test_is_generator_for_yield_in_while", "tests/unittest_nodes.py::test_is_generator_for_yield_in_if", "tests/unittest_nodes.py::test_is_generator_for_yield_in_aug_assign"], "environment_setup_commit": "0d1211558670cfefd95b39984b8d5f7f34837f32"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-946", "base_commit": "2c109eec6fe3f972c6e8c637fe956431a0d7685c", "patch": "diff --git a/astroid/builder.py b/astroid/builder.py\n--- a/astroid/builder.py\n+++ b/astroid/builder.py\n@@ -67,7 +67,7 @@ def _can_assign_attr(node, attrname):\n else:\n if slots and attrname not in {slot.value for slot in slots}:\n return False\n- return True\n+ return node.qname() != \"builtins.object\"\n \n \n class AstroidBuilder(raw_building.InspectBuilder):\n", "test_patch": "diff --git a/tests/unittest_builder.py b/tests/unittest_builder.py\n--- a/tests/unittest_builder.py\n+++ b/tests/unittest_builder.py\n@@ -28,7 +28,7 @@\n \n import pytest\n \n-from astroid import builder, exceptions, manager, nodes, test_utils, util\n+from astroid import Instance, builder, exceptions, manager, nodes, test_utils, util\n \n from . import resources\n \n@@ -476,6 +476,53 @@ def A_assign_type(self):\n self.assertIn(\"assign_type\", lclass.locals)\n self.assertIn(\"type\", lclass.locals)\n \n+ def test_infer_can_assign_regular_object(self):\n+ mod = builder.parse(\n+ \"\"\"\n+ class A:\n+ pass\n+ a = A()\n+ a.value = \"is set\"\n+ a.other = \"is set\"\n+ \"\"\"\n+ )\n+ obj = list(mod.igetattr(\"a\"))\n+ self.assertEqual(len(obj), 1)\n+ obj = obj[0]\n+ self.assertIsInstance(obj, Instance)\n+ self.assertIn(\"value\", obj.instance_attrs)\n+ self.assertIn(\"other\", obj.instance_attrs)\n+\n+ def test_infer_can_assign_has_slots(self):\n+ mod = builder.parse(\n+ \"\"\"\n+ class A:\n+ __slots__ = ('value',)\n+ a = A()\n+ a.value = \"is set\"\n+ a.other = \"not set\"\n+ \"\"\"\n+ )\n+ obj = list(mod.igetattr(\"a\"))\n+ self.assertEqual(len(obj), 1)\n+ obj = obj[0]\n+ self.assertIsInstance(obj, Instance)\n+ self.assertIn(\"value\", obj.instance_attrs)\n+ self.assertNotIn(\"other\", obj.instance_attrs)\n+\n+ def test_infer_can_assign_no_classdict(self):\n+ mod = builder.parse(\n+ \"\"\"\n+ a = object()\n+ a.value = \"not set\"\n+ \"\"\"\n+ )\n+ obj = list(mod.igetattr(\"a\"))\n+ self.assertEqual(len(obj), 1)\n+ obj = obj[0]\n+ self.assertIsInstance(obj, Instance)\n+ self.assertNotIn(\"value\", obj.instance_attrs)\n+\n def test_augassign_attr(self):\n builder.parse(\n \"\"\"\ndiff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py\n--- a/tests/unittest_scoped_nodes.py\n+++ b/tests/unittest_scoped_nodes.py\n@@ -1430,7 +1430,9 @@ class A:\n pass\n class B:\n pass\n- scope = object()\n+ class Scope:\n+ pass\n+ scope = Scope()\n scope.A = A\n scope.B = B\n class C(scope.A, scope.B):\n", "problem_statement": "Delayed attribute assignment to object() may cause incorrect inference of instance attributes\n@cdce8p: `aiohttp` and `VLCTelnet` turned out to be red herrings. This case fails on current stable versions:\r\n\r\n```python\r\nclass Example:\r\n def prev(self):\r\n pass\r\n def next(self):\r\n pass\r\n def other(self):\r\n pass\r\n\r\n\r\nex = Example()\r\nex.other() # no warning\r\nex.prev() # no warning\r\nex.next() # no warning\r\n\r\nimport typing\r\n\r\nex.other() # no warning\r\nex.prev() # false-positive: not-callable\r\nex.next() # false-positive: not-callable\r\n```\r\n\r\n_Originally posted by @nelfin in https://github.com/PyCQA/astroid/issues/927#issuecomment-818626368_\r\n\r\nI've bisected this down to 78d5537. Pylint 2.3.1 passes this case with 20a7ae5 and fails with 78d5537\n", "hints_text": "Minimal case:\r\n\r\n```python\r\nclass Example:\r\n def func(self):\r\n pass\r\n\r\n\r\nwhatthe = object()\r\nwhatthe.func = None\r\n\r\nex = Example()\r\nex.func() # false-positive: not-callable\r\n```\nNot caused by 78d5537, just revealed by it. `typing` imported `collections`, `collections.OrderedDict` had an ambiguously inferred case that was previously broken by failure with positional-only arguments which was fixed in 78d5537.", "created_at": "2021-04-13T12:30:06Z", "version": "2.5", "FAIL_TO_PASS": ["tests/unittest_builder.py::BuilderTest::test_infer_can_assign_no_classdict"], "PASS_TO_PASS": ["tests/unittest_builder.py::FromToLineNoTest::test_callfunc_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_class_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_decorated_function_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_for_while_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_if_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_try_except_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_try_finally_25_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_try_finally_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_with_lineno", "tests/unittest_builder.py::BuilderTest::test_asstuple", "tests/unittest_builder.py::BuilderTest::test_augassign_attr", "tests/unittest_builder.py::BuilderTest::test_build_constants", "tests/unittest_builder.py::BuilderTest::test_data_build_invalid_x_escape", "tests/unittest_builder.py::BuilderTest::test_data_build_null_bytes", "tests/unittest_builder.py::BuilderTest::test_future_imports", "tests/unittest_builder.py::BuilderTest::test_gen_expr_var_scope", "tests/unittest_builder.py::BuilderTest::test_globals", "tests/unittest_builder.py::BuilderTest::test_infer_can_assign_has_slots", "tests/unittest_builder.py::BuilderTest::test_infer_can_assign_regular_object", "tests/unittest_builder.py::BuilderTest::test_inferred_build", "tests/unittest_builder.py::BuilderTest::test_inferred_dont_pollute", "tests/unittest_builder.py::BuilderTest::test_inspect_build0", "tests/unittest_builder.py::BuilderTest::test_inspect_build1", "tests/unittest_builder.py::BuilderTest::test_inspect_build3", "tests/unittest_builder.py::BuilderTest::test_inspect_build_type_object", "tests/unittest_builder.py::BuilderTest::test_inspect_transform_module", "tests/unittest_builder.py::BuilderTest::test_missing_file", "tests/unittest_builder.py::BuilderTest::test_missing_newline", "tests/unittest_builder.py::BuilderTest::test_newstyle_detection", "tests/unittest_builder.py::BuilderTest::test_no_future_imports", "tests/unittest_builder.py::BuilderTest::test_not_implemented", "tests/unittest_builder.py::BuilderTest::test_object", "tests/unittest_builder.py::BuilderTest::test_package_name", "tests/unittest_builder.py::BuilderTest::test_socket_build", "tests/unittest_builder.py::BuilderTest::test_two_future_imports", "tests/unittest_builder.py::BuilderTest::test_yield_parent", "tests/unittest_builder.py::FileBuildTest::test_class_base_props", "tests/unittest_builder.py::FileBuildTest::test_class_basenames", "tests/unittest_builder.py::FileBuildTest::test_class_instance_attrs", "tests/unittest_builder.py::FileBuildTest::test_class_locals", "tests/unittest_builder.py::FileBuildTest::test_function_base_props", "tests/unittest_builder.py::FileBuildTest::test_function_locals", "tests/unittest_builder.py::FileBuildTest::test_method_base_props", "tests/unittest_builder.py::FileBuildTest::test_method_locals", "tests/unittest_builder.py::FileBuildTest::test_module_base_props", "tests/unittest_builder.py::FileBuildTest::test_module_locals", "tests/unittest_builder.py::FileBuildTest::test_unknown_encoding", "tests/unittest_builder.py::test_module_build_dunder_file", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments", "tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance", "tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef", "tests/unittest_scoped_nodes.py::test_posonlyargs_default_value"], "environment_setup_commit": "d2ae3940a1a374253cc95d8fe83cb96f7a57e843"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-2015", "base_commit": "56a65daf1ba391cc85d1a32a8802cfd0c7b7b2ab", "patch": "diff --git a/astroid/_backport_stdlib_names.py b/astroid/_backport_stdlib_names.py\nnew file mode 100644\n--- /dev/null\n+++ b/astroid/_backport_stdlib_names.py\n@@ -0,0 +1,356 @@\n+# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n+# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE\n+# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt\n+\n+\"\"\"\n+Shim to support Python versions < 3.10 that don't have sys.stdlib_module_names\n+\n+These values were created by cherry-picking the commits from\n+https://bugs.python.org/issue42955 into each version, but may be updated\n+manually if changes are needed.\n+\"\"\"\n+\n+import sys\n+\n+# TODO: Remove this file when Python 3.9 is no longer supported\n+\n+PY_3_7 = frozenset(\n+ {\n+ \"__future__\",\n+ \"_abc\",\n+ \"_ast\",\n+ \"_asyncio\",\n+ \"_bisect\",\n+ \"_blake2\",\n+ \"_bootlocale\",\n+ \"_bz2\",\n+ \"_codecs\",\n+ \"_codecs_cn\",\n+ \"_codecs_hk\",\n+ \"_codecs_iso2022\",\n+ \"_codecs_jp\",\n+ \"_codecs_kr\",\n+ \"_codecs_tw\",\n+ \"_collections\",\n+ \"_collections_abc\",\n+ \"_compat_pickle\",\n+ \"_compression\",\n+ \"_contextvars\",\n+ \"_crypt\",\n+ \"_csv\",\n+ \"_ctypes\",\n+ \"_curses\",\n+ \"_curses_panel\",\n+ \"_datetime\",\n+ \"_dbm\",\n+ \"_decimal\",\n+ \"_dummy_thread\",\n+ \"_elementtree\",\n+ \"_functools\",\n+ \"_gdbm\",\n+ \"_hashlib\",\n+ \"_heapq\",\n+ \"_imp\",\n+ \"_io\",\n+ \"_json\",\n+ \"_locale\",\n+ \"_lsprof\",\n+ \"_lzma\",\n+ \"_markupbase\",\n+ \"_md5\",\n+ \"_msi\",\n+ \"_multibytecodec\",\n+ \"_multiprocessing\",\n+ \"_opcode\",\n+ \"_operator\",\n+ \"_osx_support\",\n+ \"_pickle\",\n+ \"_posixsubprocess\",\n+ \"_py_abc\",\n+ \"_pydecimal\",\n+ \"_pyio\",\n+ \"_queue\",\n+ \"_random\",\n+ \"_sha1\",\n+ \"_sha256\",\n+ \"_sha3\",\n+ \"_sha512\",\n+ \"_signal\",\n+ \"_sitebuiltins\",\n+ \"_socket\",\n+ \"_sqlite3\",\n+ \"_sre\",\n+ \"_ssl\",\n+ \"_stat\",\n+ \"_string\",\n+ \"_strptime\",\n+ \"_struct\",\n+ \"_symtable\",\n+ \"_thread\",\n+ \"_threading_local\",\n+ \"_tkinter\",\n+ \"_tracemalloc\",\n+ \"_uuid\",\n+ \"_warnings\",\n+ \"_weakref\",\n+ \"_weakrefset\",\n+ \"_winapi\",\n+ \"abc\",\n+ \"aifc\",\n+ \"antigravity\",\n+ \"argparse\",\n+ \"array\",\n+ \"ast\",\n+ \"asynchat\",\n+ \"asyncio\",\n+ \"asyncore\",\n+ \"atexit\",\n+ \"audioop\",\n+ \"base64\",\n+ \"bdb\",\n+ \"binascii\",\n+ \"binhex\",\n+ \"bisect\",\n+ \"builtins\",\n+ \"bz2\",\n+ \"cProfile\",\n+ \"calendar\",\n+ \"cgi\",\n+ \"cgitb\",\n+ \"chunk\",\n+ \"cmath\",\n+ \"cmd\",\n+ \"code\",\n+ \"codecs\",\n+ \"codeop\",\n+ \"collections\",\n+ \"colorsys\",\n+ \"compileall\",\n+ \"concurrent\",\n+ \"configparser\",\n+ \"contextlib\",\n+ \"contextvars\",\n+ \"copy\",\n+ \"copyreg\",\n+ \"crypt\",\n+ \"csv\",\n+ \"ctypes\",\n+ \"curses\",\n+ \"dataclasses\",\n+ \"datetime\",\n+ \"dbm\",\n+ \"decimal\",\n+ \"difflib\",\n+ \"dis\",\n+ \"distutils\",\n+ \"doctest\",\n+ \"dummy_threading\",\n+ \"email\",\n+ \"encodings\",\n+ \"ensurepip\",\n+ \"enum\",\n+ \"errno\",\n+ \"faulthandler\",\n+ \"fcntl\",\n+ \"filecmp\",\n+ \"fileinput\",\n+ \"fnmatch\",\n+ \"formatter\",\n+ \"fractions\",\n+ \"ftplib\",\n+ \"functools\",\n+ \"gc\",\n+ \"genericpath\",\n+ \"getopt\",\n+ \"getpass\",\n+ \"gettext\",\n+ \"glob\",\n+ \"grp\",\n+ \"gzip\",\n+ \"hashlib\",\n+ \"heapq\",\n+ \"hmac\",\n+ \"html\",\n+ \"http\",\n+ \"idlelib\",\n+ \"imaplib\",\n+ \"imghdr\",\n+ \"imp\",\n+ \"importlib\",\n+ \"inspect\",\n+ \"io\",\n+ \"ipaddress\",\n+ \"itertools\",\n+ \"json\",\n+ \"keyword\",\n+ \"lib2to3\",\n+ \"linecache\",\n+ \"locale\",\n+ \"logging\",\n+ \"lzma\",\n+ \"macpath\",\n+ \"mailbox\",\n+ \"mailcap\",\n+ \"marshal\",\n+ \"math\",\n+ \"mimetypes\",\n+ \"mmap\",\n+ \"modulefinder\",\n+ \"msilib\",\n+ \"msvcrt\",\n+ \"multiprocessing\",\n+ \"netrc\",\n+ \"nis\",\n+ \"nntplib\",\n+ \"nt\",\n+ \"ntpath\",\n+ \"nturl2path\",\n+ \"numbers\",\n+ \"opcode\",\n+ \"operator\",\n+ \"optparse\",\n+ \"os\",\n+ \"ossaudiodev\",\n+ \"parser\",\n+ \"pathlib\",\n+ \"pdb\",\n+ \"pickle\",\n+ \"pickletools\",\n+ \"pipes\",\n+ \"pkgutil\",\n+ \"platform\",\n+ \"plistlib\",\n+ \"poplib\",\n+ \"posix\",\n+ \"posixpath\",\n+ \"pprint\",\n+ \"profile\",\n+ \"pstats\",\n+ \"pty\",\n+ \"pwd\",\n+ \"py_compile\",\n+ \"pyclbr\",\n+ \"pydoc\",\n+ \"pydoc_data\",\n+ \"pyexpat\",\n+ \"queue\",\n+ \"quopri\",\n+ \"random\",\n+ \"re\",\n+ \"readline\",\n+ \"reprlib\",\n+ \"resource\",\n+ \"rlcompleter\",\n+ \"runpy\",\n+ \"sched\",\n+ \"secrets\",\n+ \"select\",\n+ \"selectors\",\n+ \"shelve\",\n+ \"shlex\",\n+ \"shutil\",\n+ \"signal\",\n+ \"site\",\n+ \"smtpd\",\n+ \"smtplib\",\n+ \"sndhdr\",\n+ \"socket\",\n+ \"socketserver\",\n+ \"spwd\",\n+ \"sqlite3\",\n+ \"sre_compile\",\n+ \"sre_constants\",\n+ \"sre_parse\",\n+ \"ssl\",\n+ \"stat\",\n+ \"statistics\",\n+ \"string\",\n+ \"stringprep\",\n+ \"struct\",\n+ \"subprocess\",\n+ \"sunau\",\n+ \"symbol\",\n+ \"symtable\",\n+ \"sys\",\n+ \"sysconfig\",\n+ \"syslog\",\n+ \"tabnanny\",\n+ \"tarfile\",\n+ \"telnetlib\",\n+ \"tempfile\",\n+ \"termios\",\n+ \"textwrap\",\n+ \"this\",\n+ \"threading\",\n+ \"time\",\n+ \"timeit\",\n+ \"tkinter\",\n+ \"token\",\n+ \"tokenize\",\n+ \"trace\",\n+ \"traceback\",\n+ \"tracemalloc\",\n+ \"tty\",\n+ \"turtle\",\n+ \"turtledemo\",\n+ \"types\",\n+ \"typing\",\n+ \"unicodedata\",\n+ \"unittest\",\n+ \"urllib\",\n+ \"uu\",\n+ \"uuid\",\n+ \"venv\",\n+ \"warnings\",\n+ \"wave\",\n+ \"weakref\",\n+ \"webbrowser\",\n+ \"winreg\",\n+ \"winsound\",\n+ \"wsgiref\",\n+ \"xdrlib\",\n+ \"xml\",\n+ \"xmlrpc\",\n+ \"zipapp\",\n+ \"zipfile\",\n+ \"zipimport\",\n+ \"zlib\",\n+ }\n+)\n+\n+PY_3_8 = frozenset(\n+ PY_3_7\n+ - {\n+ \"macpath\",\n+ }\n+ | {\n+ \"_posixshmem\",\n+ \"_statistics\",\n+ \"_xxsubinterpreters\",\n+ }\n+)\n+\n+PY_3_9 = frozenset(\n+ PY_3_8\n+ - {\n+ \"_dummy_thread\",\n+ \"dummy_threading\",\n+ }\n+ | {\n+ \"_aix_support\",\n+ \"_bootsubprocess\",\n+ \"_peg_parser\",\n+ \"_zoneinfo\",\n+ \"graphlib\",\n+ \"zoneinfo\",\n+ }\n+)\n+\n+if sys.version_info[:2] == (3, 7):\n+ stdlib_module_names = PY_3_7\n+elif sys.version_info[:2] == (3, 8):\n+ stdlib_module_names = PY_3_8\n+elif sys.version_info[:2] == (3, 9):\n+ stdlib_module_names = PY_3_9\n+else:\n+ raise AssertionError(\"This module is only intended as a backport for Python <= 3.9\")\ndiff --git a/astroid/manager.py b/astroid/manager.py\n--- a/astroid/manager.py\n+++ b/astroid/manager.py\n@@ -30,7 +30,7 @@\n get_source_file,\n is_module_name_part_of_extension_package_whitelist,\n is_python_source,\n- is_standard_module,\n+ is_stdlib_module,\n load_module_from_name,\n modpath_from_file,\n )\n@@ -154,7 +154,7 @@ def _build_namespace_module(\n def _can_load_extension(self, modname: str) -> bool:\n if self.always_load_extensions:\n return True\n- if is_standard_module(modname):\n+ if is_stdlib_module(modname):\n return True\n return is_module_name_part_of_extension_package_whitelist(\n modname, self.extension_package_whitelist\ndiff --git a/astroid/modutils.py b/astroid/modutils.py\n--- a/astroid/modutils.py\n+++ b/astroid/modutils.py\n@@ -26,14 +26,20 @@\n import sys\n import sysconfig\n import types\n+import warnings\n from collections.abc import Callable, Iterable, Sequence\n from contextlib import redirect_stderr, redirect_stdout\n from functools import lru_cache\n from pathlib import Path\n \n-from astroid.const import IS_JYTHON, IS_PYPY\n+from astroid.const import IS_JYTHON, IS_PYPY, PY310_PLUS\n from astroid.interpreter._import import spec, util\n \n+if PY310_PLUS:\n+ from sys import stdlib_module_names\n+else:\n+ from astroid._backport_stdlib_names import stdlib_module_names\n+\n logger = logging.getLogger(__name__)\n \n \n@@ -510,6 +516,41 @@ def is_python_source(filename: str | None) -> bool:\n return os.path.splitext(filename)[1][1:] in PY_SOURCE_EXTS\n \n \n+def is_stdlib_module(modname: str) -> bool:\n+ \"\"\"Return: True if the modname is in the standard library\"\"\"\n+ return modname.split(\".\")[0] in stdlib_module_names\n+\n+\n+def module_in_path(modname: str, path: str | Iterable[str]) -> bool:\n+ \"\"\"Try to determine if a module is imported from one of the specified paths\n+\n+ :param modname: name of the module\n+\n+ :param path: paths to consider\n+\n+ :return:\n+ true if the module:\n+ - is located on the path listed in one of the directory in `paths`\n+ \"\"\"\n+\n+ modname = modname.split(\".\")[0]\n+ try:\n+ filename = file_from_modpath([modname])\n+ except ImportError:\n+ # Import failed, we can't check path if we don't know it\n+ return False\n+\n+ if filename is None:\n+ # No filename likely means it's compiled in, or potentially a namespace\n+ return False\n+ filename = _normalize_path(filename)\n+\n+ if isinstance(path, str):\n+ return filename.startswith(_cache_normalize_path(path))\n+\n+ return any(filename.startswith(_cache_normalize_path(entry)) for entry in path)\n+\n+\n def is_standard_module(modname: str, std_path: Iterable[str] | None = None) -> bool:\n \"\"\"Try to guess if a module is a standard python module (by default,\n see `std_path` parameter's description).\n@@ -523,6 +564,12 @@ def is_standard_module(modname: str, std_path: Iterable[str] | None = None) -> b\n - is located on the path listed in one of the directory in `std_path`\n - is a built-in module\n \"\"\"\n+ warnings.warn(\n+ \"is_standard_module() is deprecated. Use, is_stdlib_module() or module_in_path() instead\",\n+ DeprecationWarning,\n+ stacklevel=2,\n+ )\n+\n modname = modname.split(\".\")[0]\n try:\n filename = file_from_modpath([modname])\n", "test_patch": "diff --git a/tests/test_manager.py b/tests/test_manager.py\n--- a/tests/test_manager.py\n+++ b/tests/test_manager.py\n@@ -22,7 +22,7 @@\n AttributeInferenceError,\n )\n from astroid.interpreter._import import util\n-from astroid.modutils import EXT_LIB_DIRS, is_standard_module\n+from astroid.modutils import EXT_LIB_DIRS, module_in_path\n from astroid.nodes import Const\n from astroid.nodes.scoped_nodes import ClassDef\n \n@@ -411,7 +411,7 @@ def test_clear_cache_clears_other_lru_caches(self) -> None:\n \n # Generate some hits and misses\n ClassDef().lookup(\"garbage\")\n- is_standard_module(\"unittest\", std_path=[\"garbage_path\"])\n+ module_in_path(\"unittest\", \"garbage_path\")\n util.is_namespace(\"unittest\")\n astroid.interpreter.objectmodel.ObjectModel().attributes()\n with pytest.raises(AttributeInferenceError):\ndiff --git a/tests/test_modutils.py b/tests/test_modutils.py\n--- a/tests/test_modutils.py\n+++ b/tests/test_modutils.py\n@@ -20,6 +20,7 @@\n \n import astroid\n from astroid import modutils\n+from astroid.const import PY310_PLUS\n from astroid.interpreter._import import spec\n \n from . import resources\n@@ -287,7 +288,7 @@ def test_raise(self) -> None:\n self.assertRaises(modutils.NoSourceFile, modutils.get_source_file, \"whatever\")\n \n \n-class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase):\n+class IsStandardModuleTest(resources.SysPathSetup, unittest.TestCase):\n \"\"\"\n Return true if the module may be considered as a module from the standard\n library.\n@@ -296,50 +297,153 @@ class StandardLibModuleTest(resources.SysPathSetup, unittest.TestCase):\n def test_datetime(self) -> None:\n # This is an interesting example, since datetime, on pypy,\n # is under lib_pypy, rather than the usual Lib directory.\n- self.assertTrue(modutils.is_standard_module(\"datetime\"))\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"datetime\")\n \n def test_builtins(self) -> None:\n- self.assertFalse(modutils.is_standard_module(\"__builtin__\"))\n- self.assertTrue(modutils.is_standard_module(\"builtins\"))\n+ with pytest.warns(DeprecationWarning):\n+ assert not modutils.is_standard_module(\"__builtin__\")\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"builtins\")\n \n def test_builtin(self) -> None:\n- self.assertTrue(modutils.is_standard_module(\"sys\"))\n- self.assertTrue(modutils.is_standard_module(\"marshal\"))\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"sys\")\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"marshal\")\n \n def test_nonstandard(self) -> None:\n- self.assertFalse(modutils.is_standard_module(\"astroid\"))\n+ with pytest.warns(DeprecationWarning):\n+ assert not modutils.is_standard_module(\"astroid\")\n \n def test_unknown(self) -> None:\n- self.assertFalse(modutils.is_standard_module(\"unknown\"))\n+ with pytest.warns(DeprecationWarning):\n+ assert not modutils.is_standard_module(\"unknown\")\n \n def test_4(self) -> None:\n- self.assertTrue(modutils.is_standard_module(\"hashlib\"))\n- self.assertTrue(modutils.is_standard_module(\"pickle\"))\n- self.assertTrue(modutils.is_standard_module(\"email\"))\n- self.assertTrue(modutils.is_standard_module(\"io\"))\n- self.assertFalse(modutils.is_standard_module(\"StringIO\"))\n- self.assertTrue(modutils.is_standard_module(\"unicodedata\"))\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"hashlib\")\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"pickle\")\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"email\")\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"io\")\n+ with pytest.warns(DeprecationWarning):\n+ assert not modutils.is_standard_module(\"StringIO\")\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"unicodedata\")\n \n def test_custom_path(self) -> None:\n datadir = resources.find(\"\")\n if any(datadir.startswith(p) for p in modutils.EXT_LIB_DIRS):\n self.skipTest(\"known breakage of is_standard_module on installed package\")\n \n- self.assertTrue(modutils.is_standard_module(\"data.module\", (datadir,)))\n- self.assertTrue(\n- modutils.is_standard_module(\"data.module\", (os.path.abspath(datadir),))\n- )\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"data.module\", (datadir,))\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\n+ \"data.module\", (os.path.abspath(datadir),)\n+ )\n # \"\" will evaluate to cwd\n- self.assertTrue(modutils.is_standard_module(\"data.module\", (\"\",)))\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"data.module\", (\"\",))\n \n def test_failing_edge_cases(self) -> None:\n # using a subpackage/submodule path as std_path argument\n- self.assertFalse(modutils.is_standard_module(\"xml.etree\", etree.__path__))\n+ with pytest.warns(DeprecationWarning):\n+ assert not modutils.is_standard_module(\"xml.etree\", etree.__path__)\n+ # using a module + object name as modname argument\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"sys.path\")\n+ # this is because only the first package/module is considered\n+ with pytest.warns(DeprecationWarning):\n+ assert modutils.is_standard_module(\"sys.whatever\")\n+ with pytest.warns(DeprecationWarning):\n+ assert not modutils.is_standard_module(\"xml.whatever\", etree.__path__)\n+\n+\n+class IsStdLibModuleTest(resources.SysPathSetup, unittest.TestCase):\n+ \"\"\"\n+ Return true if the module is path of the standard library\n+ \"\"\"\n+\n+ def test_datetime(self) -> None:\n+ # This is an interesting example, since datetime, on pypy,\n+ # is under lib_pypy, rather than the usual Lib directory.\n+ assert modutils.is_stdlib_module(\"datetime\")\n+\n+ def test_builtins(self) -> None:\n+ assert not modutils.is_stdlib_module(\"__builtin__\")\n+ assert modutils.is_stdlib_module(\"builtins\")\n+\n+ def test_builtin(self) -> None:\n+ assert modutils.is_stdlib_module(\"sys\")\n+ assert modutils.is_stdlib_module(\"marshal\")\n+\n+ def test_nonstandard(self) -> None:\n+ assert not modutils.is_stdlib_module(\"astroid\")\n+\n+ def test_unknown(self) -> None:\n+ assert not modutils.is_stdlib_module(\"unknown\")\n+\n+ def test_4(self) -> None:\n+ assert modutils.is_stdlib_module(\"hashlib\")\n+ assert modutils.is_stdlib_module(\"pickle\")\n+ assert modutils.is_stdlib_module(\"email\")\n+ assert modutils.is_stdlib_module(\"io\")\n+ assert not modutils.is_stdlib_module(\"StringIO\")\n+ assert modutils.is_stdlib_module(\"unicodedata\")\n+\n+ def test_subpackages(self) -> None:\n # using a module + object name as modname argument\n- self.assertTrue(modutils.is_standard_module(\"sys.path\"))\n+ assert modutils.is_stdlib_module(\"sys.path\")\n # this is because only the first package/module is considered\n- self.assertTrue(modutils.is_standard_module(\"sys.whatever\"))\n- self.assertFalse(modutils.is_standard_module(\"xml.whatever\", etree.__path__))\n+ assert modutils.is_stdlib_module(\"sys.whatever\")\n+\n+ def test_platform_specific(self) -> None:\n+ assert modutils.is_stdlib_module(\"_curses\")\n+ assert modutils.is_stdlib_module(\"msvcrt\")\n+ assert modutils.is_stdlib_module(\"termios\")\n+\n+\n+class ModuleInPathTest(resources.SysPathSetup, unittest.TestCase):\n+ \"\"\"\n+ Return true if the module is imported from the specified path\n+ \"\"\"\n+\n+ def test_success(self) -> None:\n+ datadir = resources.find(\"\")\n+ assert modutils.module_in_path(\"data.module\", datadir)\n+ assert modutils.module_in_path(\"data.module\", (datadir,))\n+ assert modutils.module_in_path(\"data.module\", os.path.abspath(datadir))\n+ # \"\" will evaluate to cwd\n+ assert modutils.module_in_path(\"data.module\", \"\")\n+\n+ def test_bad_import(self) -> None:\n+ datadir = resources.find(\"\")\n+ assert not modutils.module_in_path(\"this_module_is_no_more\", datadir)\n+\n+ def test_no_filename(self) -> None:\n+ datadir = resources.find(\"\")\n+ assert not modutils.module_in_path(\"sys\", datadir)\n+\n+ def test_failure(self) -> None:\n+ datadir = resources.find(\"\")\n+ assert not modutils.module_in_path(\"etree\", datadir)\n+ assert not modutils.module_in_path(\"astroid\", datadir)\n+\n+\n+class BackportStdlibNamesTest(resources.SysPathSetup, unittest.TestCase):\n+ \"\"\"\n+ Verify backport raises exception on newer versions\n+ \"\"\"\n+\n+ @pytest.mark.skipif(not PY310_PLUS, reason=\"Backport valid on <=3.9\")\n+ def test_import_error(self) -> None:\n+ with pytest.raises(AssertionError):\n+ # pylint: disable-next=import-outside-toplevel, unused-import\n+ from astroid import _backport_stdlib_names # noqa\n \n \n class IsRelativeTest(unittest.TestCase):\n", "problem_statement": "Replace modutils.is_standard_module() logic with sys.stdlib_module_names\n\r\nThis extends from the conversation in https://github.com/PyCQA/pylint/pull/8190.\r\n\r\nThe logic in `modutils.is_standard_module()` should largely be able to be replaced with [sys.stdlib_module_names](https://docs.python.org/3/library/sys.html#sys.stdlib_module_names), which was introduced in 3.10. The advantages are it will be faster (no imports, no filesystem traversal), it's not dependent on the local environment, and it's maintained upstream, generated from source. For the referenced PR, I backported the generating code in CPython to generate sets for a shim to support 3.7 - 3.9.\r\n\r\nI started working on a PR for Astroid, but it seems `modutils.is_standard_module()` actually does two different things depending on how it's called.\r\n1. If no path is specified, it tries to determine if a module is part of the standard library (or a builtin, or compiled in) by inspecting the path of module after importing it.\r\n2. If a path is specified, it does the same logic, but ultimately is determining if the module is in the path specified.\r\n\r\nFor the second case, I could only find one case in the wild, in pyreverse.\r\n\r\nhttps://github.com/PyCQA/pylint/blob/5bc4cd9a4b4c240227a41786823a6f226864dc4b/pylint/pyreverse/inspector.py#L308\r\n\r\nThese seem like different behaviors to me. I'm unsure how to proceed with PR. Here are some options I've considered.\r\n\r\n- Option 1:\r\n - Introduce a new function, basically a wrapper for sys.stdlib_module_names and the shim\r\n - Old behavior is preserved\r\n - Advantage of a function, even though it's very simple, is it provides a space to add overriding logic if needed down the road\r\n \r\n- Option 2:\r\n - Only introduce the shim, so the code is in a common place for Astroid and Pylint\r\n - Can be dropped with 3.9\r\n - Old behavior is preserved\r\n\r\n- Option 3:\r\n - Fall back to old behavior if a path is given, check sys.stdlib_module_names otherwise\r\n\r\n- Option 4:\r\n - Deprecate `is_standard_module()`\r\n - Introduce new functions more specific to how they are used\r\n\r\n- Option 5:\r\n - Do Nothing\r\n\r\nI'm sure there are more options, but this is what comes to mind now. Would appreciate your thoughts and ideas.\r\n\n", "hints_text": "Option 4 seems best to me. I would even be okay with completely removing the weird behaviour described in point 2 and adding a new function that `pyreverse` can use. Imo, if we have a clear changelog entry for this it shouldn't be considered a breaking change, it is very weird that that behaviour exists in the first place.\r\n\r\nPlease go ahead with the PR! Any work on `astroid` is always highly appreciated!", "created_at": "2023-02-08T15:09:47Z", "version": "2.15", "FAIL_TO_PASS": ["tests/test_manager.py::AstroidManagerTest::test_ast_from_class", "tests/test_manager.py::AstroidManagerTest::test_ast_from_class_attr_error", "tests/test_manager.py::AstroidManagerTest::test_ast_from_class_with_module", "tests/test_manager.py::AstroidManagerTest::test_ast_from_file", "tests/test_manager.py::AstroidManagerTest::test_ast_from_file_astro_builder", "tests/test_manager.py::AstroidManagerTest::test_ast_from_file_cache", "tests/test_manager.py::AstroidManagerTest::test_ast_from_file_name_astro_builder_exception", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module_cache", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_astro_builder_exception", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_egg", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_not_python_source", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_pyz", "tests/test_manager.py::AstroidManagerTest::test_ast_from_module_name_zip", "tests/test_manager.py::AstroidManagerTest::test_ast_from_namespace_pkg_resources", "tests/test_manager.py::AstroidManagerTest::test_ast_from_namespace_pkgutil", "tests/test_manager.py::AstroidManagerTest::test_ast_from_string", "tests/test_manager.py::AstroidManagerTest::test_do_not_expose_main", "tests/test_manager.py::AstroidManagerTest::test_failed_import_hooks", "tests/test_manager.py::AstroidManagerTest::test_file_from_module", "tests/test_manager.py::AstroidManagerTest::test_file_from_module_name_astro_building_exception", "tests/test_manager.py::AstroidManagerTest::test_implicit_namespace_package", "tests/test_manager.py::AstroidManagerTest::test_module_is_not_namespace", "tests/test_manager.py::AstroidManagerTest::test_module_unexpectedly_missing_path", "tests/test_manager.py::AstroidManagerTest::test_module_unexpectedly_missing_spec", "tests/test_manager.py::AstroidManagerTest::test_module_unexpectedly_spec_is_none", "tests/test_manager.py::AstroidManagerTest::test_namespace_and_file_mismatch", "tests/test_manager.py::AstroidManagerTest::test_namespace_package_pth_support", "tests/test_manager.py::AstroidManagerTest::test_nested_namespace_import", "tests/test_manager.py::AstroidManagerTest::test_raises_exception_for_empty_modname", "tests/test_manager.py::AstroidManagerTest::test_same_name_import_module", "tests/test_manager.py::AstroidManagerTest::test_submodule_homonym_with_non_module", "tests/test_manager.py::AstroidManagerTest::test_zip_import_data", "tests/test_manager.py::AstroidManagerTest::test_zip_import_data_without_zipimport", "tests/test_manager.py::BorgAstroidManagerTC::test_borg", "tests/test_manager.py::ClearCacheTest::test_brain_plugins_reloaded_after_clearing_cache", "tests/test_manager.py::ClearCacheTest::test_builtins_inference_after_clearing_cache", "tests/test_manager.py::ClearCacheTest::test_builtins_inference_after_clearing_cache_manually", "tests/test_manager.py::ClearCacheTest::test_clear_cache_clears_other_lru_caches", "tests/test_modutils.py::ModuleFileTest::test_find_egg_module", "tests/test_modutils.py::ModuleFileTest::test_find_zipped_module", "tests/test_modutils.py::LoadModuleFromNameTest::test_known_values_load_module_from_name_1", "tests/test_modutils.py::LoadModuleFromNameTest::test_known_values_load_module_from_name_2", "tests/test_modutils.py::LoadModuleFromNameTest::test_raise_load_module_from_name_1", "tests/test_modutils.py::test_import_dotted_library", "tests/test_modutils.py::GetModulePartTest::test_get_module_part_exception", "tests/test_modutils.py::GetModulePartTest::test_known_values_get_builtin_module_part", "tests/test_modutils.py::GetModulePartTest::test_known_values_get_compiled_module_part", "tests/test_modutils.py::GetModulePartTest::test_known_values_get_module_part_1", "tests/test_modutils.py::GetModulePartTest::test_known_values_get_module_part_2", "tests/test_modutils.py::GetModulePartTest::test_known_values_get_module_part_3", "tests/test_modutils.py::ModPathFromFileTest::test_import_symlink_both_outside_of_path", "tests/test_modutils.py::ModPathFromFileTest::test_import_symlink_with_source_outside_of_path", "tests/test_modutils.py::ModPathFromFileTest::test_known_values_modpath_from_file_1", "tests/test_modutils.py::ModPathFromFileTest::test_load_from_module_symlink_on_symlinked_paths_in_syspath", "tests/test_modutils.py::ModPathFromFileTest::test_load_packages_without_init", "tests/test_modutils.py::ModPathFromFileTest::test_raise_modpath_from_file_exception", "tests/test_modutils.py::LoadModuleFromPathTest::test_do_not_load_twice", "tests/test_modutils.py::FileFromModPathTest::test_builtin", "tests/test_modutils.py::FileFromModPathTest::test_site_packages", "tests/test_modutils.py::FileFromModPathTest::test_std_lib", "tests/test_modutils.py::FileFromModPathTest::test_unexisting", "tests/test_modutils.py::FileFromModPathTest::test_unicode_in_package_init", "tests/test_modutils.py::GetSourceFileTest::test", "tests/test_modutils.py::GetSourceFileTest::test_raise", "tests/test_modutils.py::IsStandardModuleTest::test_4", "tests/test_modutils.py::IsStandardModuleTest::test_builtin", "tests/test_modutils.py::IsStandardModuleTest::test_builtins", "tests/test_modutils.py::IsStandardModuleTest::test_custom_path", "tests/test_modutils.py::IsStandardModuleTest::test_datetime", "tests/test_modutils.py::IsStandardModuleTest::test_failing_edge_cases", "tests/test_modutils.py::IsStandardModuleTest::test_nonstandard", "tests/test_modutils.py::IsStandardModuleTest::test_unknown", "tests/test_modutils.py::IsStdLibModuleTest::test_4", "tests/test_modutils.py::IsStdLibModuleTest::test_builtin", "tests/test_modutils.py::IsStdLibModuleTest::test_builtins", "tests/test_modutils.py::IsStdLibModuleTest::test_datetime", "tests/test_modutils.py::IsStdLibModuleTest::test_nonstandard", "tests/test_modutils.py::IsStdLibModuleTest::test_platform_specific", "tests/test_modutils.py::IsStdLibModuleTest::test_subpackages", "tests/test_modutils.py::IsStdLibModuleTest::test_unknown", "tests/test_modutils.py::ModuleInPathTest::test_bad_import", "tests/test_modutils.py::ModuleInPathTest::test_failure", "tests/test_modutils.py::ModuleInPathTest::test_no_filename", "tests/test_modutils.py::ModuleInPathTest::test_success", "tests/test_modutils.py::IsRelativeTest::test_deep_relative", "tests/test_modutils.py::IsRelativeTest::test_deep_relative2", "tests/test_modutils.py::IsRelativeTest::test_deep_relative3", "tests/test_modutils.py::IsRelativeTest::test_deep_relative4", "tests/test_modutils.py::IsRelativeTest::test_is_relative_bad_path", "tests/test_modutils.py::IsRelativeTest::test_known_values_is_relative_1", "tests/test_modutils.py::IsRelativeTest::test_known_values_is_relative_3", "tests/test_modutils.py::IsRelativeTest::test_known_values_is_relative_4", "tests/test_modutils.py::IsRelativeTest::test_known_values_is_relative_5", "tests/test_modutils.py::GetModuleFilesTest::test_get_all_files", "tests/test_modutils.py::GetModuleFilesTest::test_get_module_files_1", "tests/test_modutils.py::GetModuleFilesTest::test_load_module_set_attribute", "tests/test_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_success", "tests/test_modutils.py::ExtensionPackageWhitelistTest::test_is_module_name_part_of_extension_package_whitelist_true"], "PASS_TO_PASS": [], "environment_setup_commit": "29b42e5e9745b172d5980511d14efeac745a5a82"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1262", "base_commit": "e840a7c54d3d8b5be2db1e66f34a5368c64fc3f7", "patch": "diff --git a/astroid/nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes.py\n--- a/astroid/nodes/scoped_nodes.py\n+++ b/astroid/nodes/scoped_nodes.py\n@@ -389,10 +389,8 @@ class Module(LocalsDictNodeNG):\n \n :type: int or None\n \"\"\"\n- lineno = 0\n+ lineno: Literal[0] = 0\n \"\"\"The line that this node appears on in the source code.\n-\n- :type: int or None\n \"\"\"\n \n # attributes below are set by the builder module or by raw factories\n@@ -469,7 +467,6 @@ class Module(LocalsDictNodeNG):\n )\n _other_other_fields = (\"locals\", \"globals\")\n \n- lineno: None\n col_offset: None\n end_lineno: None\n end_col_offset: None\n@@ -512,7 +509,6 @@ def __init__(\n self.file = file\n self.path = path\n self.package = package\n- self.parent = parent\n self.pure_python = pure_python\n self.locals = self.globals = {}\n \"\"\"A map of the name of a local variable to the node defining the local.\n@@ -526,6 +522,8 @@ def __init__(\n \"\"\"\n self.future_imports = set()\n \n+ super().__init__(lineno=0, parent=parent)\n+\n # pylint: enable=redefined-builtin\n \n def postinit(self, body=None):\n", "test_patch": "diff --git a/tests/unittest_nodes_lineno.py b/tests/unittest_nodes_lineno.py\n--- a/tests/unittest_nodes_lineno.py\n+++ b/tests/unittest_nodes_lineno.py\n@@ -2,6 +2,7 @@\n \n import pytest\n \n+import astroid\n from astroid import builder, nodes\n from astroid.const import PY38_PLUS, PY39_PLUS, PY310_PLUS\n \n@@ -1221,3 +1222,14 @@ class X(Parent, var=42):\n assert (c1.body[0].lineno, c1.body[0].col_offset) == (4, 4)\n assert (c1.body[0].end_lineno, c1.body[0].end_col_offset) == (4, 8)\n # fmt: on\n+\n+ @staticmethod\n+ def test_end_lineno_module() -> None:\n+ \"\"\"Tests for Module\"\"\"\n+ code = \"\"\"print()\"\"\"\n+ module = astroid.parse(code)\n+ assert isinstance(module, nodes.Module)\n+ assert module.lineno == 0\n+ assert module.col_offset is None\n+ assert module.end_lineno is None\n+ assert module.end_col_offset is None\n", "problem_statement": "``nodes.Module`` don't have a ``end_lineno`` and ``end_col_offset``\n### Steps to reproduce\r\n\r\n```python\r\nimport astroid\r\n\r\ncode = \"\"\"\r\n print(\"a module\")\r\n \"\"\"\r\n\r\nmodule = astroid.parse(code)\r\nprint(module.end_lineno)\r\nprint(module.end_col_offset)\r\n```\r\n\r\n### Current behavior\r\n\r\n`AttributeError` on both of the last lines.\r\n\r\n### Expected behavior\r\n\r\n@cdce8p Let me know if I misunderstood you, but I thought we wanted these to be accessible on all nodes, just initialised as `None`.\r\nIf that was not the case, I would make the case to do so as it allows you to do `node.end_lineno` without running in to `AttributeError`'s.\r\n\r\n### Version\r\n\r\nLatest `main`.\r\n\n", "hints_text": "", "created_at": "2021-11-19T16:46:31Z", "version": "2.9", "FAIL_TO_PASS": ["tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_module"], "PASS_TO_PASS": ["tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_container", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_name", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_attribute", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_call", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_assignment", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_stmts", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_nodes", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_ops", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_if", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_for", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_const", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_function", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_dict", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_try", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_subscript", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_import", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_with", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_while", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_string", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_comprehension", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_class"], "environment_setup_commit": "0d1211558670cfefd95b39984b8d5f7f34837f32"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1351", "base_commit": "cfd9e74f7b4cbac08357cadec03c736501368afa", "patch": "diff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py\n--- a/astroid/nodes/node_ng.py\n+++ b/astroid/nodes/node_ng.py\n@@ -438,6 +438,8 @@ def fromlineno(self) -> Optional[int]:\n @decorators.cachedproperty\n def tolineno(self) -> Optional[int]:\n \"\"\"The last line that this node appears on in the source code.\"\"\"\n+ if self.end_lineno is not None:\n+ return self.end_lineno\n if not self._astroid_fields:\n # can't have children\n last_child = None\ndiff --git a/astroid/rebuilder.py b/astroid/rebuilder.py\n--- a/astroid/rebuilder.py\n+++ b/astroid/rebuilder.py\n@@ -2125,11 +2125,21 @@ def visit_starred(self, node: \"ast.Starred\", parent: NodeNG) -> nodes.Starred:\n def visit_tryexcept(self, node: \"ast.Try\", parent: NodeNG) -> nodes.TryExcept:\n \"\"\"visit a TryExcept node by returning a fresh instance of it\"\"\"\n if sys.version_info >= (3, 8):\n+ # TryExcept excludes the 'finally' but that will be included in the\n+ # end_lineno from 'node'. Therefore, we check all non 'finally'\n+ # children to find the correct end_lineno and column.\n+ end_lineno = node.end_lineno\n+ end_col_offset = node.end_col_offset\n+ all_children: List[\"ast.AST\"] = [*node.body, *node.handlers, *node.orelse]\n+ for child in reversed(all_children):\n+ end_lineno = child.end_lineno\n+ end_col_offset = child.end_col_offset\n+ break\n newnode = nodes.TryExcept(\n lineno=node.lineno,\n col_offset=node.col_offset,\n- end_lineno=node.end_lineno,\n- end_col_offset=node.end_col_offset,\n+ end_lineno=end_lineno,\n+ end_col_offset=end_col_offset,\n parent=parent,\n )\n else:\n", "test_patch": "diff --git a/tests/unittest_builder.py b/tests/unittest_builder.py\n--- a/tests/unittest_builder.py\n+++ b/tests/unittest_builder.py\n@@ -71,11 +71,14 @@ def test_callfunc_lineno(self) -> None:\n strarg = callfunc.args[0]\n self.assertIsInstance(strarg, nodes.Const)\n if hasattr(sys, \"pypy_version_info\"):\n- lineno = 4\n+ self.assertEqual(strarg.fromlineno, 4)\n+ self.assertEqual(strarg.tolineno, 4)\n else:\n- lineno = 5 if not PY38_PLUS else 4\n- self.assertEqual(strarg.fromlineno, lineno)\n- self.assertEqual(strarg.tolineno, lineno)\n+ if not PY38_PLUS:\n+ self.assertEqual(strarg.fromlineno, 5)\n+ else:\n+ self.assertEqual(strarg.fromlineno, 4)\n+ self.assertEqual(strarg.tolineno, 5)\n namearg = callfunc.args[1]\n self.assertIsInstance(namearg, nodes.Name)\n self.assertEqual(namearg.fromlineno, 5)\ndiff --git a/tests/unittest_nodes_lineno.py b/tests/unittest_nodes_lineno.py\n--- a/tests/unittest_nodes_lineno.py\n+++ b/tests/unittest_nodes_lineno.py\n@@ -784,7 +784,7 @@ def test_end_lineno_try() -> None:\n assert (t3.lineno, t3.col_offset) == (10, 0)\n assert (t3.end_lineno, t3.end_col_offset) == (17, 8)\n assert (t3.body[0].lineno, t3.body[0].col_offset) == (10, 0)\n- assert (t3.body[0].end_lineno, t3.body[0].end_col_offset) == (17, 8)\n+ assert (t3.body[0].end_lineno, t3.body[0].end_col_offset) == (15, 8)\n assert (t3.finalbody[0].lineno, t3.finalbody[0].col_offset) == (17, 4)\n assert (t3.finalbody[0].end_lineno, t3.finalbody[0].end_col_offset) == (17, 8)\n \ndiff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py\n--- a/tests/unittest_scoped_nodes.py\n+++ b/tests/unittest_scoped_nodes.py\n@@ -1092,15 +1092,19 @@ def g1(x):\n print(x)\n \n @f(a=2,\n- b=3)\n+ b=3,\n+ )\n def g2():\n pass\n \"\"\"\n astroid = builder.parse(data)\n self.assertEqual(astroid[\"g1\"].fromlineno, 4)\n self.assertEqual(astroid[\"g1\"].tolineno, 5)\n- self.assertEqual(astroid[\"g2\"].fromlineno, 9)\n- self.assertEqual(astroid[\"g2\"].tolineno, 10)\n+ if not PY38_PLUS:\n+ self.assertEqual(astroid[\"g2\"].fromlineno, 9)\n+ else:\n+ self.assertEqual(astroid[\"g2\"].fromlineno, 10)\n+ self.assertEqual(astroid[\"g2\"].tolineno, 11)\n \n def test_metaclass_error(self) -> None:\n astroid = builder.parse(\n", "problem_statement": "Decorator.toline is off by 1\n### Steps to reproduce\r\n\r\nI came across this inconsistency while debugging why pylint reports `missing-docstring` on the wrong line for the `g2` function in the example. As it turns out, the `toline` of the decorator seems to point to `b=3,` instead of `)`.\r\n\r\n```python\r\nimport ast\r\nimport astroid\r\n\r\nsource = \"\"\"\\\r\n@f(a=2,\r\n b=3,\r\n)\r\ndef g2():\r\n pass\r\n\"\"\"\r\n\r\n[f] = ast.parse(source).body\r\n[deco] = f.decorator_list\r\nprint(\"ast\", deco.lineno, deco.end_lineno)\r\n\r\n[f] = astroid.parse(source).body\r\n[deco] = f.decorators.nodes\r\nprint(\"astroid\", deco.fromlineno, deco.tolineno)\r\n```\r\n\r\n### Current behavior\r\n\r\n```\r\nast 1 3\r\nastroid 1 2\r\n```\r\n\r\n### Expected behavior\r\n\r\n```\r\nast 1 3\r\nastroid 1 3\r\n```\r\n\r\n### `python -c \"from astroid import __pkginfo__; print(__pkginfo__.version)\"` output\r\n\r\n2.9.3\n", "hints_text": "Actually, it seems a decorator is a red herring here, because I get the same off by one issue simply parsing a call\r\n\r\n```python\r\nsource = \"\"\"\\\r\nf(a=2,\r\n b=3,\r\n)\r\n\"\"\"\r\n\r\n[call] = ast.parse(source).body\r\nprint(\"ast\", call.lineno, call.end_lineno)\r\n\r\n[call] = astroid.parse(source).body\r\nprint(\"astroid\", call.fromlineno, call.tolineno)\r\n```\r\n\r\nwhich outputs\r\n\r\n```\r\nast 1 3\r\nastroid 1 2\r\n```\nOkay, this seems to be caused by the implementation of `NodeNG.tolineno` which uses the last line of the *child* to approximate the last line of the parent:\r\n\r\nhttps://github.com/PyCQA/astroid/blob/03efcc3f86b88bab3080fe69119ee4c69e4afd0a/astroid/nodes/node_ng.py#L437-L446\r\n\r\nOnce possible fix is to override `tolineno` in `Call`. Wdyt?\n> this seems to be caused by the implementation of NodeNG.tolineno which uses the last line of the child to approximate the last line of the parent:\r\n\r\nNaive question, would it be possible to use the last line of the node instead, directly in NodeNG ?\nYeah, I think that should work with a caveat that the `ast` module only reports end line/column since Python 3.8. I'll draft a PR.\n@superbobry I was looking at `tolineno` recently. I was wondering if it would make sense to add a check for >= 3.8 and then just use the `end_lineno` attribute that was added recently. No need to reinvent the wheel on those versions.\r\n\r\nPerhaps that's a bit out of the scope of the PR you were going to draft, but it might help!", "created_at": "2022-01-14T21:14:48Z", "version": "2.10", "FAIL_TO_PASS": ["tests/unittest_builder.py::FromToLineNoTest::test_callfunc_lineno", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_try", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_function_with_decorator_lineno"], "PASS_TO_PASS": ["tests/unittest_builder.py::FromToLineNoTest::test_class_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_decorated_function_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_for_while_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_if_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_try_except_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_try_finally_25_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_try_finally_lineno", "tests/unittest_builder.py::FromToLineNoTest::test_with_lineno", "tests/unittest_builder.py::BuilderTest::test_asstuple", "tests/unittest_builder.py::BuilderTest::test_augassign_attr", "tests/unittest_builder.py::BuilderTest::test_build_constants", "tests/unittest_builder.py::BuilderTest::test_data_build_invalid_x_escape", "tests/unittest_builder.py::BuilderTest::test_data_build_null_bytes", "tests/unittest_builder.py::BuilderTest::test_future_imports", "tests/unittest_builder.py::BuilderTest::test_gen_expr_var_scope", "tests/unittest_builder.py::BuilderTest::test_globals", "tests/unittest_builder.py::BuilderTest::test_infer_can_assign_has_slots", "tests/unittest_builder.py::BuilderTest::test_infer_can_assign_no_classdict", "tests/unittest_builder.py::BuilderTest::test_infer_can_assign_regular_object", "tests/unittest_builder.py::BuilderTest::test_inferred_build", "tests/unittest_builder.py::BuilderTest::test_inferred_dont_pollute", "tests/unittest_builder.py::BuilderTest::test_inspect_build0", "tests/unittest_builder.py::BuilderTest::test_inspect_build1", "tests/unittest_builder.py::BuilderTest::test_inspect_build3", "tests/unittest_builder.py::BuilderTest::test_inspect_build_type_object", "tests/unittest_builder.py::BuilderTest::test_inspect_transform_module", "tests/unittest_builder.py::BuilderTest::test_missing_file", "tests/unittest_builder.py::BuilderTest::test_missing_newline", "tests/unittest_builder.py::BuilderTest::test_newstyle_detection", "tests/unittest_builder.py::BuilderTest::test_no_future_imports", "tests/unittest_builder.py::BuilderTest::test_not_implemented", "tests/unittest_builder.py::BuilderTest::test_object", "tests/unittest_builder.py::BuilderTest::test_package_name", "tests/unittest_builder.py::BuilderTest::test_socket_build", "tests/unittest_builder.py::BuilderTest::test_two_future_imports", "tests/unittest_builder.py::BuilderTest::test_yield_parent", "tests/unittest_builder.py::FileBuildTest::test_class_base_props", "tests/unittest_builder.py::FileBuildTest::test_class_basenames", "tests/unittest_builder.py::FileBuildTest::test_class_instance_attrs", "tests/unittest_builder.py::FileBuildTest::test_class_locals", "tests/unittest_builder.py::FileBuildTest::test_function_base_props", "tests/unittest_builder.py::FileBuildTest::test_function_locals", "tests/unittest_builder.py::FileBuildTest::test_method_base_props", "tests/unittest_builder.py::FileBuildTest::test_method_locals", "tests/unittest_builder.py::FileBuildTest::test_module_base_props", "tests/unittest_builder.py::FileBuildTest::test_module_locals", "tests/unittest_builder.py::FileBuildTest::test_unknown_encoding", "tests/unittest_builder.py::test_module_build_dunder_file", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_container", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_name", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_attribute", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_call", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_assignment", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_stmts", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_mix_nodes", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_ops", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_if", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_for", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_const", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_function", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_dict", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_subscript", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_import", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_with", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_while", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_string", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_comprehension", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_class", "tests/unittest_nodes_lineno.py::TestLinenoColOffset::test_end_lineno_module", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_in_memory", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_file_stream_physical", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_1", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_import_2", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_module_getattr", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_public_names", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_relative_to_absolute_name_beyond_top_level", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_stream_api", "tests/unittest_scoped_nodes.py::ModuleNodeTest::test_wildcard_import_names", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_abstract_methods_are_not_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_argnames", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_decorator_builtin_descriptors", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_default_value", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_classmethod", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_function", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_dunder_class_local_to_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_format_args_keyword_only_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_four_args", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_func_instance_attr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_igetattr", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_abstract_decorated", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_generator", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_is_method", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_pytype", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_lambda_qname", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_method_init_subclass", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_no_returns_is_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_only_raises_is_not_implicitly_none", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_positional_only_argnames", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_annotation_is_not_the_last", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_return_nothing", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_special_attributes", "tests/unittest_scoped_nodes.py::FunctionNodeTest::test_type_builtin_descriptor_subclasses", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__bases__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test__mro__attribute", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_add_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_all_ancestors_need_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_frame_is_not_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_assignment_names_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_callfunc_are_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_extra_decorators_only_same_name_considered", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_class_keywords", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_classmethod_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_cls_special_attributes_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_dict_interface", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_duplicate_bases_namedtuple", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_extra_decorators_only_class_level_assignments", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_generator_from_infer_call_result_parent", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_from_grandpa", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_getattr_method_transform", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_has_dynamic_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_implicit_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_inner_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_bound_method_lambdas_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_getattr_with_class_attr", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_instance_special_attributes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_kite_graph", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_ancestors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_invalid_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_local_attr_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_error", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_inference_errors", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_lookup_using_same_class", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_metaclass_yes_leak", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_methods", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_3", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_4", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_5", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_6", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_7", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_1", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_generic_error_2", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_typing_extensions", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_attribute_classes", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_mro_with_factories", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_navigation", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_no_infinite_metaclass_loop_with_redefine", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_nonregr_infer_callresult", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_added_dynamically_still_inferred", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_empty_list_of_slots", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_for_dict_keys", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_slots_taken_from_parents", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type", "tests/unittest_scoped_nodes.py::ClassNodeTest::test_type_three_arguments", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_subclass_property", "tests/unittest_scoped_nodes.py::test_issue940_property_grandchild", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_property", "tests/unittest_scoped_nodes.py::test_issue940_with_metaclass_class_context_property", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_values_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_derived_funcdef", "tests/unittest_scoped_nodes.py::test_issue940_metaclass_funcdef_is_not_datadescriptor", "tests/unittest_scoped_nodes.py::test_issue940_enums_as_a_real_world_usecase", "tests/unittest_scoped_nodes.py::test_metaclass_cannot_infer_call_yields_an_instance", "tests/unittest_scoped_nodes.py::test_posonlyargs_python_38[\\ndef", "tests/unittest_scoped_nodes.py::test_posonlyargs_default_value", "tests/unittest_scoped_nodes.py::test_ancestor_with_generic", "tests/unittest_scoped_nodes.py::test_slots_duplicate_bases_issue_1089", "tests/unittest_scoped_nodes.py::TestFrameNodes::test_frame_node", "tests/unittest_scoped_nodes.py::TestFrameNodes::test_non_frame_node"], "environment_setup_commit": "da745538c7236028a22cdf0405f6829fcf6886bc"}, {"repo": "pylint-dev/astroid", "instance_id": "pylint-dev__astroid-1959", "base_commit": "49691cc04f2d38b174787280f7ed38f818c828bd", "patch": "diff --git a/astroid/raw_building.py b/astroid/raw_building.py\n--- a/astroid/raw_building.py\n+++ b/astroid/raw_building.py\n@@ -324,6 +324,17 @@ def _build_from_function(\n object_build_function(node, member, name)\n \n \n+def _safe_has_attribute(obj, member: str) -> bool:\n+ \"\"\"Required because unexpected RunTimeError can be raised.\n+\n+ See https://github.com/PyCQA/astroid/issues/1958\n+ \"\"\"\n+ try:\n+ return hasattr(obj, member)\n+ except Exception: # pylint: disable=broad-except\n+ return False\n+\n+\n class InspectBuilder:\n \"\"\"class for building nodes from living object\n \n@@ -419,7 +430,7 @@ def object_build(\n # This should be called for Jython, where some builtin\n # methods aren't caught by isbuiltin branch.\n _build_from_function(node, name, member, self._module)\n- elif hasattr(member, \"__all__\"):\n+ elif _safe_has_attribute(member, \"__all__\"):\n module = build_module(name)\n _attach_local_node(node, module, name)\n # recursion\n", "test_patch": "diff --git a/tests/testdata/python3/data/fake_module_with_broken_getattr.py b/tests/testdata/python3/data/fake_module_with_broken_getattr.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/testdata/python3/data/fake_module_with_broken_getattr.py\n@@ -0,0 +1,7 @@\n+class Broken:\n+\n+ def __getattr__(self, name):\n+ raise Exception(\"boom\")\n+\n+\n+broken = Broken()\ndiff --git a/tests/unittest_raw_building.py b/tests/unittest_raw_building.py\n--- a/tests/unittest_raw_building.py\n+++ b/tests/unittest_raw_building.py\n@@ -1,3 +1,9 @@\n+\"\"\"\n+'tests.testdata.python3.data.fake_module_with_warnings' and\n+'tests.testdata.python3.data.fake_module_with_warnings' are fake modules\n+to simulate issues in unittest below\n+\"\"\"\n+\n # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html\n # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE\n # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt\n@@ -8,7 +14,7 @@\n import _io\n import pytest\n \n-# A fake module to simulate pandas in unittest below\n+import tests.testdata.python3.data.fake_module_with_broken_getattr as fm_getattr\n import tests.testdata.python3.data.fake_module_with_warnings as fm\n from astroid.builder import AstroidBuilder\n from astroid.const import IS_PYPY\n@@ -102,6 +108,14 @@ def test_build_function_deepinspect_deprecation(self) -> None:\n # This should not raise an exception\n AstroidBuilder().module_build(m, \"test\")\n \n+ def test_module_object_with_broken_getattr(self) -> None:\n+ # Tests https://github.com/PyCQA/astroid/issues/1958\n+ # When astroid deep inspection of modules raises\n+ # errors when using hasattr().\n+\n+ # This should not raise an exception\n+ AstroidBuilder().inspect_build(fm_getattr, \"test\")\n+\n \n if __name__ == \"__main__\":\n unittest.main()\n", "problem_statement": "v2.13.x regression: Crash when inspecting `PyQt5.QtWidgets` due to `RuntimeError` during `hasattr`\n### Steps to reproduce\r\n\r\nInstall PyQt5, run `pylint --extension-pkg-whitelist=PyQt5 x.py` over a file containing `from PyQt5 import QtWidgets`\r\n\r\n### Current behavior\r\n\r\nWith astroid 2.12.13 and pylint 2.15.10, this works fine. With astroid 2.13.2, this happens:\r\n\r\n```pytb\r\nException on node <ImportFrom l.1 at 0x7fc5a3c47d00> in file '/home/florian/tmp/pylintbug/x.py'\r\nTraceback (most recent call last):\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/utils/ast_walker.py\", line 90, in walk\r\n callback(astroid)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 1726, in visit_importfrom\r\n self._check_module_attrs(node, module, name.split(\".\"))\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 2701, in _check_module_attrs\r\n module = next(module.getattr(name)[0].infer())\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 412, in getattr\r\n result = [self.import_module(name, relative_only=True)]\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 527, in import_module\r\n return AstroidManager().ast_from_module_name(\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 205, in ast_from_module_name\r\n return self.ast_from_module(named_module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 312, in ast_from_module\r\n return AstroidBuilder(self).module_build(module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/builder.py\", line 101, in module_build\r\n node = self.inspect_build(module, modname=modname, path=path)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 366, in inspect_build\r\n self.object_build(node, module)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 422, in object_build\r\n elif hasattr(member, \"__all__\"):\r\nRuntimeError: wrapped C/C++ object of type QApplication has been deleted\r\nx.py:1:0: F0002: x.py: Fatal error while checking 'x.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/home/florian/.cache/pylint/pylint-crash-2023-01-10-11-06-17.txt'. (astroid-error)\r\n```\r\n\r\nIt looks like it happens when `member` is `QtWidgets.qApp`, which is a kind of \"magic\" object referring to the QApplication singleton. Since none exists, it looks like PyQt doesn't like trying to access an attribute on that.\r\n\r\nBisected to:\r\n\r\n- #1885 \r\n\r\nIt looks like 974f26f75eb3eccb4bcd8ea143901baf60a685ff is the exact culprit.\r\n\r\ncc @nickdrozd \r\n\r\n(took the freedom to add appropriate labels already, hope that's fine)\r\n\n", "hints_text": "Thank you for the investigation @The-Compiler ! I'm going to revert the offending commit seeing it's only a cleanup. Let's do something more elegant later on if required.\nThe commit you linked is from a fork, so I tried to reproduce locally to bisect on pylint main repo but I cannot\r\n```\r\npip3 install PyQt5\r\nCollecting PyQt5\r\n Collecting PyQt5-sip<13,>=12.11\r\nCollecting PyQt5-Qt5>=5.15.0\r\nInstalling collected packages: PyQt5-Qt5, PyQt5-sip, PyQt5\r\nSuccessfully installed PyQt5-5.15.7 PyQt5-Qt5-5.15.2 PyQt5-sip-12.11.0\r\n(venv) fix-crash-regression-2.13.2: pylint --extension-pkg-whitelist=PyQt5 x.py \r\n************* Module x\r\nx.py:1:0: W0611: Unused QtWidgets imported from PyQt5 (unused-import)\r\n---------------------------------------------------------------------\r\n\r\nYour code has been rated at 0.00/10 (previous run: -50.00/10, +50.00)\r\n```\r\nCould you provide your other dependencies maybe ?\r\n\n> The commit you linked is from a fork, so I tried to reproduce locally to bisect on pylint main repo but I cannot\r\n\r\nThe main astroid repo bisects to the merge of #1885 (f26dbe419ac15a87ed65e9b55ed15d3d8100b608) - that was a squash merge, 974f26f75eb3eccb4bcd8ea143901baf60a685ff is my guess at what in the PR is the problem.\r\n\r\n> Could you provide your other dependencies maybe ?\r\n\r\nNothing else really:\r\n\r\n```\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ python3 --version\r\nPython 3.10.8\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ python3 -m venv .venv\r\npython3 -m venv .venv 2.87s user 0.26s system 98% cpu 3.170 total\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ .venv/bin/pip install pylint PyQt5\r\nCollecting pylint\r\n Using cached pylint-2.15.10-py3-none-any.whl (509 kB)\r\nCollecting PyQt5\r\n Using cached PyQt5-5.15.7-cp37-abi3-manylinux1_x86_64.whl (8.4 MB)\r\nCollecting tomli>=1.1.0\r\n Using cached tomli-2.0.1-py3-none-any.whl (12 kB)\r\nCollecting tomlkit>=0.10.1\r\n Using cached tomlkit-0.11.6-py3-none-any.whl (35 kB)\r\nCollecting platformdirs>=2.2.0\r\n Using cached platformdirs-2.6.2-py3-none-any.whl (14 kB)\r\nCollecting mccabe<0.8,>=0.6\r\n Using cached mccabe-0.7.0-py2.py3-none-any.whl (7.3 kB)\r\nCollecting dill>=0.2\r\n Using cached dill-0.3.6-py3-none-any.whl (110 kB)\r\nCollecting astroid<=2.14.0-dev0,>=2.12.13\r\n Using cached astroid-2.13.2-py3-none-any.whl (272 kB)\r\nCollecting isort<6,>=4.2.5\r\n Using cached isort-5.11.4-py3-none-any.whl (104 kB)\r\nCollecting PyQt5-Qt5>=5.15.0\r\n Using cached PyQt5_Qt5-5.15.2-py3-none-manylinux2014_x86_64.whl (59.9 MB)\r\nCollecting PyQt5-sip<13,>=12.11\r\n Using cached PyQt5_sip-12.11.0-cp310-cp310-manylinux1_x86_64.whl (359 kB)\r\nCollecting lazy-object-proxy>=1.4.0\r\n Using cached lazy_object_proxy-1.9.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (63 kB)\r\nCollecting wrapt<2,>=1.11\r\n Using cached wrapt-1.14.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (77 kB)\r\nCollecting typing-extensions>=4.0.0\r\n Using cached typing_extensions-4.4.0-py3-none-any.whl (26 kB)\r\nInstalling collected packages: PyQt5-Qt5, wrapt, typing-extensions, tomlkit, tomli, PyQt5-sip, platformdirs, mccabe, lazy-object-proxy, isort, dill, PyQt5, astroid, pylint\r\nSuccessfully installed PyQt5-5.15.7 PyQt5-Qt5-5.15.2 PyQt5-sip-12.11.0 astroid-2.13.2 dill-0.3.6 isort-5.11.4 lazy-object-proxy-1.9.0 mccabe-0.7.0 platformdirs-2.6.2 pylint-2.15.10 tomli-2.0.1 tomlkit-0.11.6 typing-extensions-4.4.0 wrapt-1.14.1\r\n\r\n[notice] A new release of pip available: 22.2.2 -> 22.3.1\r\n[notice] To update, run: python3 -m pip install --upgrade pip\r\n.venv/bin/pip install pylint PyQt5 3.18s user 0.57s system 74% cpu 5.004 total\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ cat x.py\r\nfrom PyQt5 import QtWidgets\r\n\r\n\u2500[florian@aragog]\u2500\u2500[~/tmp/pylintbug]\u2500\u2500[23-01-10]\u2500\u2500[12:35]\u2500\u2500\u2500\u2500\u2504\r\n$ .venv/bin/pylint --extension-pkg-whitelist=PyQt5 x.py \r\n************* Module x\r\nx.py:1:0: C0114: Missing module docstring (missing-module-docstring)\r\nException on node <ImportFrom l.1 at 0x7fa1f6e37d90> in file '/home/florian/tmp/pylintbug/x.py'\r\nTraceback (most recent call last):\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/utils/ast_walker.py\", line 90, in walk\r\n callback(astroid)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 1726, in visit_importfrom\r\n self._check_module_attrs(node, module, name.split(\".\"))\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/pylint/checkers/variables.py\", line 2701, in _check_module_attrs\r\n module = next(module.getattr(name)[0].infer())\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 412, in getattr\r\n result = [self.import_module(name, relative_only=True)]\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/nodes/scoped_nodes/scoped_nodes.py\", line 527, in import_module\r\n return AstroidManager().ast_from_module_name(\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 205, in ast_from_module_name\r\n return self.ast_from_module(named_module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/manager.py\", line 312, in ast_from_module\r\n return AstroidBuilder(self).module_build(module, modname)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/builder.py\", line 101, in module_build\r\n node = self.inspect_build(module, modname=modname, path=path)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 366, in inspect_build\r\n self.object_build(node, module)\r\n File \"/home/florian/tmp/pylintbug/.venv/lib/python3.10/site-packages/astroid/raw_building.py\", line 422, in object_build\r\n elif hasattr(member, \"__all__\"):\r\nRuntimeError: wrapped C/C++ object of type QApplication has been deleted\r\nx.py:1:0: F0002: x.py: Fatal error while checking 'x.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/home/florian/.cache/pylint/pylint-crash-2023-01-10-12-36-04.txt'. (astroid-error)\r\n\r\n------------------------------------------------------------------\r\nYour code has been rated at 0.00/10 (previous run: 0.00/10, +0.00)\r\n```\r\n", "created_at": "2023-01-10T12:07:01Z", "version": "2.14", "FAIL_TO_PASS": ["tests/unittest_raw_building.py::RawBuildingTC::test_module_object_with_broken_getattr"], "PASS_TO_PASS": ["tests/unittest_raw_building.py::RawBuildingTC::test_attach_dummy_node", "tests/unittest_raw_building.py::RawBuildingTC::test_build_class", "tests/unittest_raw_building.py::RawBuildingTC::test_build_from_import", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_args", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_deepinspect_deprecation", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_defaults", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_kwonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_function_posonlyargs", "tests/unittest_raw_building.py::RawBuildingTC::test_build_module", "tests/unittest_raw_building.py::RawBuildingTC::test_io_is__io"], "environment_setup_commit": "0c9ab0fe56703fa83c73e514a1020d398d23fa7f"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4853", "base_commit": "4a44e4c63c6b8d6a3f1db0aa193f4ccb631ed698", "patch": "diff --git a/pyvista/core/utilities/geometric_objects.py b/pyvista/core/utilities/geometric_objects.py\n--- a/pyvista/core/utilities/geometric_objects.py\n+++ b/pyvista/core/utilities/geometric_objects.py\n@@ -62,7 +62,7 @@ def translate(surf, center=(0.0, 0.0, 0.0), direction=(1.0, 0.0, 0.0)):\n if np.array_equal(normz, (0.0, 0.0, 0.0)):\n # the assumed normy axis is parallel to normx, so shift its\n # axis and recalculate normz\n- norm_y_temp = np.roll(norm_y_temp, 1)\n+ norm_y_temp = [-1.0, 0.0, 0.0]\n normz = np.cross(normx, norm_y_temp)\n normz /= np.linalg.norm(normz)\n normy = np.cross(normz, normx)\n", "test_patch": "diff --git a/tests/core/test_parametric_geometry.py b/tests/core/test_parametric_geometry.py\n--- a/tests/core/test_parametric_geometry.py\n+++ b/tests/core/test_parametric_geometry.py\n@@ -148,3 +148,15 @@ def test_ParametricSuperToroid():\n def test_ParametricTorus():\n geom = pv.ParametricTorus()\n assert geom.n_points\n+\n+\n+def test_direction():\n+ geom1 = pv.ParametricEllipsoid(300, 100, 10, direction=[1, 0, 0])\n+ geom2 = pv.ParametricEllipsoid(300, 100, 10, direction=[0, 1, 0])\n+ assert geom1.n_points\n+ assert geom2.n_points\n+ points1 = geom1.points\n+ points2 = geom2.points\n+ assert np.allclose(points1[:, 0], points2[:, 1])\n+ assert np.allclose(points1[:, 1], -points2[:, 0])\n+ assert np.allclose(points1[:, 2], points2[:, 2])\n", "problem_statement": "Confusing behaviour of ParametricEllipsoid\n### Describe the bug, what's wrong, and what you expected.\r\n\r\nWhen creating a ParametricEllispoid using a direction of [0, 1, 0], the ellipsoid is rotated along the y axis. \r\nFor example if setting the direction to [1e-5, 1, 0], which corresponds to approximately similar direction, the ellipsoid displays then the correct behaviour.\r\n\r\n### Steps to reproduce the bug.\r\n\r\n```python\r\nimport pyvista as pv\r\n\r\nellipsoid = pv.ParametricEllipsoid(300, 100, 10, direction=[0, 1, 0])\r\n```\r\n\r\n### System Information\r\n\r\n```shell\r\nDate: Wed Sep 06 14:07:38 2023 CEST\r\n\r\n OS : Linux\r\n CPU(s) : 8\r\n Machine : x86_64\r\n Architecture : 64bit\r\n RAM : 31.2 GiB\r\n Environment : Jupyter\r\n File system : ext4\r\n GPU Vendor : Intel\r\n GPU Renderer : Mesa Intel(R) UHD Graphics (CML GT2)\r\n GPU Version : 4.6 (Core Profile) Mesa 22.0.1\r\n MathText Support : False\r\n\r\n Python 3.8.13 (default, Apr 19 2022, 02:32:06) [GCC 11.2.0]\r\n\r\n pyvista : 0.41.1\r\n vtk : 9.2.6\r\n numpy : 1.24.4\r\n matplotlib : 3.3.4\r\n scooby : 0.7.2\r\n pooch : v1.7.0\r\n imageio : 2.31.1\r\n IPython : 8.12.2\r\n ipywidgets : 8.0.7\r\n scipy : 1.10.1\r\n tqdm : 4.65.0\r\n jupyterlab : 3.6.5\r\n trame : 2.5.2\r\n trame_client : 2.10.0\r\n trame_server : 2.11.7\r\n trame_vtk : 2.5.8\r\n nest_asyncio : 1.5.6\r\n```\r\n\r\n\r\n### Screenshots\r\n\r\nHere is the given ellipsoid\r\n\r\nHere is what is expected\r\n\r\n\n", "hints_text": "", "created_at": "2023-09-06T17:37:24Z", "version": "0.43", "FAIL_TO_PASS": ["tests/core/test_parametric_geometry.py::test_direction"], "PASS_TO_PASS": ["tests/core/test_parametric_geometry.py::test_spline", "tests/core/test_parametric_geometry.py::test_kochanek_spline", "tests/core/test_parametric_geometry.py::test_ParametricBohemianDome", "tests/core/test_parametric_geometry.py::test_ParametricBour", "tests/core/test_parametric_geometry.py::test_ParametricBoy", "tests/core/test_parametric_geometry.py::test_ParametricCatalanMinimal", "tests/core/test_parametric_geometry.py::test_ParametricConicSpiral", "tests/core/test_parametric_geometry.py::test_ParametricCrossCap", "tests/core/test_parametric_geometry.py::test_ParametricDini", "tests/core/test_parametric_geometry.py::test_ParametricEllipsoid", "tests/core/test_parametric_geometry.py::test_ParametricEnneper", "tests/core/test_parametric_geometry.py::test_ParametricFigure8Klein", "tests/core/test_parametric_geometry.py::test_ParametricHenneberg", "tests/core/test_parametric_geometry.py::test_ParametricKlein", "tests/core/test_parametric_geometry.py::test_ParametricKuen", "tests/core/test_parametric_geometry.py::test_ParametricMobius", "tests/core/test_parametric_geometry.py::test_ParametricPluckerConoid", "tests/core/test_parametric_geometry.py::test_ParametricPseudosphere", "tests/core/test_parametric_geometry.py::test_ParametricRandomHills", "tests/core/test_parametric_geometry.py::test_ParametricRoman", "tests/core/test_parametric_geometry.py::test_ParametricSuperEllipsoid", "tests/core/test_parametric_geometry.py::test_ParametricSuperToroid", "tests/core/test_parametric_geometry.py::test_ParametricTorus"], "environment_setup_commit": "17ed0eb49a942b297e61a83a1c8ba828c5922b99"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4648", "base_commit": "d804a93a3bcae250c74a9f0f7c37fbc8bf002011", "patch": "diff --git a/examples/01-filter/interpolate.py b/examples/01-filter/interpolate.py\n--- a/examples/01-filter/interpolate.py\n+++ b/examples/01-filter/interpolate.py\n@@ -4,6 +4,22 @@\n Interpolating\n ~~~~~~~~~~~~~\n \n+There are two main methods of interpolating or sampling data from a target mesh\n+in PyVista. :func:`pyvista.DataSetFilters.interpolate` uses a distance weighting\n+kernel to interpolate point data from nearby points of the target mesh onto\n+the desired points.\n+:func:`pyvista.DataSetFilters.sample` interpolates data using the\n+interpolation scheme of the enclosing cell from the target mesh.\n+\n+If the target mesh is a point cloud, i.e. there is no connectivity in the cell\n+structure, then :func:`pyvista.DataSetFilters.interpolate` is typically\n+preferred. If interpolation is desired within the cells of the target mesh, then\n+:func:`pyvista.DataSetFilters.sample` is typically desired.\n+\n+\n+This example uses :func:`pyvista.DataSetFilters.interpolate`.\n+For :func:`pyvista.DataSetFilters.sample`, see :ref:`resampling_example`.\n+\n Interpolate one mesh's point/cell arrays onto another mesh's nodes using a\n Gaussian Kernel.\n \"\"\"\ndiff --git a/examples/01-filter/resample.py b/examples/01-filter/resample.py\n--- a/examples/01-filter/resample.py\n+++ b/examples/01-filter/resample.py\n@@ -4,10 +4,27 @@\n Resampling\n ~~~~~~~~~~\n \n+There are two main methods of interpolating or sampling data from a target mesh\n+in PyVista. :func:`pyvista.DataSetFilters.interpolate` uses a distance weighting\n+kernel to interpolate point data from nearby points of the target mesh onto\n+the desired points.\n+:func:`pyvista.DataSetFilters.sample` interpolates data using the\n+interpolation scheme of the enclosing cell from the target mesh.\n+\n+If the target mesh is a point cloud, i.e. there is no connectivity in the cell\n+structure, then :func:`pyvista.DataSetFilters.interpolate` is typically\n+preferred. If interpolation is desired within the cells of the target mesh, then\n+:func:`pyvista.DataSetFilters.sample` is typically desired.\n+\n+\n+This example uses :func:`pyvista.DataSetFilters.sample`.\n+For :func:`pyvista.DataSetFilters.interpolate`, see :ref:`interpolate_example`.\n+\n+\n Resample one mesh's point/cell arrays onto another mesh's nodes.\n \"\"\"\n ###############################################################################\n-# This example will resample a volumetric mesh's scalar data onto the surface\n+# This example will resample a volumetric mesh's scalar data onto the surface\n # of a sphere contained in that volume.\n \n # sphinx_gallery_thumbnail_number = 3\n@@ -17,7 +34,7 @@\n ###############################################################################\n # Simple Resample\n # +++++++++++++++\n-# Query a grids points onto a sphere\n+# Query a grid's points onto a sphere\n mesh = pv.Sphere(center=(4.5, 4.5, 4.5), radius=4.5)\n data_to_probe = examples.load_uniform()\n \ndiff --git a/pyvista/core/filters/data_set.py b/pyvista/core/filters/data_set.py\n--- a/pyvista/core/filters/data_set.py\n+++ b/pyvista/core/filters/data_set.py\n@@ -8,7 +8,12 @@\n \n import pyvista\n import pyvista.core._vtk_core as _vtk\n-from pyvista.core.errors import AmbiguousDataError, MissingDataError, VTKVersionError\n+from pyvista.core.errors import (\n+ AmbiguousDataError,\n+ MissingDataError,\n+ PyVistaDeprecationWarning,\n+ VTKVersionError,\n+)\n from pyvista.core.filters import _get_output, _update_alg\n from pyvista.core.utilities import transformations\n from pyvista.core.utilities.arrays import (\n@@ -3024,7 +3029,12 @@ def probe(\n ):\n \"\"\"Sample data values at specified point locations.\n \n- This uses :class:`vtk.vtkProbeFilter`.\n+ .. deprecated:: 0.41.0\n+ `probe` will be removed in a future version. Use\n+ :func:`pyvista.DataSetFilters.sample` instead.\n+ If using `mesh1.probe(mesh2)`, use `mesh2.sample(mesh1)`.\n+\n+ This uses :class:`vtkProbeFilter`.\n \n Parameters\n ----------\n@@ -3068,11 +3078,21 @@ def probe(\n >>> from pyvista import examples\n >>> mesh = pv.Sphere(center=(4.5, 4.5, 4.5), radius=4.5)\n >>> grid = examples.load_uniform()\n- >>> result = grid.probe(mesh)\n- >>> 'Spatial Point Data' in result.point_data\n+ >>> result = grid.probe(mesh) # doctest:+SKIP\n+ >>> 'Spatial Point Data' in result.point_data # doctest:+SKIP\n True\n \n \"\"\"\n+ # deprecated in v0.41.0\n+ # remove in v0.44.0\n+ warnings.warn(\n+ \"\"\"probe filter is deprecated and will be removed in a future version.\n+ Use sample filter instead.\n+ If using `mesh1.probe(mesh2)`, use `mesh2.sample(mesh1)`.\n+ \"\"\",\n+ PyVistaDeprecationWarning,\n+ )\n+\n if not pyvista.is_pyvista_dataset(points):\n points = wrap(points)\n alg = _vtk.vtkProbeFilter()\n@@ -3100,9 +3120,17 @@ def sample(\n pass_point_data=True,\n categorical=False,\n progress_bar=False,\n+ locator=None,\n ):\n \"\"\"Resample array data from a passed mesh onto this mesh.\n \n+ For `mesh1.sample(mesh2)`, the arrays from `mesh2` are sampled onto\n+ the points of `mesh1`. This function interpolates within an\n+ enclosing cell. This contrasts with\n+ :function`pyvista.DataSetFilters.interpolate` that uses a distance\n+ weighting for nearby points. If there is cell topology, `sample` is\n+ usually preferred.\n+\n This uses :class:`vtk.vtkResampleWithDataSet`.\n \n Parameters\n@@ -3130,22 +3158,41 @@ def sample(\n progress_bar : bool, default: False\n Display a progress bar to indicate progress.\n \n+ locator : vtkAbstractCellLocator, optional\n+ Prototype cell locator to perform the ``FindCell()``\n+ operation. Default uses the DataSet ``FindCell`` method.\n+\n Returns\n -------\n pyvista.DataSet\n Dataset containing resampled data.\n \n+ See Also\n+ --------\n+ pyvista.DataSetFilters.interpolate\n+\n Examples\n --------\n Resample data from another dataset onto a sphere.\n \n- >>> import pyvista\n+ >>> import pyvista as pv\n >>> from pyvista import examples\n- >>> mesh = pyvista.Sphere(center=(4.5, 4.5, 4.5), radius=4.5)\n+ >>> mesh = pv.Sphere(center=(4.5, 4.5, 4.5), radius=4.5)\n >>> data_to_probe = examples.load_uniform()\n >>> result = mesh.sample(data_to_probe)\n >>> result.plot(scalars=\"Spatial Point Data\")\n \n+ If sampling from a set of points represented by a ``(n, 3)``\n+ shaped ``numpy.ndarray``, they need to be converted to a\n+ PyVista DataSet, e.g. :class:`pyvista.PolyData`, first.\n+\n+ >>> import numpy as np\n+ >>> points = np.array([[1.5, 5.0, 6.2], [6.7, 4.2, 8.0]])\n+ >>> mesh = pv.PolyData(points)\n+ >>> result = mesh.sample(data_to_probe)\n+ >>> result[\"Spatial Point Data\"]\n+ pyvista_ndarray([ 46.5 , 225.12])\n+\n See :ref:`resampling_example` for more examples using this filter.\n \n \"\"\"\n@@ -3161,6 +3208,9 @@ def sample(\n if tolerance is not None:\n alg.SetComputeTolerance(False)\n alg.SetTolerance(tolerance)\n+ if locator:\n+ alg.SetCellLocatorPrototype(locator)\n+\n _update_alg(alg, progress_bar, 'Resampling array Data from a Passed Mesh onto Mesh')\n return _get_output(alg)\n \n@@ -3178,8 +3228,8 @@ def interpolate(\n ):\n \"\"\"Interpolate values onto this mesh from a given dataset.\n \n- The input dataset is typically a point cloud. Only point data from\n- the source mesh will be interpolated onto points of this mesh. Whether\n+ The ``target`` dataset is typically a point cloud. Only point data from\n+ the ``target`` mesh will be interpolated onto points of this mesh. Whether\n preexisting point and cell data of this mesh are preserved in the\n output can be customized with the ``pass_point_data`` and\n ``pass_cell_data`` parameters.\n@@ -3188,6 +3238,10 @@ def interpolate(\n ``radius`` parameters to adjust this kernel. You can also switch this\n kernel to use an N closest points approach.\n \n+ If the cell topology is more useful for interpolating, e.g. from a\n+ discretized FEM or CFD simulation, use\n+ :func:`pyvista.DataSetFilters.sample` instead.\n+\n Parameters\n ----------\n target : pyvista.DataSet\n@@ -3237,6 +3291,10 @@ def interpolate(\n pyvista.DataSet\n Interpolated dataset. Return type matches input.\n \n+ See Also\n+ --------\n+ pyvista.DataSetFilters.sample\n+\n Examples\n --------\n Interpolate the values of 5 points onto a sample plane.\n", "test_patch": "diff --git a/tests/filters/test_dataset_filters.py b/tests/filters/test_dataset_filters.py\n--- a/tests/filters/test_dataset_filters.py\n+++ b/tests/filters/test_dataset_filters.py\n@@ -11,7 +11,7 @@\n from pyvista.core import _vtk_core\n from pyvista.core.celltype import CellType\n from pyvista.core.errors import NotAllTrianglesError, VTKVersionError\n-from pyvista.errors import MissingDataError\n+from pyvista.errors import MissingDataError, PyVistaDeprecationWarning\n \n normals = ['x', 'y', '-z', (1, 1, 1), (3.3, 5.4, 0.8)]\n \n@@ -1145,17 +1145,24 @@ def test_smooth_taubin(uniform):\n assert np.allclose(smooth_inplace.points, smoothed.points)\n \n \n-def test_resample():\n+def test_sample():\n mesh = pyvista.Sphere(center=(4.5, 4.5, 4.5), radius=4.5)\n data_to_probe = examples.load_uniform()\n- result = mesh.sample(data_to_probe, progress_bar=True)\n- name = 'Spatial Point Data'\n- assert name in result.array_names\n- assert isinstance(result, type(mesh))\n- result = mesh.sample(data_to_probe, tolerance=1.0, progress_bar=True)\n- name = 'Spatial Point Data'\n- assert name in result.array_names\n- assert isinstance(result, type(mesh))\n+\n+ def sample_test(**kwargs):\n+ \"\"\"Test `sample` with kwargs.\"\"\"\n+ result = mesh.sample(data_to_probe, **kwargs)\n+ name = 'Spatial Point Data'\n+ assert name in result.array_names\n+ assert isinstance(result, type(mesh))\n+\n+ sample_test()\n+ sample_test(tolerance=1.0)\n+ sample_test(progress_bar=True)\n+ sample_test(categorical=True)\n+ sample_test(locator=_vtk_core.vtkStaticCellLocator())\n+ sample_test(pass_cell_data=False)\n+ sample_test(pass_point_data=False)\n \n \n @pytest.mark.parametrize('use_points', [True, False])\n@@ -1168,9 +1175,10 @@ def test_probe(categorical, use_points, locator):\n dataset = np.array(mesh.points)\n else:\n dataset = mesh\n- result = data_to_probe.probe(\n- dataset, tolerance=1e-5, categorical=categorical, progress_bar=True, locator=locator\n- )\n+ with pytest.warns(PyVistaDeprecationWarning):\n+ result = data_to_probe.probe(\n+ dataset, tolerance=1e-5, categorical=categorical, progress_bar=True, locator=locator\n+ )\n name = 'Spatial Point Data'\n assert name in result.array_names\n assert isinstance(result, type(mesh))\n", "problem_statement": "Clean up and clarify sampling-like filters\n### Describe what maintenance you would like added.\n\nThere was a discussion on slack on the use of sampling-like filters, i.e. `sample`, `probe`, and `interpolate`. One issue is that it is hard to figure out when to use which filter. The other issue is that `probe` has the opposite behavior of `sample` and `interpolate` in regards to order of operation (see below).\n\n### Links to source code.\n\n_No response_\n\n### Pseudocode or Screenshots\n\n```python\r\nimport pyvista as pv\r\n\r\nsmall = pv.ImageData(dimensions=(5, 5, 5))\r\nlarge = pv.ImageData(dimensions=(10, 10, 10))\r\nprint(small.n_points)\r\nprint(large.n_points)\r\nprint(small.probe(large).n_points) # gives different result\r\nprint(small.sample(large).n_points)\r\nprint(small.interpolate(large).n_points)\r\n```\r\n\r\n\r\nThis gives\r\n\r\n```txt\r\n125\r\n1000\r\n1000\r\n125\r\n125\r\n```\n", "hints_text": "`probe` uses [vtkProbeFilter](https://vtk.org/doc/nightly/html/classvtkProbeFilter.html). Note that `vtkCompositeDataProbeFilter` is a subclass, and adds the ability to use Composite Data as in input (only one of the two slots in the algorithm).\r\n\r\n`sample` uses [vtkResampleWithDataSet](https://vtk.org/doc/nightly/html/classvtkResampleWithDataSet.html#details). This uses `vtkCompositeDataProbeFilter` under the hood, but also allows composite data to be used in both the source and the input.\r\n\r\nSo I propose that we deprecate `probe` and only keep `sample` and `interpolate`.\r\n\r\n`imterpolate` is separate from the other two since it uses a different sampling/interpolation method. \nThe pyvista standard, at least in my experience, is that we should generally expect the shape of the mesh to be equal to the mesh on which the filter attribute is called. That is, `mesh1.filter(mesh2)` should return a mesh closer to `mesh1`. This also enables `inplace=True` usage when possible.\r\n\r\nSo, if we were to keep `probe` we should switch the order of operation, and the deprecation/breaking change would have to be done carefully. I still think it should be removed entirely instead as above, but wanted to lay out other options.\n> So, if we were to keep `probe` we should switch the order of operation, and the deprecation/breaking change would have to be done carefully. I still think it should be removed entirely instead as above, but wanted to lay out other options.\r\n\r\nFrom a design standpoint, we'd probably have to do the deprecation the same way: deprecating the old method and introducing a new one that has the right semantics. Switching the input and output is not the kind of change we should subject downstream to.\n+1 to this, I've definitely been confused by it before. \r\n\r\n> The pyvista standard, at least in my experience, is that we should generally expect the shape of the mesh to be equal to the mesh on which the filter attribute is called. \r\n\r\n+1 again\r\n\r\n> From a design standpoint, we'd probably have to do the deprecation the same way: deprecating the old method and introducing a new one that has the right semantics. Switching the input and output is not the kind of change we should subject downstream to.\r\n\r\ndeprecate `probe` and introduce `eborp` \ud83d\ude09 \r\n\n+1 for `eborp`", "created_at": "2023-07-11T11:49:13Z", "version": "0.41", "FAIL_TO_PASS": ["tests/filters/test_dataset_filters.py::test_sample", "tests/filters/test_dataset_filters.py::test_probe[None-True-True]", "tests/filters/test_dataset_filters.py::test_probe[None-True-False]", "tests/filters/test_dataset_filters.py::test_probe[None-False-True]", "tests/filters/test_dataset_filters.py::test_probe[None-False-False]", "tests/filters/test_dataset_filters.py::test_probe[locator1-True-True]", "tests/filters/test_dataset_filters.py::test_probe[locator1-True-False]", "tests/filters/test_dataset_filters.py::test_probe[locator1-False-True]", "tests/filters/test_dataset_filters.py::test_probe[locator1-False-False]"], "PASS_TO_PASS": ["tests/filters/test_dataset_filters.py::test_datasetfilters_init", "tests/filters/test_dataset_filters.py::test_clip_filter", "tests/filters/test_dataset_filters.py::test_clip_by_scalars_filter[False-False]", "tests/filters/test_dataset_filters.py::test_clip_by_scalars_filter[False-True]", "tests/filters/test_dataset_filters.py::test_clip_by_scalars_filter[True-False]", "tests/filters/test_dataset_filters.py::test_clip_by_scalars_filter[True-True]", "tests/filters/test_dataset_filters.py::test_clip_filter_no_active", "tests/filters/test_dataset_filters.py::test_clip_filter_scalar_multiple", "tests/filters/test_dataset_filters.py::test_clip_filter_composite", "tests/filters/test_dataset_filters.py::test_clip_box", "tests/filters/test_dataset_filters.py::test_clip_box_composite", "tests/filters/test_dataset_filters.py::test_clip_surface", "tests/filters/test_dataset_filters.py::test_clip_closed_surface", "tests/filters/test_dataset_filters.py::test_implicit_distance", "tests/filters/test_dataset_filters.py::test_slice_filter", "tests/filters/test_dataset_filters.py::test_slice_filter_composite", "tests/filters/test_dataset_filters.py::test_slice_orthogonal_filter", "tests/filters/test_dataset_filters.py::test_slice_orthogonal_filter_composite", "tests/filters/test_dataset_filters.py::test_slice_along_axis", "tests/filters/test_dataset_filters.py::test_slice_along_axis_composite", "tests/filters/test_dataset_filters.py::test_threshold", "tests/filters/test_dataset_filters.py::test_threshold_all_scalars", "tests/filters/test_dataset_filters.py::test_threshold_multicomponent", "tests/filters/test_dataset_filters.py::test_threshold_percent", "tests/filters/test_dataset_filters.py::test_threshold_paraview_consistency", "tests/filters/test_dataset_filters.py::test_outline", "tests/filters/test_dataset_filters.py::test_outline_composite", "tests/filters/test_dataset_filters.py::test_outline_corners", "tests/filters/test_dataset_filters.py::test_outline_corners_composite", "tests/filters/test_dataset_filters.py::test_extract_geometry", "tests/filters/test_dataset_filters.py::test_extract_geometry_extent", "tests/filters/test_dataset_filters.py::test_extract_all_edges", "tests/filters/test_dataset_filters.py::test_extract_all_edges_no_data", "tests/filters/test_dataset_filters.py::test_wireframe_composite", "tests/filters/test_dataset_filters.py::test_delaunay_2d_unstructured", "tests/filters/test_dataset_filters.py::test_contour[contour]", "tests/filters/test_dataset_filters.py::test_contour[marching_cubes]", "tests/filters/test_dataset_filters.py::test_contour[flying_edges]", "tests/filters/test_dataset_filters.py::test_contour_errors", "tests/filters/test_dataset_filters.py::test_elevation", "tests/filters/test_dataset_filters.py::test_elevation_composite", "tests/filters/test_dataset_filters.py::test_texture_map_to_plane", "tests/filters/test_dataset_filters.py::test_texture_map_to_sphere", "tests/filters/test_dataset_filters.py::test_compute_cell_sizes", "tests/filters/test_dataset_filters.py::test_compute_cell_sizes_composite", "tests/filters/test_dataset_filters.py::test_cell_centers", "tests/filters/test_dataset_filters.py::test_cell_centers_composite", "tests/filters/test_dataset_filters.py::test_glyph", "tests/filters/test_dataset_filters.py::test_glyph_cell_point_data", "tests/filters/test_dataset_filters.py::test_glyph_settings", "tests/filters/test_dataset_filters.py::test_glyph_orient_and_scale", "tests/filters/test_dataset_filters.py::test_split_and_connectivity", "tests/filters/test_dataset_filters.py::test_warp_by_scalar", "tests/filters/test_dataset_filters.py::test_warp_by_vector", "tests/filters/test_dataset_filters.py::test_invalid_warp_scalar", "tests/filters/test_dataset_filters.py::test_invalid_warp_scalar_inplace", "tests/filters/test_dataset_filters.py::test_invalid_warp_vector", "tests/filters/test_dataset_filters.py::test_cell_data_to_point_data", "tests/filters/test_dataset_filters.py::test_cell_data_to_point_data_composite", "tests/filters/test_dataset_filters.py::test_point_data_to_cell_data", "tests/filters/test_dataset_filters.py::test_point_data_to_cell_data_composite", "tests/filters/test_dataset_filters.py::test_triangulate", "tests/filters/test_dataset_filters.py::test_triangulate_composite", "tests/filters/test_dataset_filters.py::test_delaunay_3d", "tests/filters/test_dataset_filters.py::test_smooth", "tests/filters/test_dataset_filters.py::test_smooth_taubin", "tests/filters/test_dataset_filters.py::test_streamlines_dir[forward]", "tests/filters/test_dataset_filters.py::test_streamlines_dir[backward]", "tests/filters/test_dataset_filters.py::test_streamlines_dir[both]", "tests/filters/test_dataset_filters.py::test_streamlines_type[2]", "tests/filters/test_dataset_filters.py::test_streamlines_type[4]", "tests/filters/test_dataset_filters.py::test_streamlines_type[45]", "tests/filters/test_dataset_filters.py::test_streamlines_cell_point[point]", "tests/filters/test_dataset_filters.py::test_streamlines_cell_point[cell]", "tests/filters/test_dataset_filters.py::test_streamlines_return_source", "tests/filters/test_dataset_filters.py::test_streamlines_start_position", "tests/filters/test_dataset_filters.py::test_streamlines_errors", "tests/filters/test_dataset_filters.py::test_streamlines_from_source", "tests/filters/test_dataset_filters.py::test_streamlines_from_source_structured_grids", "tests/filters/test_dataset_filters.py::test_streamlines_evenly_spaced_2D", "tests/filters/test_dataset_filters.py::test_streamlines_evenly_spaced_2D_sep_dist_ratio", "tests/filters/test_dataset_filters.py::test_streamlines_evenly_spaced_2D_start_position", "tests/filters/test_dataset_filters.py::test_streamlines_evenly_spaced_2D_vectors", "tests/filters/test_dataset_filters.py::test_streamlines_evenly_spaced_2D_integrator_type", "tests/filters/test_dataset_filters.py::test_streamlines_evenly_spaced_2D_interpolator_type", "tests/filters/test_dataset_filters.py::test_streamlines_evenly_spaced_2D_errors", "tests/filters/test_dataset_filters.py::test_sample_over_line", "tests/filters/test_dataset_filters.py::test_plot_over_line", "tests/filters/test_dataset_filters.py::test_sample_over_multiple_lines", "tests/filters/test_dataset_filters.py::test_sample_over_circular_arc", "tests/filters/test_dataset_filters.py::test_sample_over_circular_arc_normal", "tests/filters/test_dataset_filters.py::test_plot_over_circular_arc", "tests/filters/test_dataset_filters.py::test_plot_over_circular_arc_normal", "tests/filters/test_dataset_filters.py::test_slice_along_line", "tests/filters/test_dataset_filters.py::test_extract_points", "tests/filters/test_dataset_filters.py::test_slice_along_line_composite", "tests/filters/test_dataset_filters.py::test_interpolate", "tests/filters/test_dataset_filters.py::test_select_enclosed_points", "tests/filters/test_dataset_filters.py::test_decimate_boundary", "tests/filters/test_dataset_filters.py::test_extract_surface", "tests/filters/test_dataset_filters.py::test_merge_general", "tests/filters/test_dataset_filters.py::test_iadd_general", "tests/filters/test_dataset_filters.py::test_compute_cell_quality", "tests/filters/test_dataset_filters.py::test_compute_derivatives", "tests/filters/test_dataset_filters.py::test_extract_subset", "tests/filters/test_dataset_filters.py::test_gaussian_smooth_output_type", "tests/filters/test_dataset_filters.py::test_gaussian_smooth_constant_data", "tests/filters/test_dataset_filters.py::test_gaussian_smooth_outlier", "tests/filters/test_dataset_filters.py::test_gaussian_smooth_cell_data_specified", "tests/filters/test_dataset_filters.py::test_gaussian_smooth_cell_data_active", "tests/filters/test_dataset_filters.py::test_median_smooth_output_type", "tests/filters/test_dataset_filters.py::test_median_smooth_constant_data", "tests/filters/test_dataset_filters.py::test_median_smooth_outlier", "tests/filters/test_dataset_filters.py::test_image_dilate_erode_output_type", "tests/filters/test_dataset_filters.py::test_image_dilate_erode_dilation", "tests/filters/test_dataset_filters.py::test_image_dilate_erode_erosion", "tests/filters/test_dataset_filters.py::test_image_dilate_erode_cell_data_specified", "tests/filters/test_dataset_filters.py::test_image_dilate_erode_cell_data_active", "tests/filters/test_dataset_filters.py::test_image_threshold_output_type", "tests/filters/test_dataset_filters.py::test_image_threshold_wrong_threshold_length", "tests/filters/test_dataset_filters.py::test_image_threshold_wrong_threshold_type", "tests/filters/test_dataset_filters.py::test_image_threshold_upper[0-1]", "tests/filters/test_dataset_filters.py::test_image_threshold_upper[0-None]", "tests/filters/test_dataset_filters.py::test_image_threshold_upper[None-1]", "tests/filters/test_dataset_filters.py::test_image_threshold_upper[None-None]", "tests/filters/test_dataset_filters.py::test_image_threshold_between[0-1]", "tests/filters/test_dataset_filters.py::test_image_threshold_between[0-None]", "tests/filters/test_dataset_filters.py::test_image_threshold_between[None-1]", "tests/filters/test_dataset_filters.py::test_image_threshold_between[None-None]", "tests/filters/test_dataset_filters.py::test_extract_subset_structured", "tests/filters/test_dataset_filters.py::test_concatenate_structured", "tests/filters/test_dataset_filters.py::test_concatenate_structured_bad_dimensions", "tests/filters/test_dataset_filters.py::test_concatenate_structured_bad_inputs", "tests/filters/test_dataset_filters.py::test_concatenate_structured_bad_point_data", "tests/filters/test_dataset_filters.py::test_concatenate_structured_disconnected", "tests/filters/test_dataset_filters.py::test_concatenate_structured_different_arrays", "tests/filters/test_dataset_filters.py::test_structured_add_non_grid", "tests/filters/test_dataset_filters.py::test_poly_data_strip", "tests/filters/test_dataset_filters.py::test_shrink", "tests/filters/test_dataset_filters.py::test_tessellate", "tests/filters/test_dataset_filters.py::test_transform_mesh[0-0]", "tests/filters/test_dataset_filters.py::test_transform_mesh[0-1]", "tests/filters/test_dataset_filters.py::test_transform_mesh[0-2]", "tests/filters/test_dataset_filters.py::test_transform_mesh[1-0]", "tests/filters/test_dataset_filters.py::test_transform_mesh[1-1]", "tests/filters/test_dataset_filters.py::test_transform_mesh[1-2]", "tests/filters/test_dataset_filters.py::test_transform_mesh[2-0]", "tests/filters/test_dataset_filters.py::test_transform_mesh[2-1]", "tests/filters/test_dataset_filters.py::test_transform_mesh[2-2]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[0-0]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[0-1]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[0-2]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[1-0]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[1-1]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[1-2]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[2-0]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[2-1]", "tests/filters/test_dataset_filters.py::test_transform_mesh_and_vectors[2-2]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[0-0]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[0-1]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[0-2]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[1-0]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[1-1]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[1-2]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[2-0]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[2-1]", "tests/filters/test_dataset_filters.py::test_transform_int_vectors_warning[2-2]", "tests/filters/test_dataset_filters.py::test_transform_inplace_bad_types[dataset0]", "tests/filters/test_dataset_filters.py::test_transform_inplace_bad_types[dataset1]", "tests/filters/test_dataset_filters.py::test_reflect_mesh_about_point", "tests/filters/test_dataset_filters.py::test_reflect_mesh_with_vectors", "tests/filters/test_dataset_filters.py::test_reflect_inplace[dataset0]", "tests/filters/test_dataset_filters.py::test_reflect_inplace[dataset1]", "tests/filters/test_dataset_filters.py::test_reflect_inplace[dataset2]", "tests/filters/test_dataset_filters.py::test_transform_inplace_bad_types_2[dataset0]", "tests/filters/test_dataset_filters.py::test_transform_inplace_bad_types_2[dataset1]", "tests/filters/test_dataset_filters.py::test_extrude_rotate", "tests/filters/test_dataset_filters.py::test_extrude_rotate_inplace", "tests/filters/test_dataset_filters.py::test_extrude_trim", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[intersection-boundary_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[intersection-all_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[minimum_distance-boundary_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[minimum_distance-all_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[maximum_distance-boundary_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[maximum_distance-all_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[average_distance-boundary_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_strategy[average_distance-all_edges]", "tests/filters/test_dataset_filters.py::test_extrude_trim_catch", "tests/filters/test_dataset_filters.py::test_extrude_trim_inplace", "tests/filters/test_dataset_filters.py::test_subdivide_adaptive[True]", "tests/filters/test_dataset_filters.py::test_subdivide_adaptive[False]", "tests/filters/test_dataset_filters.py::test_invalid_subdivide_adaptive", "tests/filters/test_dataset_filters.py::test_collision", "tests/filters/test_dataset_filters.py::test_collision_solid_non_triangle", "tests/filters/test_dataset_filters.py::test_reconstruct_surface_poly", "tests/filters/test_dataset_filters.py::test_is_manifold", "tests/filters/test_dataset_filters.py::test_reconstruct_surface_unstructured", "tests/filters/test_dataset_filters.py::test_integrate_data_datasets", "tests/filters/test_dataset_filters.py::test_integrate_data", "tests/filters/test_dataset_filters.py::test_align", "tests/filters/test_dataset_filters.py::test_subdivide_tetra", "tests/filters/test_dataset_filters.py::test_extract_cells_by_type", "tests/filters/test_dataset_filters.py::test_merge_points"], "environment_setup_commit": "d804a93a3bcae250c74a9f0f7c37fbc8bf002011"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4808", "base_commit": "d0c2e12cac39af1872b00907f9526dbfb59ec69e", "patch": "diff --git a/pyvista/core/filters/poly_data.py b/pyvista/core/filters/poly_data.py\n--- a/pyvista/core/filters/poly_data.py\n+++ b/pyvista/core/filters/poly_data.py\n@@ -81,6 +81,11 @@ def edge_mask(self, angle, progress_bar=False):\n \n def _boolean(self, btype, other_mesh, tolerance, progress_bar=False):\n \"\"\"Perform boolean operation.\"\"\"\n+ if self.n_points == other_mesh.n_points:\n+ if np.allclose(self.points, other_mesh.points):\n+ raise ValueError(\n+ \"The input mesh contains identical points to the surface being operated on. Unable to perform boolean operations on an identical surface.\"\n+ )\n if not isinstance(other_mesh, pyvista.PolyData):\n raise TypeError(\"Input mesh must be PolyData.\")\n if not self.is_all_triangles or not other_mesh.is_all_triangles:\n", "test_patch": "diff --git a/tests/core/test_polydata.py b/tests/core/test_polydata.py\n--- a/tests/core/test_polydata.py\n+++ b/tests/core/test_polydata.py\n@@ -280,9 +280,9 @@ def test_boolean_difference(sphere, sphere_shifted):\n assert np.isclose(difference.volume, expected_volume, atol=1e-3)\n \n \n-def test_boolean_difference_fail(plane):\n+def test_boolean_difference_fail(plane, sphere):\n with pytest.raises(NotAllTrianglesError):\n- plane - plane\n+ plane - sphere\n \n \n def test_subtract(sphere, sphere_shifted):\ndiff --git a/tests/core/test_polydata_filters.py b/tests/core/test_polydata_filters.py\n--- a/tests/core/test_polydata_filters.py\n+++ b/tests/core/test_polydata_filters.py\n@@ -45,3 +45,8 @@ def test_boolean_intersect_edge_case():\n \n with pytest.warns(UserWarning, match='contained within another'):\n a.boolean_intersection(b)\n+\n+\n+def test_identical_boolean(sphere):\n+ with pytest.raises(ValueError, match='identical points'):\n+ sphere.boolean_intersection(sphere.copy())\n", "problem_statement": "Boolean Operation freezes/crashes \n### Describe the bug, what's wrong, and what you expected.\n\nApparently, if two polyData have the exact same shape, their boolean operation freezes/crashes the application!\r\n\n\n### Steps to reproduce the bug.\n\n```python\r\np1 = pv.Sphere().triangulate()\r\np2 = pv.Sphere().triangulate()\r\n\r\np1.boolean_intersection(p2)\r\n``````\n\n### System Information\n\n```shell\n--------------------------------------------------------------------------------\r\n Date: Tue Aug 22 12:17:01 2023 EEST\r\n\r\n OS : Darwin\r\n CPU(s) : 12\r\n Machine : x86_64\r\n Architecture : 64bit\r\n RAM : 16.0 GiB\r\n Environment : Jupyter\r\n File system : apfs\r\n GPU Vendor : ATI Technologies Inc.\r\n GPU Renderer : AMD Radeon Pro 5300M OpenGL Engine\r\n GPU Version : 4.1 ATI-4.14.1\r\n MathText Support : False\r\n\r\n Python 3.10.11 (v3.10.11:7d4cc5aa85, Apr 4 2023, 19:05:19) [Clang 13.0.0\r\n (clang-1300.0.29.30)]\r\n\r\n pyvista : 0.41.1\r\n vtk : 9.2.6\r\n numpy : 1.24.2\r\n matplotlib : 3.7.1\r\n scooby : 0.7.2\r\n pooch : v1.7.0\r\n IPython : 8.14.0\r\n scipy : 1.10.1\r\n jupyterlab : 4.0.5\r\n nest_asyncio : 1.5.7\r\n--------------------------------------------------------------------------------\n```\n\n\n### Screenshots\n\n_No response_\n", "hints_text": "", "created_at": "2023-08-26T23:18:49Z", "version": "0.42", "FAIL_TO_PASS": ["tests/core/test_polydata_filters.py::test_identical_boolean"], "PASS_TO_PASS": ["tests/core/test_polydata.py::test_init", "tests/core/test_polydata.py::test_init_from_pdata", "tests/core/test_polydata.py::test_init_from_arrays", "tests/core/test_polydata.py::test_init_from_arrays_with_vert", "tests/core/test_polydata.py::test_init_from_arrays_triangular", "tests/core/test_polydata.py::test_init_as_points", "tests/core/test_polydata.py::test_init_as_points_from_list", "tests/core/test_polydata.py::test_invalid_init", "tests/core/test_polydata.py::test_invalid_file", "tests/core/test_polydata.py::test_lines_on_init", "tests/core/test_polydata.py::test_polydata_repr_str", "tests/core/test_polydata.py::test_geodesic", "tests/core/test_polydata.py::test_geodesic_fail", "tests/core/test_polydata.py::test_geodesic_distance", "tests/core/test_polydata.py::test_ray_trace", "tests/core/test_polydata.py::test_edge_mask", "tests/core/test_polydata.py::test_boolean_union_intersection", "tests/core/test_polydata.py::test_boolean_difference", "tests/core/test_polydata.py::test_boolean_difference_fail", "tests/core/test_polydata.py::test_subtract", "tests/core/test_polydata.py::test_append", "tests/core/test_polydata.py::test_append_raises", "tests/core/test_polydata.py::test_merge", "tests/core/test_polydata.py::test_merge_active_scalars[input0]", "tests/core/test_polydata.py::test_merge_active_scalars[input1]", "tests/core/test_polydata.py::test_merge_main_has_priority[input0]", "tests/core/test_polydata.py::test_merge_main_has_priority[input1]", "tests/core/test_polydata.py::test_add", "tests/core/test_polydata.py::test_intersection", "tests/core/test_polydata.py::test_curvature[mean]", "tests/core/test_polydata.py::test_curvature[gaussian]", "tests/core/test_polydata.py::test_curvature[maximum]", "tests/core/test_polydata.py::test_curvature[minimum]", "tests/core/test_polydata.py::test_invalid_curvature", "tests/core/test_polydata.py::test_save[.ply-True]", "tests/core/test_polydata.py::test_save[.ply-False]", "tests/core/test_polydata.py::test_save[.vtp-True]", "tests/core/test_polydata.py::test_save[.vtp-False]", "tests/core/test_polydata.py::test_save[.stl-True]", "tests/core/test_polydata.py::test_save[.stl-False]", "tests/core/test_polydata.py::test_save[.vtk-True]", "tests/core/test_polydata.py::test_save[.vtk-False]", "tests/core/test_polydata.py::test_pathlib_read_write", "tests/core/test_polydata.py::test_invalid_save", "tests/core/test_polydata.py::test_triangulate_filter", "tests/core/test_polydata.py::test_subdivision[butterfly]", "tests/core/test_polydata.py::test_subdivision[loop]", "tests/core/test_polydata.py::test_subdivision[linear]", "tests/core/test_polydata.py::test_invalid_subdivision", "tests/core/test_polydata.py::test_extract_feature_edges", "tests/core/test_polydata.py::test_extract_feature_edges_no_data", "tests/core/test_polydata.py::test_decimate", "tests/core/test_polydata.py::test_decimate_pro", "tests/core/test_polydata.py::test_compute_normals", "tests/core/test_polydata.py::test_compute_normals_inplace", "tests/core/test_polydata.py::test_compute_normals_split_vertices", "tests/core/test_polydata.py::test_point_normals", "tests/core/test_polydata.py::test_cell_normals", "tests/core/test_polydata.py::test_face_normals", "tests/core/test_polydata.py::test_clip_plane", "tests/core/test_polydata.py::test_extract_largest", "tests/core/test_polydata.py::test_clean", "tests/core/test_polydata.py::test_area", "tests/core/test_polydata.py::test_volume", "tests/core/test_polydata.py::test_remove_points_any", "tests/core/test_polydata.py::test_remove_points_all", "tests/core/test_polydata.py::test_remove_points_fail", "tests/core/test_polydata.py::test_vertice_cells_on_read", "tests/core/test_polydata.py::test_center_of_mass", "tests/core/test_polydata.py::test_project_points_to_plane", "tests/core/test_polydata.py::test_tube", "tests/core/test_polydata.py::test_smooth_inplace", "tests/core/test_polydata.py::test_delaunay_2d", "tests/core/test_polydata.py::test_lines", "tests/core/test_polydata.py::test_strips", "tests/core/test_polydata.py::test_ribbon_filter", "tests/core/test_polydata.py::test_is_all_triangles", "tests/core/test_polydata.py::test_extrude", "tests/core/test_polydata.py::test_extrude_capping_warnings", "tests/core/test_polydata.py::test_flip_normals", "tests/core/test_polydata.py::test_n_verts", "tests/core/test_polydata.py::test_n_lines", "tests/core/test_polydata.py::test_geodesic_disconnected", "tests/core/test_polydata.py::test_tetrahedron_regular_faces", "tests/core/test_polydata.py::test_regular_faces[False]", "tests/core/test_polydata.py::test_regular_faces[True]", "tests/core/test_polydata.py::test_set_regular_faces", "tests/core/test_polydata.py::test_empty_regular_faces", "tests/core/test_polydata.py::test_regular_faces_mutable", "tests/core/test_polydata_filters.py::test_contour_banded_raise", "tests/core/test_polydata_filters.py::test_contour_banded_points", "tests/core/test_polydata_filters.py::test_boolean_intersect_edge_case"], "environment_setup_commit": "e58d53d0ec16a16121c84912867dae6199b034a9"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4311", "base_commit": "db6ee8dd4a747b8864caae36c5d05883976a3ae5", "patch": "diff --git a/pyvista/core/datasetattributes.py b/pyvista/core/datasetattributes.py\n--- a/pyvista/core/datasetattributes.py\n+++ b/pyvista/core/datasetattributes.py\n@@ -1072,7 +1072,12 @@ def active_scalars_name(self) -> Optional[str]:\n \n \"\"\"\n if self.GetScalars() is not None:\n- return str(self.GetScalars().GetName())\n+ name = self.GetScalars().GetName()\n+ if name is None:\n+ # Getting the keys has the side effect of naming \"unnamed\" arrays\n+ self.keys()\n+ name = self.GetScalars().GetName()\n+ return str(name)\n return None\n \n @active_scalars_name.setter\ndiff --git a/pyvista/core/filters/rectilinear_grid.py b/pyvista/core/filters/rectilinear_grid.py\n--- a/pyvista/core/filters/rectilinear_grid.py\n+++ b/pyvista/core/filters/rectilinear_grid.py\n@@ -17,7 +17,8 @@ def to_tetrahedra(\n self,\n tetra_per_cell: int = 5,\n mixed: Union[Sequence[int], bool] = False,\n- pass_cell_ids: bool = False,\n+ pass_cell_ids: bool = True,\n+ pass_cell_data: bool = True,\n progress_bar: bool = False,\n ):\n \"\"\"Create a tetrahedral mesh structured grid.\n@@ -39,10 +40,17 @@ def to_tetrahedra(\n string uses a cell array rather than the active array to determine\n the number of tetrahedra to generate per cell.\n \n- pass_cell_ids : bool, default: False\n+ pass_cell_ids : bool, default: True\n Set to ``True`` to make the tetrahedra have scalar data indicating\n which cell they came from in the original\n- :class:`pyvista.RectilinearGrid`.\n+ :class:`pyvista.RectilinearGrid`. The name of this array is\n+ ``'vtkOriginalCellIds'`` within the ``cell_data``.\n+\n+ pass_cell_data : bool, default: True\n+ Set to ``True`` to make the tetradera mesh have the cell data from\n+ the original :class:`pyvista.RectilinearGrid`. This uses\n+ ``pass_cell_ids=True`` internally. If ``True``, ``pass_cell_ids``\n+ will also be set to ``True``.\n \n progress_bar : bool, default: False\n Display a progress bar to indicate progress.\n@@ -80,7 +88,7 @@ def to_tetrahedra(\n \n \"\"\"\n alg = _vtk.vtkRectilinearGridToTetrahedra()\n- alg.SetRememberVoxelId(pass_cell_ids)\n+ alg.SetRememberVoxelId(pass_cell_ids or pass_cell_data)\n if mixed is not False:\n if isinstance(mixed, str):\n self.cell_data.active_scalars_name = mixed\n@@ -107,4 +115,17 @@ def to_tetrahedra(\n \n alg.SetInputData(self)\n _update_alg(alg, progress_bar, 'Converting to tetrahedra')\n- return _get_output(alg)\n+ out = _get_output(alg)\n+ if pass_cell_data:\n+ # algorithm stores original cell ids in active scalars\n+ for name in self.cell_data: # type: ignore\n+ if name != out.cell_data.active_scalars_name:\n+ out[name] = self.cell_data[name][out.cell_data.active_scalars] # type: ignore\n+\n+ if alg.GetRememberVoxelId():\n+ # original cell_ids are not named and are the active scalars\n+ out.cell_data.set_array(\n+ out.cell_data.pop(out.cell_data.active_scalars_name), 'vtkOriginalCellIds'\n+ )\n+\n+ return out\n", "test_patch": "diff --git a/tests/filters/test_rectilinear_grid.py b/tests/filters/test_rectilinear_grid.py\n--- a/tests/filters/test_rectilinear_grid.py\n+++ b/tests/filters/test_rectilinear_grid.py\n@@ -45,3 +45,25 @@ def test_to_tetrahedral_mixed(tiny_rectilinear):\n def test_to_tetrahedral_edge_case():\n with pytest.raises(RuntimeError, match='is 1'):\n pv.UniformGrid(dimensions=(1, 2, 2)).to_tetrahedra(tetra_per_cell=12)\n+\n+\n+def test_to_tetrahedral_pass_cell_ids(tiny_rectilinear):\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_cell_data=False)\n+ assert not tet_grid.cell_data\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=True, pass_cell_data=False)\n+ assert 'vtkOriginalCellIds' in tet_grid.cell_data\n+ assert np.issubdtype(tet_grid.cell_data['vtkOriginalCellIds'].dtype, np.integer)\n+\n+\n+def test_to_tetrahedral_pass_cell_data(tiny_rectilinear):\n+ tiny_rectilinear[\"cell_data\"] = np.ones(tiny_rectilinear.n_cells)\n+\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_cell_data=False)\n+ assert not tet_grid.cell_data\n+\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_cell_data=True)\n+ assert tet_grid.cell_data\n+ assert \"cell_data\" in tet_grid.cell_data\n+\n+ # automatically added\n+ assert 'vtkOriginalCellIds' in tet_grid.cell_data\n", "problem_statement": "Allow passing through cell data in `to_tetrahedra` method in RectilinearGrid\n### Describe the feature you would like to be added.\n\nNo cell data is passed through when converting to a tetrahedra. The user can currently request to pass through the original cell id, but it requires one more step to regenerate the cell data on the tetrahedralized mesh.\n\n### Links to VTK Documentation, Examples, or Class Definitions.\n\n_No response_\n\n### Pseudocode or Screenshots\n\nCurrently we have to do\r\n\r\n```python\r\nmesh # Rectilinear or UniformGrid, which has cell data \"cell_data\"\r\ntetra_mesh = mesh.to_tetrahedra(pass_cell_ids=True)\r\ntetra_mesh[\"cell_data\"] = mesh[\"cell_data\"][tetra_mesh.cell_data.active_scalars]\r\n```\r\n\r\nIt would be better to do something like\r\n\r\n```python\r\nmesh # Rectilinear or UniformGrid, which has cell data \"cell_data\"\r\ntetra_mesh = mesh.to_tetrahedra(pass_cell_data=True) # the prior code would occur inside the method\r\n```\n", "hints_text": "", "created_at": "2023-04-20T18:23:33Z", "version": "0.39", "FAIL_TO_PASS": ["tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_pass_cell_ids", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_pass_cell_data"], "PASS_TO_PASS": ["tests/filters/test_rectilinear_grid.py::test_to_tetrahedral[5]", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral[6]", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral[12]", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_raise", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_mixed", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_edge_case"], "environment_setup_commit": "4c2d1aed10b1600d520271beba8579c71433e808"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4414", "base_commit": "438dd0d6ea2ebee73ecccdba878837af8fd83d7d", "patch": "diff --git a/pyvista/core/filters/poly_data.py b/pyvista/core/filters/poly_data.py\n--- a/pyvista/core/filters/poly_data.py\n+++ b/pyvista/core/filters/poly_data.py\n@@ -420,11 +420,11 @@ def merge(\n \"\"\"\n # check if dataset or datasets are not polydata\n if isinstance(dataset, (list, tuple, pyvista.MultiBlock)):\n- is_pd = all(isinstance(data, pyvista.PolyData) for data in dataset)\n+ is_polydata = all(isinstance(data, pyvista.PolyData) for data in dataset)\n else:\n- is_pd = isinstance(dataset, pyvista.PolyData)\n+ is_polydata = isinstance(dataset, pyvista.PolyData)\n \n- if inplace and not is_pd:\n+ if inplace and not is_polydata:\n raise TypeError(\"In-place merge requires both input datasets to be PolyData.\")\n \n merged = DataSetFilters.merge(\n@@ -438,12 +438,28 @@ def merge(\n )\n \n # convert back to a polydata if both inputs were polydata\n- if is_pd:\n- pd_merged = pyvista.PolyData(merged.points, faces=merged.cells, n_faces=merged.n_cells)\n- pd_merged.point_data.update(merged.point_data)\n- pd_merged.cell_data.update(merged.cell_data)\n- pd_merged.field_data.update(merged.field_data)\n- merged = pd_merged\n+ if is_polydata:\n+ # if either of the input datasets contained lines or strips, we\n+ # must use extract_geometry to ensure they get converted back\n+ # correctly. This incurrs a performance penalty, but is needed to\n+ # maintain data consistency.\n+ if isinstance(dataset, (list, tuple, pyvista.MultiBlock)):\n+ dataset_has_lines_strips = any(\n+ [ds.n_lines or ds.n_strips or ds.n_verts for ds in dataset]\n+ )\n+ else:\n+ dataset_has_lines_strips = dataset.n_lines or dataset.n_strips or dataset.n_verts\n+\n+ if self.n_lines or self.n_strips or self.n_verts or dataset_has_lines_strips:\n+ merged = merged.extract_geometry()\n+ else:\n+ polydata_merged = pyvista.PolyData(\n+ merged.points, faces=merged.cells, n_faces=merged.n_cells, deep=False\n+ )\n+ polydata_merged.point_data.update(merged.point_data)\n+ polydata_merged.cell_data.update(merged.cell_data)\n+ polydata_merged.field_data.update(merged.field_data)\n+ merged = polydata_merged\n \n if inplace:\n self.deep_copy(merged)\n", "test_patch": "diff --git a/tests/test_polydata.py b/tests/test_polydata.py\n--- a/tests/test_polydata.py\n+++ b/tests/test_polydata.py\n@@ -340,6 +340,16 @@ def test_merge(sphere, sphere_shifted, hexbeam):\n merged = mesh.merge(sphere_shifted, inplace=True)\n assert merged is mesh\n \n+ # test merge with lines\n+ arc_1 = pyvista.CircularArc([0, 0, 0], [10, 10, 0], [10, 0, 0], negative=False, resolution=3)\n+ arc_2 = pyvista.CircularArc([10, 10, 0], [20, 0, 0], [10, 0, 0], negative=False, resolution=3)\n+ merged = arc_1 + arc_2\n+ assert merged.n_lines == 2\n+\n+ # test merge with lines as iterable\n+ merged = arc_1.merge((arc_2, arc_2))\n+ assert merged.n_lines == 3\n+\n # test main_has_priority\n mesh = sphere.copy()\n data_main = np.arange(mesh.n_points, dtype=float)\n", "problem_statement": "Adding ``CircularArc``s together does not provide a line\n### Describe the bug, what's wrong, and what you expected.\r\n\r\nDon't know if it can be considered a bug or not but...\r\n\r\nIf you define two consecutive ``pv.CircularArc`` and you plot them, weird things start to appear with the new PyVista 0.39 version. Run the following code snippet using ``pyvista==0.38.6`` and ``pyvista==0.39.0``\r\n\r\n### Steps to reproduce the bug.\r\n\r\n```python\r\nimport pyvista as pv\r\n\r\n\r\n# Define your arcs\r\n#\r\n# Y (s2)\r\n# ^ ____(e1)____\r\n# | / \\\r\n# | / \\\r\n# |/ \\\r\n# (s1)O ------(c)-------(e2)----> X\r\n#\r\n# Let's imagine the above is an arc from (0,0) to (10,10) and origin\r\n# at (10,0); and another consecutive arc from (10,10) to (20,0) and\r\n# origin at (10,0)\r\n#\r\narc_1 = pv.CircularArc([0, 0, 0], [10, 10, 0], [10, 0, 0], negative=False)\r\narc_2 = pv.CircularArc([10, 10, 0], [20, 0, 0], [10, 0, 0], negative=False)\r\n\r\n# ========== CRITICAL BEHAVIOR ==========\r\n# I add them together\r\narc = arc_1 + arc_2\r\n# ========== CRITICAL BEHAVIOR ==========\r\n\r\n# Instantiate plotter\r\npl = pv.Plotter()\r\n\r\n# Add the polydata\r\npl.add_mesh(arc)\r\n\r\n# Plotter config: view from the top\r\npl.view_vector(vector=[0, 0, 1], viewup=[0, 1, 0])\r\n\r\n# Plot\r\npl.show()\r\n\r\n```\r\n\r\n### System Information\r\n\r\n```shell\r\nFor PyVista 0.38.6\r\n\r\n--------------------------------------------------------------------------------\r\n Date: Thu May 11 13:49:09 2023 Romance Daylight Time\r\n\r\n OS : Windows\r\n CPU(s) : 16\r\n Machine : AMD64\r\n Architecture : 64bit\r\n Environment : Python\r\n GPU Vendor : Intel\r\n GPU Renderer : Intel(R) UHD Graphics\r\n GPU Version : 4.5.0 - Build 30.0.100.9955\r\n\r\n Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr 5 2023, 00:38:17) [MSC v.1929 64\r\n bit (AMD64)]\r\n\r\n pyvista : 0.38.6\r\n vtk : 9.2.6\r\n numpy : 1.24.3\r\n imageio : 2.28.1\r\n scooby : 0.7.2\r\n pooch : v1.7.0\r\n matplotlib : 3.7.1\r\n--------------------------------------------------------------------------------\r\n\r\nFor PyVista 0.39.0\r\n\r\n--------------------------------------------------------------------------------\r\n Date: Thu May 11 13:50:00 2023 Romance Daylight Time\r\n\r\n OS : Windows\r\n CPU(s) : 16\r\n Machine : AMD64\r\n Architecture : 64bit\r\n Environment : Python\r\n GPU Vendor : Intel\r\n GPU Renderer : Intel(R) UHD Graphics\r\n GPU Version : 4.5.0 - Build 30.0.100.9955\r\n MathText Support : False\r\n\r\n Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr 5 2023, 00:38:17) [MSC v.1929 64\r\n bit (AMD64)]\r\n\r\n pyvista : 0.39.0\r\n vtk : 9.2.6\r\n numpy : 1.24.3\r\n matplotlib : 3.7.1\r\n scooby : 0.7.2\r\n pooch : v1.7.0\r\n--------------------------------------------------------------------------------\r\n```\r\n\r\n\r\n### Screenshots\r\n\r\nPyVista 0.39\r\n\r\n\r\n\r\nPyVista 0.38.6\r\n\r\n\r\n\n", "hints_text": "IMO, we shouldn't be seeing a surface, but two consecutive lines as it is shown in PyVista 0.38.6.", "created_at": "2023-05-12T03:06:04Z", "version": "0.40", "FAIL_TO_PASS": ["tests/test_polydata.py::test_merge"], "PASS_TO_PASS": ["tests/test_polydata.py::test_init", "tests/test_polydata.py::test_init_from_pdata", "tests/test_polydata.py::test_init_from_arrays", "tests/test_polydata.py::test_init_from_arrays_with_vert", "tests/test_polydata.py::test_init_from_arrays_triangular", "tests/test_polydata.py::test_init_as_points", "tests/test_polydata.py::test_init_as_points_from_list", "tests/test_polydata.py::test_invalid_init", "tests/test_polydata.py::test_invalid_file", "tests/test_polydata.py::test_lines_on_init", "tests/test_polydata.py::test_polydata_repr_str", "tests/test_polydata.py::test_geodesic", "tests/test_polydata.py::test_geodesic_fail", "tests/test_polydata.py::test_geodesic_distance", "tests/test_polydata.py::test_ray_trace", "tests/test_polydata.py::test_edge_mask", "tests/test_polydata.py::test_boolean_union_intersection", "tests/test_polydata.py::test_boolean_difference", "tests/test_polydata.py::test_boolean_difference_fail", "tests/test_polydata.py::test_subtract", "tests/test_polydata.py::test_add", "tests/test_polydata.py::test_intersection", "tests/test_polydata.py::test_curvature[mean]", "tests/test_polydata.py::test_curvature[gaussian]", "tests/test_polydata.py::test_curvature[maximum]", "tests/test_polydata.py::test_curvature[minimum]", "tests/test_polydata.py::test_invalid_curvature", "tests/test_polydata.py::test_save[.ply-True]", "tests/test_polydata.py::test_save[.ply-False]", "tests/test_polydata.py::test_save[.vtp-True]", "tests/test_polydata.py::test_save[.vtp-False]", "tests/test_polydata.py::test_save[.stl-True]", "tests/test_polydata.py::test_save[.stl-False]", "tests/test_polydata.py::test_save[.vtk-True]", "tests/test_polydata.py::test_save[.vtk-False]", "tests/test_polydata.py::test_save_ply_texture_array[3-True]", "tests/test_polydata.py::test_save_ply_texture_array[3-False]", "tests/test_polydata.py::test_save_ply_texture_array[4-True]", "tests/test_polydata.py::test_save_ply_texture_array[4-False]", "tests/test_polydata.py::test_save_ply_texture_array_catch[True]", "tests/test_polydata.py::test_save_ply_texture_array_catch[False]", "tests/test_polydata.py::test_pathlib_read_write", "tests/test_polydata.py::test_invalid_save", "tests/test_polydata.py::test_triangulate_filter", "tests/test_polydata.py::test_subdivision[butterfly]", "tests/test_polydata.py::test_subdivision[loop]", "tests/test_polydata.py::test_subdivision[linear]", "tests/test_polydata.py::test_invalid_subdivision", "tests/test_polydata.py::test_extract_feature_edges", "tests/test_polydata.py::test_extract_feature_edges_no_data", "tests/test_polydata.py::test_decimate", "tests/test_polydata.py::test_decimate_pro", "tests/test_polydata.py::test_compute_normals", "tests/test_polydata.py::test_compute_normals_inplace", "tests/test_polydata.py::test_compute_normals_split_vertices", "tests/test_polydata.py::test_point_normals", "tests/test_polydata.py::test_cell_normals", "tests/test_polydata.py::test_face_normals", "tests/test_polydata.py::test_clip_plane", "tests/test_polydata.py::test_extract_largest", "tests/test_polydata.py::test_clean", "tests/test_polydata.py::test_area", "tests/test_polydata.py::test_volume", "tests/test_polydata.py::test_remove_points_any", "tests/test_polydata.py::test_remove_points_all", "tests/test_polydata.py::test_remove_points_fail", "tests/test_polydata.py::test_vertice_cells_on_read", "tests/test_polydata.py::test_center_of_mass", "tests/test_polydata.py::test_project_points_to_plane", "tests/test_polydata.py::test_tube", "tests/test_polydata.py::test_smooth_inplace", "tests/test_polydata.py::test_delaunay_2d", "tests/test_polydata.py::test_lines", "tests/test_polydata.py::test_strips", "tests/test_polydata.py::test_ribbon_filter", "tests/test_polydata.py::test_is_all_triangles", "tests/test_polydata.py::test_extrude", "tests/test_polydata.py::test_extrude_capping_warnings", "tests/test_polydata.py::test_flip_normals", "tests/test_polydata.py::test_n_verts", "tests/test_polydata.py::test_n_lines", "tests/test_polydata.py::test_geodesic_disconnected"], "environment_setup_commit": "19938bf14e7705ed1e7d4c9aa6558d90df6de9d1"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4417", "base_commit": "a8921b94b91a7d9809c9b5ac2ef9c981b5f71ea1", "patch": "diff --git a/pyvista/core/composite.py b/pyvista/core/composite.py\n--- a/pyvista/core/composite.py\n+++ b/pyvista/core/composite.py\n@@ -1110,6 +1110,8 @@ def as_polydata_blocks(self, copy=False):\n if block is not None:\n if isinstance(block, MultiBlock):\n dataset.replace(i, block.as_polydata_blocks(copy=copy))\n+ elif isinstance(block, pyvista.PointSet):\n+ dataset.replace(i, block.cast_to_polydata(deep=True))\n elif not isinstance(block, pyvista.PolyData):\n dataset.replace(i, block.extract_surface())\n elif copy:\n", "test_patch": "diff --git a/tests/test_composite.py b/tests/test_composite.py\n--- a/tests/test_composite.py\n+++ b/tests/test_composite.py\n@@ -753,9 +753,13 @@ def test_set_active_scalars_mixed(multiblock_poly):\n \n \n def test_to_polydata(multiblock_all):\n+ if pyvista.vtk_version_info >= (9, 1, 0):\n+ multiblock_all.append(pyvista.PointSet([0.0, 0.0, 1.0])) # missing pointset\n assert not multiblock_all.is_all_polydata\n \n dataset_a = multiblock_all.as_polydata_blocks()\n+ if pyvista.vtk_version_info >= (9, 1, 0):\n+ assert dataset_a[-1].n_points == 1\n assert not multiblock_all.is_all_polydata\n assert dataset_a.is_all_polydata\n \n", "problem_statement": "``Multiblock``.plot does not work when using ``PointSet``\n### Describe the bug, what's wrong, and what you expected.\n\nIt seems ``MultiBlock`` entities made of ``PointSet`` plot nothing when using ``plot`` method.\n\n### Steps to reproduce the bug.\n\n```python\r\nimport pyvista as pv\r\nimport numpy as np\r\n\r\npoints_arr = np.array(\r\n [\r\n [0.0, 1.0, 0.0],\r\n [0.0, 0.0, 0.0],\r\n [1.0, 1.0, 0.0],\r\n [1.0, 0.0, 0.0],\r\n [0.0, 0.0, 1.0],\r\n [1.0, 0.0, 1.0],\r\n [1.0, 1.0, 1.0],\r\n [0.0, 1.0, 1.0],\r\n ]\r\n)\r\n\r\npoints = pv.MultiBlock()\r\nfor each_kp in points_arr:\r\n points.append(pv.PointSet(each_kp))\r\n\r\npoints.plot()\r\n```\n\n### System Information\n\n```shell\n--------------------------------------------------------------------------------\r\n Date: Wed May 10 18:07:18 2023 CEST\r\n\r\n OS : Darwin\r\n CPU(s) : 8\r\n Machine : arm64\r\n Architecture : 64bit\r\n RAM : 16.0 GiB\r\n Environment : IPython\r\n File system : apfs\r\n GPU Vendor : Apple\r\n GPU Renderer : Apple M2\r\n GPU Version : 4.1 Metal - 83.1\r\n MathText Support : False\r\n\r\n Python 3.11.1 (main, Dec 23 2022, 09:28:24) [Clang 14.0.0\r\n (clang-1400.0.29.202)]\r\n\r\n pyvista : 0.39.0\r\n vtk : 9.2.6\r\n numpy : 1.24.3\r\n matplotlib : 3.7.1\r\n scooby : 0.7.1\r\n pooch : v1.7.0\r\n imageio : 2.28.0\r\n IPython : 8.12.1\r\n ipywidgets : 8.0.6\r\n scipy : 1.10.1\r\n tqdm : 4.65.0\r\n jupyterlab : 3.6.3\r\n pythreejs : 2.4.2\r\n nest_asyncio : 1.5.6\r\n--------------------------------------------------------------------------------\n```\n\n\n### Screenshots\n\n<img width=\"624\" alt=\"image\" src=\"https://github.com/pyvista/pyvista/assets/28149841/a1b0999f-2d35-4911-a216-eb6503955860\">\r\n\n", "hints_text": "I can reproduce this problem. We'll add it for the v0.39.1 milestone.\nThe trick is this bit of code:\r\n\r\nhttps://github.com/pyvista/pyvista/blob/a8921b94b91a7d9809c9b5ac2ef9c981b5f71ea1/pyvista/plotting/plotting.py#L3218-L3224\r\n\r\nwhich isn't used for `MultiBlock` plotting because `add_mesh` forwards to `add_composite()`\r\n\r\nhttps://github.com/pyvista/pyvista/blob/a8921b94b91a7d9809c9b5ac2ef9c981b5f71ea1/pyvista/plotting/plotting.py#L3230\r\n\r\nBut then I realized this block should handle it\r\n\r\nhttps://github.com/pyvista/pyvista/blob/a8921b94b91a7d9809c9b5ac2ef9c981b5f71ea1/pyvista/plotting/plotting.py#L2544\r\n\r\n\r\nso maybe there's a bug in that method or the copy isn't propagating? Not sure...\r\n\r\n", "created_at": "2023-05-12T16:10:15Z", "version": "0.40", "FAIL_TO_PASS": ["tests/test_composite.py::test_to_polydata"], "PASS_TO_PASS": ["tests/test_composite.py::test_multi_block_init_vtk", "tests/test_composite.py::test_multi_block_init_dict", "tests/test_composite.py::test_multi_block_keys", "tests/test_composite.py::test_multi_block_init_list", "tests/test_composite.py::test_multi_block_append", "tests/test_composite.py::test_multi_block_set_get_ers", "tests/test_composite.py::test_replace", "tests/test_composite.py::test_pop", "tests/test_composite.py::test_del_slice", "tests/test_composite.py::test_slicing_multiple_in_setitem", "tests/test_composite.py::test_reverse", "tests/test_composite.py::test_insert", "tests/test_composite.py::test_extend", "tests/test_composite.py::test_multi_block_clean", "tests/test_composite.py::test_multi_block_repr", "tests/test_composite.py::test_multi_block_eq", "tests/test_composite.py::test_multi_block_io[True-.vtm-True]", "tests/test_composite.py::test_multi_block_io[True-.vtm-False]", "tests/test_composite.py::test_multi_block_io[True-.vtmb-True]", "tests/test_composite.py::test_multi_block_io[True-.vtmb-False]", "tests/test_composite.py::test_multi_block_io[False-.vtm-True]", "tests/test_composite.py::test_multi_block_io[False-.vtm-False]", "tests/test_composite.py::test_multi_block_io[False-.vtmb-True]", "tests/test_composite.py::test_multi_block_io[False-.vtmb-False]", "tests/test_composite.py::test_ensight_multi_block_io[vtm-True]", "tests/test_composite.py::test_ensight_multi_block_io[vtm-False]", "tests/test_composite.py::test_ensight_multi_block_io[vtmb-True]", "tests/test_composite.py::test_ensight_multi_block_io[vtmb-False]", "tests/test_composite.py::test_invalid_arg", "tests/test_composite.py::test_multi_io_erros", "tests/test_composite.py::test_extract_geometry", "tests/test_composite.py::test_combine_filter", "tests/test_composite.py::test_multi_block_copy", "tests/test_composite.py::test_multi_block_negative_index", "tests/test_composite.py::test_multi_slice_index", "tests/test_composite.py::test_slice_defaults", "tests/test_composite.py::test_slice_negatives", "tests/test_composite.py::test_multi_block_volume", "tests/test_composite.py::test_multi_block_length", "tests/test_composite.py::test_multi_block_save_lines", "tests/test_composite.py::test_multi_block_data_range", "tests/test_composite.py::test_multiblock_ref", "tests/test_composite.py::test_set_active_scalars", "tests/test_composite.py::test_set_active_scalars_multi", "tests/test_composite.py::test_set_active_scalars_components", "tests/test_composite.py::test_set_active_multi_multi", "tests/test_composite.py::test_set_active_scalars_mixed", "tests/test_composite.py::test_compute_normals", "tests/test_composite.py::test_activate_plotting_scalars"], "environment_setup_commit": "19938bf14e7705ed1e7d4c9aa6558d90df6de9d1"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4406", "base_commit": "461bb5ed5be8c9dda6e9ed765fab3224149d9c62", "patch": "diff --git a/pyvista/core/filters/rectilinear_grid.py b/pyvista/core/filters/rectilinear_grid.py\n--- a/pyvista/core/filters/rectilinear_grid.py\n+++ b/pyvista/core/filters/rectilinear_grid.py\n@@ -2,24 +2,29 @@\n \n import collections\n from typing import Sequence, Union\n+import warnings\n \n import numpy as np\n \n from pyvista import _vtk, abstract_class\n from pyvista.core.filters import _get_output, _update_alg\n+from pyvista.utilities import assert_empty_kwargs\n+from pyvista.utilities.misc import PyVistaDeprecationWarning\n \n \n @abstract_class\n class RectilinearGridFilters:\n \"\"\"An internal class to manage filters/algorithms for rectilinear grid datasets.\"\"\"\n \n+ # Note remove kwargs when removing deprecation for pass_cell_data\n def to_tetrahedra(\n self,\n tetra_per_cell: int = 5,\n mixed: Union[Sequence[int], bool] = False,\n pass_cell_ids: bool = True,\n- pass_cell_data: bool = True,\n+ pass_data: bool = True,\n progress_bar: bool = False,\n+ **kwargs,\n ):\n \"\"\"Create a tetrahedral mesh structured grid.\n \n@@ -46,7 +51,7 @@ def to_tetrahedra(\n :class:`pyvista.RectilinearGrid`. The name of this array is\n ``'vtkOriginalCellIds'`` within the ``cell_data``.\n \n- pass_cell_data : bool, default: True\n+ pass_data : bool, default: True\n Set to ``True`` to make the tetrahedra mesh have the cell data from\n the original :class:`pyvista.RectilinearGrid`. This uses\n ``pass_cell_ids=True`` internally. If ``True``, ``pass_cell_ids``\n@@ -55,6 +60,9 @@ def to_tetrahedra(\n progress_bar : bool, default: False\n Display a progress bar to indicate progress.\n \n+ **kwargs : dict, optional\n+ Deprecated keyword argument ``pass_cell_data``.\n+\n Returns\n -------\n pyvista.UnstructuredGrid\n@@ -87,8 +95,17 @@ def to_tetrahedra(\n >>> tet_grid.explode(factor=0.5).plot(show_edges=True)\n \n \"\"\"\n+ # Note remove this section when deprecation is done\n+ pass_cell_data = kwargs.pop(\"pass_cell_data\", None)\n+ assert_empty_kwargs(**kwargs)\n+ if pass_cell_data is not None:\n+ warnings.warn(\n+ \"pass_cell_data is a deprecated option, use pass_data\", PyVistaDeprecationWarning\n+ )\n+ pass_data = pass_cell_data\n+\n alg = _vtk.vtkRectilinearGridToTetrahedra()\n- alg.SetRememberVoxelId(pass_cell_ids or pass_cell_data)\n+ alg.SetRememberVoxelId(pass_cell_ids or pass_data)\n if mixed is not False:\n if isinstance(mixed, str):\n self.cell_data.active_scalars_name = mixed\n@@ -116,16 +133,27 @@ def to_tetrahedra(\n alg.SetInputData(self)\n _update_alg(alg, progress_bar, 'Converting to tetrahedra')\n out = _get_output(alg)\n- if pass_cell_data:\n+\n+ if pass_data:\n # algorithm stores original cell ids in active scalars\n+ # this does not preserve active scalars, but we need to\n+ # keep active scalars until they are renamed\n for name in self.cell_data: # type: ignore\n if name != out.cell_data.active_scalars_name:\n out[name] = self.cell_data[name][out.cell_data.active_scalars] # type: ignore\n \n+ for name in self.point_data: # type: ignore\n+ out[name] = self.point_data[name] # type: ignore\n+\n if alg.GetRememberVoxelId():\n # original cell_ids are not named and are the active scalars\n out.cell_data.set_array(\n out.cell_data.pop(out.cell_data.active_scalars_name), 'vtkOriginalCellIds'\n )\n \n+ if pass_data:\n+ # Now reset active scalars in cast the original mesh had data with active scalars\n+ association, name = self.active_scalars_info # type: ignore\n+ out.set_active_scalars(name, preference=association)\n+\n return out\n", "test_patch": "diff --git a/tests/filters/test_rectilinear_grid.py b/tests/filters/test_rectilinear_grid.py\n--- a/tests/filters/test_rectilinear_grid.py\n+++ b/tests/filters/test_rectilinear_grid.py\n@@ -2,6 +2,7 @@\n import pytest\n \n import pyvista as pv\n+from pyvista.utilities.misc import PyVistaDeprecationWarning\n \n \n @pytest.fixture\n@@ -48,22 +49,39 @@ def test_to_tetrahedral_edge_case():\n \n \n def test_to_tetrahedral_pass_cell_ids(tiny_rectilinear):\n- tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_cell_data=False)\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_data=False)\n assert not tet_grid.cell_data\n- tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=True, pass_cell_data=False)\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=True, pass_data=False)\n assert 'vtkOriginalCellIds' in tet_grid.cell_data\n assert np.issubdtype(tet_grid.cell_data['vtkOriginalCellIds'].dtype, np.integer)\n \n \n def test_to_tetrahedral_pass_cell_data(tiny_rectilinear):\n+ # test that data isn't passed\n tiny_rectilinear[\"cell_data\"] = np.ones(tiny_rectilinear.n_cells)\n-\n- tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_cell_data=False)\n+ tiny_rectilinear[\"point_data\"] = np.arange(tiny_rectilinear.n_points)\n+ tiny_rectilinear.set_active_scalars(\"cell_data\")\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_data=False)\n assert not tet_grid.cell_data\n+ assert not tet_grid.point_data\n \n- tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_cell_data=True)\n+ # test with cell data\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_data=True)\n assert tet_grid.cell_data\n assert \"cell_data\" in tet_grid.cell_data\n+ assert \"point_data\" in tet_grid.point_data\n+ assert tet_grid.active_scalars_name == \"cell_data\"\n \n # automatically added\n assert 'vtkOriginalCellIds' in tet_grid.cell_data\n+\n+ with pytest.warns(PyVistaDeprecationWarning):\n+ tiny_rectilinear.to_tetrahedra(pass_cell_data=True)\n+ if pv._version.version_info >= (0, 43, 0):\n+ raise RuntimeError('Remove this deprecated kwarg')\n+\n+ # Test point data active\n+ tiny_rectilinear.set_active_scalars(\"point_data\")\n+ assert tiny_rectilinear.active_scalars_name == \"point_data\"\n+ tet_grid = tiny_rectilinear.to_tetrahedra(pass_cell_ids=False, pass_data=True)\n+ assert tet_grid.active_scalars_name == \"point_data\"\n", "problem_statement": "to_tetrahedra active scalars\n### Describe the bug, what's wrong, and what you expected.\n\n#4311 passes cell data through the `to_tetrahedra` call. However, after these changes. The active scalars information is lost.\r\n\r\ncc @akaszynski who implemented these changes in that PR.\n\n### Steps to reproduce the bug.\n\n```py\r\nimport pyvista as pv\r\nimport numpy as np\r\nmesh = pv.UniformGrid(dimensions=(10, 10, 10))\r\nmesh[\"a\"] = np.zeros(mesh.n_cells)\r\nmesh[\"b\"] = np.ones(mesh.n_cells)\r\nprint(mesh.cell_data)\r\ntet = mesh.to_tetrahedra()\r\nprint(tet.cell_data)\r\n```\r\n\r\n```txt\r\npyvista DataSetAttributes\r\nAssociation : CELL\r\nActive Scalars : a\r\nActive Vectors : None\r\nActive Texture : None\r\nActive Normals : None\r\nContains arrays :\r\n a float64 (729,) SCALARS\r\n b float64 (729,)\r\npyvista DataSetAttributes\r\nAssociation : CELL\r\nActive Scalars : None\r\nActive Vectors : None\r\nActive Texture : None\r\nActive Normals : None\r\nContains arrays :\r\n a float64 (3645,)\r\n b float64 (3645,)\r\n vtkOriginalCellIds int32 (3645,)\r\n```\n\n### System Information\n\n```shell\nPython 3.11.2 (main, Mar 23 2023, 17:12:29) [GCC 10.2.1 20210110]\r\n\r\n pyvista : 0.39.0\r\n vtk : 9.2.6\r\n numpy : 1.24.2\r\n matplotlib : 3.7.1\r\n scooby : 0.7.1\r\n pooch : v1.7.0\r\n imageio : 2.27.0\r\n IPython : 8.12.0\r\n--------------------------------------------------------------------------------\n```\n\n\n### Screenshots\n\n_No response_\n", "hints_text": "First, these lines should reset the active_scalars to the last scalars added to the tetrahedral mesh:\r\n\r\nhttps://github.com/pyvista/pyvista/blob/a87cf37d9cea6fc68d8099a56d86ded8f6e78734/pyvista/core/filters/rectilinear_grid.py#L119-L123\r\n\r\nThese subsequent lines pop out the active scalars, which is somehow the blank scalars, and set it as \"vtkOriginalCellIds\".\r\n\r\nhttps://github.com/pyvista/pyvista/blob/a87cf37d9cea6fc68d8099a56d86ded8f6e78734/pyvista/core/filters/rectilinear_grid.py#L125-L129\r\n\r\nEdit: I am wrong the first set of lines, would only set active scalars if there are none present, but the unnamed scalars are active. We just need to reset the active scalars according to the original mesh I think.\nGood point. Thanks @MatthewFlamm for pointing this out. We'll have this added in the v0.39.1 patch.", "created_at": "2023-05-10T18:54:53Z", "version": "0.40", "FAIL_TO_PASS": ["tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_pass_cell_ids", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_pass_cell_data"], "PASS_TO_PASS": ["tests/filters/test_rectilinear_grid.py::test_to_tetrahedral[5]", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral[6]", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral[12]", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_raise", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_mixed", "tests/filters/test_rectilinear_grid.py::test_to_tetrahedral_edge_case"], "environment_setup_commit": "19938bf14e7705ed1e7d4c9aa6558d90df6de9d1"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4226", "base_commit": "1f28aadcb39b5be2f955feae9d462eadb0dfc5c1", "patch": "diff --git a/pyvista/plotting/_property.py b/pyvista/plotting/_property.py\n--- a/pyvista/plotting/_property.py\n+++ b/pyvista/plotting/_property.py\n@@ -4,7 +4,7 @@\n import pyvista as pv\n from pyvista import _vtk\n from pyvista.plotting.opts import InterpolationType\n-from pyvista.utilities.misc import no_new_attr\n+from pyvista.utilities.misc import _check_range, no_new_attr\n \n from .colors import Color\n \n@@ -74,7 +74,7 @@ class Property(_vtk.vtkProperty):\n The specular lighting coefficient.\n \n specular_power : float, default: :attr:`pyvista.themes._LightingConfig.specular_power`\n- The specular power. Between 0.0 and 128.0.\n+ The specular power. Must be between 0.0 and 128.0.\n \n show_edges : bool, default: :attr:`pyvista.themes.DefaultTheme.show_edges`\n Shows the edges. Does not apply to a wireframe representation.\n@@ -395,6 +395,7 @@ def opacity(self) -> float:\n \n @opacity.setter\n def opacity(self, value: float):\n+ _check_range(value, (0, 1), 'opacity')\n self.SetOpacity(value)\n \n @property\n@@ -460,10 +461,11 @@ def lighting(self, value: bool):\n def ambient(self) -> float:\n \"\"\"Return or set ambient.\n \n- When lighting is enabled, this is the amount of light in\n- the range of 0 to 1 (default 0.0) that reaches the actor\n- when not directed at the light source emitted from the\n- viewer.\n+ Default Default :attr:`pyvista.themes._LightingConfig.ambient`.\n+\n+ When lighting is enabled, this is the amount of light in the range\n+ of 0 to 1 that reaches the actor when not directed at the light\n+ source emitted from the viewer.\n \n Examples\n --------\n@@ -493,17 +495,19 @@ def ambient(self) -> float:\n \n @ambient.setter\n def ambient(self, value: float):\n+ _check_range(value, (0, 1), 'ambient')\n self.SetAmbient(value)\n \n @property\n def diffuse(self) -> float:\n \"\"\"Return or set the diffuse lighting coefficient.\n \n- Default 1.0.\n+ Default :attr:`pyvista.themes._LightingConfig.diffuse`.\n \n- This is the scattering of light by reflection or transmission. Diffuse\n- reflection results when light strikes an irregular surface such as a\n- frosted window or the surface of a frosted or coated light bulb.\n+ This is the scattering of light by reflection or\n+ transmission. Diffuse reflection results when light strikes an\n+ irregular surface such as a frosted window or the surface of a\n+ frosted or coated light bulb. Must be between 0 and 1.\n \n Examples\n --------\n@@ -533,16 +537,17 @@ def diffuse(self) -> float:\n \n @diffuse.setter\n def diffuse(self, value: float):\n+ _check_range(value, (0, 1), 'diffuse')\n self.SetDiffuse(value)\n \n @property\n def specular(self) -> float:\n \"\"\"Return or set specular.\n \n- Default 0.0\n+ Default Default :attr:`pyvista.themes._LightingConfig.specular`.\n \n- Specular lighting simulates the bright spot of a light that appears on\n- shiny objects.\n+ Specular lighting simulates the bright spot of a light that appears\n+ on shiny objects. Must be between 0 and 1.\n \n Examples\n --------\n@@ -572,13 +577,16 @@ def specular(self) -> float:\n \n @specular.setter\n def specular(self, value: float):\n+ _check_range(value, (0, 1), 'specular')\n self.SetSpecular(value)\n \n @property\n def specular_power(self) -> float:\n \"\"\"Return or set specular power.\n \n- The specular power. Between 0.0 and 128.0. Default 1.0\n+ Default :attr:`pyvista.themes._LightingConfig.specular_power`.\n+\n+ The specular power. Must be between 0.0 and 128.0.\n \n Examples\n --------\n@@ -616,14 +624,17 @@ def specular_power(self) -> float:\n \n @specular_power.setter\n def specular_power(self, value: float):\n+ _check_range(value, (0, 128), 'specular_power')\n self.SetSpecularPower(value)\n \n @property\n def metallic(self) -> float:\n \"\"\"Return or set metallic.\n \n+ Default :attr:`pyvista.themes._LightingConfig.metallic`.\n+\n This requires that the interpolation be set to ``'Physically based\n- rendering'``\n+ rendering'``. Must be between 0 and 1.\n \n Examples\n --------\n@@ -657,14 +668,17 @@ def metallic(self) -> float:\n \n @metallic.setter\n def metallic(self, value: float):\n+ _check_range(value, (0, 1), 'metallic')\n self.SetMetallic(value)\n \n @property\n def roughness(self) -> float:\n \"\"\"Return or set roughness.\n \n+ Default :attr:`pyvista.themes._LightingConfig.roughness`.\n+\n This requires that the interpolation be set to ``'Physically based\n- rendering'``\n+ rendering'``. Must be between 0 and 1.\n \n Examples\n --------\n@@ -699,12 +713,15 @@ def roughness(self) -> float:\n \n @roughness.setter\n def roughness(self, value: bool):\n+ _check_range(value, (0, 1), 'roughness')\n self.SetRoughness(value)\n \n @property\n def interpolation(self) -> InterpolationType:\n \"\"\"Return or set the method of shading.\n \n+ Defaults to :attr:`pyvista.themes._LightingConfig.interpolation`.\n+\n One of the following options.\n \n * ``'Physically based rendering'`` - Physically based rendering.\n@@ -760,11 +777,13 @@ def interpolation(self, value: Union[str, int, InterpolationType]):\n def render_points_as_spheres(self) -> bool:\n \"\"\"Return or set rendering points as spheres.\n \n+ Defaults to :attr:`pyvista.themes.DefaultTheme.render_points_as_spheres`.\n+\n Requires representation style be set to ``'points'``.\n \n Examples\n --------\n- Enable rendering points as spheres\n+ Enable rendering points as spheres.\n \n >>> import pyvista as pv\n >>> prop = pv.Property()\n@@ -795,6 +814,8 @@ def render_points_as_spheres(self, value: bool):\n def render_lines_as_tubes(self) -> bool:\n \"\"\"Return or set rendering lines as tubes.\n \n+ Defaults to :attr:`pyvista.themes.DefaultTheme.render_lines_as_tubes`.\n+\n Requires representation style be set to ``'wireframe'``.\n \n Examples\n@@ -830,6 +851,8 @@ def render_lines_as_tubes(self, value: bool):\n def line_width(self) -> float:\n \"\"\"Return or set the line width.\n \n+ Defaults to :attr:`pyvista.themes.DefaultTheme.line_width`.\n+\n Examples\n --------\n Change the line width to ``10``.\n@@ -862,6 +885,8 @@ def line_width(self, value: bool):\n def point_size(self):\n \"\"\"Return or set the point size.\n \n+ Defaults to :attr:`pyvista.themes.DefaultTheme.point_size`.\n+\n Examples\n --------\n Change the point size to ``10.0``.\n@@ -1095,6 +1120,7 @@ def anisotropy(self, value: float):\n from pyvista.core.errors import VTKVersionError\n \n raise VTKVersionError('Anisotropy requires VTK v9.1.0 or newer.')\n+ _check_range(value, (0, 1), 'anisotropy')\n self.SetAnisotropy(value)\n \n def plot(self, **kwargs) -> None:\ndiff --git a/pyvista/plotting/composite_mapper.py b/pyvista/plotting/composite_mapper.py\n--- a/pyvista/plotting/composite_mapper.py\n+++ b/pyvista/plotting/composite_mapper.py\n@@ -11,7 +11,7 @@\n from pyvista import _vtk\n from pyvista.utilities import convert_array, convert_string_array\n \n-from ..utilities.misc import vtk_version_info\n+from ..utilities.misc import _check_range, vtk_version_info\n from .colors import Color\n from .mapper import _BaseMapper\n \n@@ -205,6 +205,7 @@ def opacity(self, new_opacity: float):\n self._attr.Modified()\n return\n \n+ _check_range(new_opacity, (0, 1), 'opacity')\n self._attr.SetBlockOpacity(self._block, new_opacity)\n \n @property\ndiff --git a/pyvista/themes.py b/pyvista/themes.py\n--- a/pyvista/themes.py\n+++ b/pyvista/themes.py\n@@ -41,7 +41,7 @@\n from .plotting.opts import InterpolationType\n from .plotting.plotting import Plotter\n from .plotting.tools import parse_font_family\n-from .utilities.misc import PyVistaDeprecationWarning\n+from .utilities.misc import PyVistaDeprecationWarning, _check_range\n \n \n class _rcParams(dict): # pragma: no cover\n@@ -73,12 +73,6 @@ def __repr__(self):\n return repr(pyvista.global_theme)\n \n \n-def _check_between_zero_and_one(value: float, value_name: str = 'value'):\n- \"\"\"Check if a value is between zero and one.\"\"\"\n- if value < 0 or value > 1:\n- raise ValueError(f'{value_name} must be between 0 and 1.')\n-\n-\n def load_theme(filename):\n \"\"\"Load a theme from a file.\n \n@@ -288,9 +282,8 @@ def interpolation(self, interpolation: Union[str, int, InterpolationType]):\n def metallic(self) -> float:\n \"\"\"Return or set the metallic value.\n \n- Usually this value is either 0 or 1 for a real material but any\n- value in between is valid. This parameter is only used by PBR\n- interpolation.\n+ This requires that the interpolation be set to ``'Physically based\n+ rendering'``. Must be between 0 and 1.\n \n Examples\n --------\n@@ -307,6 +300,7 @@ def metallic(self) -> float:\n \n @metallic.setter\n def metallic(self, metallic: float):\n+ _check_range(metallic, (0, 1), 'metallic')\n self._metallic = metallic\n \n @property\n@@ -332,6 +326,7 @@ def roughness(self) -> float:\n \n @roughness.setter\n def roughness(self, roughness: float):\n+ _check_range(roughness, (0, 1), 'roughness')\n self._roughness = roughness\n \n @property\n@@ -356,12 +351,18 @@ def ambient(self) -> float:\n \n @ambient.setter\n def ambient(self, ambient: float):\n+ _check_range(ambient, (0, 1), 'ambient')\n self._ambient = ambient\n \n @property\n def diffuse(self) -> float:\n \"\"\"Return or set the diffuse value.\n \n+ This is the scattering of light by reflection or\n+ transmission. Diffuse reflection results when light strikes an\n+ irregular surface such as a frosted window or the surface of a\n+ frosted or coated light bulb. Must be between 0 and 1.\n+\n Examples\n --------\n Set the global diffuse lighting value to ``0.5``.\n@@ -376,13 +377,15 @@ def diffuse(self) -> float:\n \n @diffuse.setter\n def diffuse(self, diffuse: float):\n+ _check_range(diffuse, (0, 1), 'diffuse')\n self._diffuse = diffuse\n \n @property\n def specular(self) -> float:\n \"\"\"Return or set the specular value.\n \n- Should be between 0 and 1.\n+ Specular lighting simulates the bright spot of a light that appears\n+ on shiny objects. Must be between 0 and 1.\n \n Examples\n --------\n@@ -398,12 +401,15 @@ def specular(self) -> float:\n \n @specular.setter\n def specular(self, specular: float):\n+ _check_range(specular, (0, 1), 'specular')\n self._specular = specular\n \n @property\n def specular_power(self) -> float:\n \"\"\"Return or set the specular power value.\n \n+ Must be between 0.0 and 128.0.\n+\n Examples\n --------\n Set the global specular power value to ``50``.\n@@ -418,6 +424,7 @@ def specular_power(self) -> float:\n \n @specular_power.setter\n def specular_power(self, specular_power: float):\n+ _check_range(specular_power, (0, 128), 'specular_power')\n self._specular_power = specular_power\n \n @property\n@@ -603,7 +610,7 @@ def opacity(self) -> float:\n \n @opacity.setter\n def opacity(self, opacity: float):\n- _check_between_zero_and_one(opacity, 'opacity')\n+ _check_range(opacity, (0, 1), 'opacity')\n self._opacity = float(opacity)\n \n @property\n@@ -641,7 +648,7 @@ def decimate(self, decimate: float):\n if decimate is None:\n self._decimate = None\n else:\n- _check_between_zero_and_one(decimate, 'decimate')\n+ _check_range(decimate, (0, 1), 'decimate')\n self._decimate = float(decimate)\n \n def __repr__(self):\n@@ -1138,6 +1145,7 @@ def cap_opacity(self) -> float:\n \n @cap_opacity.setter\n def cap_opacity(self, cap_opacity: float):\n+ _check_range(cap_opacity, (0, 1), 'cap_opacity')\n self._cap_opacity = float(cap_opacity)\n \n @property\n@@ -1723,7 +1731,7 @@ def opacity(self) -> float:\n \n @opacity.setter\n def opacity(self, opacity: float):\n- _check_between_zero_and_one(opacity, 'opacity')\n+ _check_range(opacity, (0, 1), 'opacity')\n self._opacity = float(opacity)\n \n @property\ndiff --git a/pyvista/utilities/misc.py b/pyvista/utilities/misc.py\n--- a/pyvista/utilities/misc.py\n+++ b/pyvista/utilities/misc.py\n@@ -27,6 +27,14 @@ def _set_plot_theme_from_env():\n )\n \n \n+def _check_range(value, rng, parm_name):\n+ \"\"\"Check if a parameter is within a range.\"\"\"\n+ if value < rng[0] or value > rng[1]:\n+ raise ValueError(\n+ f'The value {float(value)} for `{parm_name}` is outside the acceptable range {tuple(rng)}.'\n+ )\n+\n+\n @lru_cache(maxsize=None)\n def has_module(module_name):\n \"\"\"Return if a module can be imported.\"\"\"\n", "test_patch": "diff --git a/tests/test_property.py b/tests/test_property.py\n--- a/tests/test_property.py\n+++ b/tests/test_property.py\n@@ -1,6 +1,7 @@\n import pytest\n \n import pyvista as pv\n+from pyvista.plotting._property import _check_range\n \n \n @pytest.fixture()\n@@ -8,6 +9,14 @@ def prop():\n return pv.Property()\n \n \n+def test_check_range():\n+ with pytest.raises(ValueError, match=\"outside the acceptable\"):\n+ _check_range(-1, (0, 1), 'parm')\n+ with pytest.raises(ValueError, match=\"outside the acceptable\"):\n+ _check_range(2, (0, 1), 'parm')\n+ assert _check_range(0, (0, 1), 'parm') is None\n+\n+\n def test_property_init():\n prop = pv.Property()\n \n@@ -31,6 +40,8 @@ def test_property_opacity(prop):\n opacity = 0.5\n prop.opacity = opacity\n assert prop.opacity == opacity\n+ with pytest.raises(ValueError):\n+ prop.opacity = 2\n \n \n def test_property_show_edges(prop):\n@@ -49,30 +60,40 @@ def test_property_ambient(prop):\n value = 0.45\n prop.ambient = value\n assert prop.ambient == value\n+ with pytest.raises(ValueError):\n+ prop.ambient = -1\n \n \n def test_property_diffuse(prop):\n value = 0.5\n prop.diffuse = value\n assert prop.diffuse == value\n+ with pytest.raises(ValueError):\n+ prop.diffuse = 2\n \n \n def test_property_specular(prop):\n value = 0.5\n prop.specular = value\n assert prop.specular == value\n+ with pytest.raises(ValueError):\n+ prop.specular = 2\n \n \n def test_property_specular_power(prop):\n value = 0.5\n prop.specular_power = value\n assert prop.specular_power == value\n+ with pytest.raises(ValueError):\n+ prop.specular = 200\n \n \n def test_property_metallic(prop):\n value = 0.1\n prop.metallic = value\n assert prop.metallic == value\n+ with pytest.raises(ValueError):\n+ prop.metallic = -1\n \n \n def test_property_roughness(prop):\n", "problem_statement": "Diffuse and Specular setters silently ignore invalid values\n### Describe the bug, what's wrong, and what you expected.\n\nWhile working on #3870, I noticed that `diffuse` and `specular` do not always get set on `pyvista.Property`. This happens if an invalid value is used. For example, diffuse should be between 0-1, but if you pass a value of 2.0, `vtkProperty` corrects it to 1.0:\r\n\r\n```py\r\n>>> import vtk\r\n>>> prop = vtk.vtkProperty()\r\n>>> prop.SetDiffuse(2.0)\r\n>>> prop.GetDiffuse()\r\n1.0\r\n```\r\n\r\nThis similarly happens for specular, which should also have a valid range of 0-1.\r\n\r\nShould we have `pyvista.Property`'s setters for these methods error out when an invalid value is passed? I ask because I definitely wasted time trying to figure out why a diffuse value of 1.0 looks the same as 2.0 before thinking it should be between 0 and 1.\r\n\r\nPerhaps this at a minimum should be documented in the setters and docstring for `add_mesh()`?\n\n### Steps to reproduce the bug.\n\n```python\r\nimport pyvista as pv\r\n\r\npl = pv.Plotter()\r\na = pl.add_mesh(pv.Sphere(), diffuse=3.0, specular=10)\r\n# Expected to error for invalid values\r\n```\n\n### System Information\n\n```shell\nmain branch\n```\n\n\n### Screenshots\n\n_No response_\n", "hints_text": "Something similar came up [on this PR](https://github.com/pyvista/pyvista/pull/1040#issuecomment-739850576). To quote that comment of mine:\r\n> If the user sets nonsense data we should either raise, or pass it on to vtk which probably clamps internally (I haven't tested yet).\r\n\r\n(later it was discussed that yes, VTK clamps values internally). I'm not sure we came back to this point later during the PR, but anyway we ended up letting VTK do its thing, whatever that was.\r\n\r\nI'm still not sure that checking and raising makes most sense, but I agree that at least documenting these values would be nice. We apparently have a handful of these documented, but not the others. Then again if we find it to be worth specifying in the docstring, we might as well make it a hard check on our side.", "created_at": "2023-04-03T23:29:30Z", "version": "0.39", "FAIL_TO_PASS": ["tests/test_property.py::test_check_range", "tests/test_property.py::test_property_init", "tests/test_property.py::test_property_style", "tests/test_property.py::test_property_edge_color", "tests/test_property.py::test_property_opacity", "tests/test_property.py::test_property_show_edges", "tests/test_property.py::test_property_lighting", "tests/test_property.py::test_property_ambient", "tests/test_property.py::test_property_diffuse", "tests/test_property.py::test_property_specular", "tests/test_property.py::test_property_specular_power", "tests/test_property.py::test_property_metallic", "tests/test_property.py::test_property_roughness", "tests/test_property.py::test_property_interpolation", "tests/test_property.py::test_property_render_points_as_spheres", "tests/test_property.py::test_property_render_lines_as_tubes", "tests/test_property.py::test_property_point_size", "tests/test_property.py::test_property_line_width", "tests/test_property.py::test_property_culling[back]", "tests/test_property.py::test_property_culling[front]", "tests/test_property.py::test_property_culling[none]", "tests/test_property.py::test_property_diffuse_color", "tests/test_property.py::test_property_ambient_color", "tests/test_property.py::test_property_specular_color", "tests/test_property.py::test_property_anisotropy"], "PASS_TO_PASS": [], "environment_setup_commit": "4c2d1aed10b1600d520271beba8579c71433e808"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-3750", "base_commit": "3db44d72070ccd6e8fc5c7f708500424011bcc47", "patch": "diff --git a/pyvista/core/filters/data_set.py b/pyvista/core/filters/data_set.py\n--- a/pyvista/core/filters/data_set.py\n+++ b/pyvista/core/filters/data_set.py\n@@ -937,9 +937,10 @@ def threshold(\n continuous=False,\n preference='cell',\n all_scalars=False,\n- progress_bar=False,\n- component_mode=\"all\",\n+ component_mode='all',\n component=0,\n+ method='upper',\n+ progress_bar=False,\n ):\n \"\"\"Apply a ``vtkThreshold`` filter to the input dataset.\n \n@@ -956,43 +957,54 @@ def threshold(\n thresholding depends on whether that point is part of a cell that\n is kept after thresholding.\n \n+ Please also note the default ``preference`` choice for CELL data\n+ over POINT data. This is contrary to most other places in PyVista's\n+ API where the preference typically defaults to POINT data. We chose\n+ to prefer CELL data here so that if thresholding by a named array\n+ that exists for both the POINT and CELL data, this filter will\n+ default to the CELL data array while performing the CELL-wise\n+ operation.\n+\n Parameters\n ----------\n value : float or sequence, optional\n- Single value or (min, max) to be used for the data threshold. If\n+ Single value or (min, max) to be used for the data threshold. If\n a sequence, then length must be 2. If no value is specified, the\n non-NaN data range will be used to remove any NaN values.\n+ Please reference the ``method`` parameter for how single values\n+ are handled.\n \n scalars : str, optional\n Name of scalars to threshold on. Defaults to currently active scalars.\n \n- invert : bool, optional\n- If value is a single value, when invert is ``True`` cells\n- are kept when their values are below parameter ``\"value\"``.\n- When invert is ``False`` cells are kept when their value is\n- above the threshold ``\"value\"``. Default is ``False``:\n- yielding above the threshold ``\"value\"``.\n+ invert : bool, default: False\n+ Invert the threshold results. That is, cells that would have been\n+ in the output with this option off are excluded, while cells that\n+ would have been excluded from the output are included.\n \n- continuous : bool, optional\n+ .. warning::\n+ This option is only supported for VTK version 9+\n+\n+ continuous : bool, default: False\n When True, the continuous interval [minimum cell scalar,\n maximum cell scalar] will be used to intersect the threshold bound,\n rather than the set of discrete scalar values from the vertices.\n \n- preference : str, optional\n+ preference : str, default: 'cell'\n When ``scalars`` is specified, this is the preferred array\n type to search for in the dataset. Must be either\n- ``'point'`` or ``'cell'``.\n+ ``'point'`` or ``'cell'``. Throughout PyVista, the preference\n+ is typically ``'point'`` but since the threshold filter is a\n+ cell-wise operation, we prefer cell data for thresholding\n+ operations.\n \n- all_scalars : bool, optional\n+ all_scalars : bool, default: False\n If using scalars from point data, all\n points in a cell must satisfy the threshold when this\n value is ``True``. When ``False``, any point of the cell\n with a scalar value satisfying the threshold criterion\n will extract the cell. Has no effect when using cell data.\n \n- progress_bar : bool, optional\n- Display a progress bar to indicate progress.\n-\n component_mode : {'selected', 'all', 'any'}\n The method to satisfy the criteria for the threshold of\n multicomponent scalars. 'selected' (default)\n@@ -1004,6 +1016,17 @@ def threshold(\n When using ``component_mode='selected'``, this sets\n which component to threshold on.\n \n+ method : str, default: 'upper'\n+ Set the threshold method for single-values, defining which\n+ threshold bounds to use. If the ``value`` is a range, this\n+ parameter will be ignored, extracting data between the two\n+ values. For single values, ``'lower'`` will extract data\n+ lower than the ``value``. ``'upper'`` will extract data\n+ larger than the ``value``.\n+\n+ progress_bar : bool, default: False\n+ Display a progress bar to indicate progress.\n+\n Returns\n -------\n pyvista.UnstructuredGrid\n@@ -1057,31 +1080,6 @@ def threshold(\n \n field = get_array_association(self, scalars, preference=preference)\n \n- # If using an inverted range, merge the result of two filters:\n- if isinstance(value, (np.ndarray, collections.abc.Sequence)) and invert:\n- valid_range = [np.nanmin(arr), np.nanmax(arr)]\n- # Create two thresholds\n- t1 = self.threshold(\n- [valid_range[0], value[0]],\n- scalars=scalars,\n- continuous=continuous,\n- preference=preference,\n- invert=False,\n- )\n- t2 = self.threshold(\n- [value[1], valid_range[1]],\n- scalars=scalars,\n- continuous=continuous,\n- preference=preference,\n- invert=False,\n- )\n- # Use an AppendFilter to merge the two results\n- appender = _vtk.vtkAppendFilter()\n- appender.AddInputData(t1)\n- appender.AddInputData(t2)\n- _update_alg(appender, progress_bar, 'Thresholding')\n- return _get_output(appender)\n-\n # Run a standard threshold algorithm\n alg = _vtk.vtkThreshold()\n alg.SetAllScalars(all_scalars)\n@@ -1094,18 +1092,9 @@ def threshold(\n # use valid range if no value given\n if value is None:\n value = self.get_data_range(scalars)\n- # check if value is a sequence (if so threshold by min max range like ParaView)\n- if isinstance(value, (np.ndarray, collections.abc.Sequence)):\n- if len(value) != 2:\n- raise ValueError(\n- f'Value range must be length one for a float value or two for min/max; not ({value}).'\n- )\n- alg.ThresholdBetween(value[0], value[1])\n- elif isinstance(value, collections.abc.Iterable):\n- raise TypeError('Value must either be a single scalar or a sequence.')\n- else:\n- # just a single value\n- _set_threshold_limit(alg, value, invert)\n+\n+ _set_threshold_limit(alg, value, method, invert)\n+\n if component_mode == \"component\":\n alg.SetComponentModeToUseSelected()\n dim = arr.shape[1]\n@@ -1124,6 +1113,7 @@ def threshold(\n raise ValueError(\n f\"component_mode must be 'component', 'all', or 'any' got: {component_mode}\"\n )\n+\n # Run the threshold\n _update_alg(alg, progress_bar, 'Thresholding')\n return _get_output(alg)\n@@ -1135,6 +1125,7 @@ def threshold_percent(\n invert=False,\n continuous=False,\n preference='cell',\n+ method='upper',\n progress_bar=False,\n ):\n \"\"\"Threshold the dataset by a percentage of its range on the active scalars array.\n@@ -1155,25 +1146,36 @@ def threshold_percent(\n scalars : str, optional\n Name of scalars to threshold on. Defaults to currently active scalars.\n \n- invert : bool, optional\n- When invert is ``True`` cells are kept when their values are\n- below the percentage of the range. When invert is\n- ``False``, cells are kept when their value is above the\n- percentage of the range. Default is ``False``: yielding\n- above the threshold ``\"value\"``.\n-\n- continuous : bool, optional\n- When ``True``, the continuous interval [minimum cell scalar,\n- maximum cell scalar] will be used to intersect the threshold\n- bound, rather than the set of discrete scalar values from\n- the vertices.\n+ invert : bool, default: False\n+ Invert the threshold results. That is, cells that would have been\n+ in the output with this option off are excluded, while cells that\n+ would have been excluded from the output are included.\n \n- preference : str, optional\n+ .. warning::\n+ This option is only supported for VTK version 9+\n+\n+ continuous : bool, default: False\n+ When True, the continuous interval [minimum cell scalar,\n+ maximum cell scalar] will be used to intersect the threshold bound,\n+ rather than the set of discrete scalar values from the vertices.\n+\n+ preference : str, default: 'cell'\n When ``scalars`` is specified, this is the preferred array\n type to search for in the dataset. Must be either\n- ``'point'`` or ``'cell'``.\n+ ``'point'`` or ``'cell'``. Throughout PyVista, the preference\n+ is typically ``'point'`` but since the threshold filter is a\n+ cell-wise operation, we prefer cell data for thresholding\n+ operations.\n+\n+ method : str, default: 'upper'\n+ Set the threshold method for single-values, defining which\n+ threshold bounds to use. If the ``value`` is a range, this\n+ parameter will be ignored, extracting data between the two\n+ values. For single values, ``'lower'`` will extract data\n+ lower than the ``value``. ``'upper'`` will extract data\n+ larger than the ``value``.\n \n- progress_bar : bool, optional\n+ progress_bar : bool, default: False\n Display a progress bar to indicate progress.\n \n Returns\n@@ -1239,6 +1241,7 @@ def _get_val(percent, dmin, dmax):\n invert=invert,\n continuous=continuous,\n preference=preference,\n+ method=method,\n progress_bar=progress_bar,\n )\n \n@@ -5482,20 +5485,58 @@ def separate_cells(self):\n return self.shrink(1.0)\n \n \n-def _set_threshold_limit(alg, value, invert):\n- \"\"\"Set vtkThreshold limit.\n+def _set_threshold_limit(alg, value, method, invert):\n+ \"\"\"Set vtkThreshold limits and function.\n+\n+ Addresses VTK API deprecations and previous PyVista inconsistencies with ParaView. Reference:\n \n- Addresses VTK API deprecation as pointed out in\n- https://github.com/pyvista/pyvista/issues/2850\n+ * https://github.com/pyvista/pyvista/issues/2850\n+ * https://github.com/pyvista/pyvista/issues/3610\n+ * https://discourse.vtk.org/t/unnecessary-vtk-api-change/9929\n \n \"\"\"\n- if invert:\n- if pyvista.vtk_version_info >= (9, 1):\n- alg.SetUpperThreshold(value)\n- else: # pragma: no cover\n- alg.ThresholdByLower(value)\n- else:\n- if pyvista.vtk_version_info >= (9, 1):\n- alg.SetLowerThreshold(value)\n- else: # pragma: no cover\n- alg.ThresholdByUpper(value)\n+ # Check value\n+ if isinstance(value, (np.ndarray, collections.abc.Sequence)):\n+ if len(value) != 2:\n+ raise ValueError(\n+ f'Value range must be length one for a float value or two for min/max; not ({value}).'\n+ )\n+ # Check range\n+ if value[0] > value[1]:\n+ raise ValueError(\n+ 'Value sequence is invalid, please use (min, max). The provided first value is greater than the second.'\n+ )\n+ elif isinstance(value, collections.abc.Iterable):\n+ raise TypeError('Value must either be a single scalar or a sequence.')\n+ if pyvista.vtk_version_info >= (9,):\n+ alg.SetInvert(invert)\n+ elif invert: # pragma: no cover\n+ raise ValueError('PyVista no longer supports inverted thresholds for VTK<9.')\n+ # Set values and function\n+ if pyvista.vtk_version_info >= (9, 1):\n+ if isinstance(value, (np.ndarray, collections.abc.Sequence)):\n+ alg.SetThresholdFunction(_vtk.vtkThreshold.THRESHOLD_BETWEEN)\n+ alg.SetLowerThreshold(value[0])\n+ alg.SetUpperThreshold(value[1])\n+ else:\n+ # Single value\n+ if method.lower() == 'lower':\n+ alg.SetLowerThreshold(value)\n+ alg.SetThresholdFunction(_vtk.vtkThreshold.THRESHOLD_LOWER)\n+ elif method.lower() == 'upper':\n+ alg.SetUpperThreshold(value)\n+ alg.SetThresholdFunction(_vtk.vtkThreshold.THRESHOLD_UPPER)\n+ else:\n+ raise ValueError('Invalid method choice. Either `lower` or `upper`')\n+ else: # pragma: no cover\n+ # ThresholdByLower, ThresholdByUpper, ThresholdBetween\n+ if isinstance(value, (np.ndarray, collections.abc.Sequence)):\n+ alg.ThresholdBetween(value[0], value[1])\n+ else:\n+ # Single value\n+ if method.lower() == 'lower':\n+ alg.ThresholdByLower(value)\n+ elif method.lower() == 'upper':\n+ alg.ThresholdByUpper(value)\n+ else:\n+ raise ValueError('Invalid method choice. Either `lower` or `upper`')\ndiff --git a/pyvista/plotting/widgets.py b/pyvista/plotting/widgets.py\n--- a/pyvista/plotting/widgets.py\n+++ b/pyvista/plotting/widgets.py\n@@ -1247,6 +1247,8 @@ def add_mesh_threshold(\n pointa=(0.4, 0.9),\n pointb=(0.9, 0.9),\n continuous=False,\n+ all_scalars=False,\n+ method='upper',\n **kwargs,\n ):\n \"\"\"Apply a threshold on a mesh with a slider.\n@@ -1265,8 +1267,13 @@ def add_mesh_threshold(\n scalars : str, optional\n The string name of the scalars on the mesh to threshold and display.\n \n- invert : bool, optional\n- Invert (flip) the threshold.\n+ invert : bool, default: False\n+ Invert the threshold results. That is, cells that would have been\n+ in the output with this option off are excluded, while cells that\n+ would have been excluded from the output are included.\n+\n+ .. warning::\n+ This option is only supported for VTK version 9+\n \n widget_color : color_like, optional\n Color of the widget. Either a string, RGB sequence, or\n@@ -1277,7 +1284,7 @@ def add_mesh_threshold(\n * ``color=[1.0, 1.0, 1.0]``\n * ``color='#FFFFFF'``\n \n- preference : str, optional\n+ preference : str, default: 'cell'\n When ``mesh.n_points == mesh.n_cells`` and setting\n scalars, this parameter sets how the scalars will be\n mapped to the mesh. Default ``'cell'``, causes the\n@@ -1287,20 +1294,35 @@ def add_mesh_threshold(\n title : str, optional\n The string label of the slider widget.\n \n- pointa : sequence, optional\n+ pointa : sequence, default: (0.4, 0.9)\n The relative coordinates of the left point of the slider\n on the display port.\n \n- pointb : sequence, optional\n+ pointb : sequence, default: (0.9, 0.9)\n The relative coordinates of the right point of the slider\n on the display port.\n \n- continuous : bool, optional\n+ continuous : bool, default: False\n If this is enabled (default is ``False``), use the continuous\n interval ``[minimum cell scalar, maximum cell scalar]``\n to intersect the threshold bound, rather than the set of\n discrete scalar values from the vertices.\n \n+ all_scalars : bool, default: False\n+ If using scalars from point data, all\n+ points in a cell must satisfy the threshold when this\n+ value is ``True``. When ``False``, any point of the cell\n+ with a scalar value satisfying the threshold criterion\n+ will extract the cell. Has no effect when using cell data.\n+\n+ method : str, default: 'upper'\n+ Set the threshold method for single-values, defining which\n+ threshold bounds to use. If the ``value`` is a range, this\n+ parameter will be ignored, extracting data between the two\n+ values. For single values, ``'lower'`` will extract data\n+ lower than the ``value``. ``'upper'`` will extract data\n+ larger than the ``value``.\n+\n **kwargs : dict, optional\n All additional keyword arguments are passed to ``add_mesh`` to\n control how the mesh is displayed.\n@@ -1338,12 +1360,13 @@ def add_mesh_threshold(\n 0, 0, 0, field.value, scalars\n ) # args: (idx, port, connection, field, name)\n alg.SetUseContinuousCellRange(continuous)\n+ alg.SetAllScalars(all_scalars)\n \n threshold_mesh = pyvista.wrap(alg.GetOutput())\n self.threshold_meshes.append(threshold_mesh)\n \n def callback(value):\n- _set_threshold_limit(alg, value, invert)\n+ _set_threshold_limit(alg, value, method, invert)\n alg.Update()\n threshold_mesh.shallow_copy(alg.GetOutput())\n \n", "test_patch": "diff --git a/tests/plotting/test_widgets.py b/tests/plotting/test_widgets.py\n--- a/tests/plotting/test_widgets.py\n+++ b/tests/plotting/test_widgets.py\n@@ -150,10 +150,12 @@ def test_widget_slider(uniform):\n p.add_slider_widget(callback=func, rng=[0, 10], style=\"modern\", pass_widget=True)\n p.close()\n \n- p = pyvista.Plotter()\n- p.add_mesh_threshold(uniform, invert=True)\n- p.add_mesh(uniform.outline())\n- p.close()\n+ if pyvista.vtk_version_info >= (9,):\n+ # Invert not support for VTK8.1.2\n+ p = pyvista.Plotter()\n+ p.add_mesh_threshold(uniform, invert=True)\n+ p.add_mesh(uniform.outline())\n+ p.close()\n \n p = pyvista.Plotter()\n p.add_mesh_threshold(uniform, invert=False)\ndiff --git a/tests/test_filters.py b/tests/test_filters.py\n--- a/tests/test_filters.py\n+++ b/tests/test_filters.py\n@@ -348,9 +348,10 @@ def test_threshold(datasets):\n thresh = dataset.threshold([100, 500], invert=False, progress_bar=True)\n assert thresh is not None\n assert isinstance(thresh, pyvista.UnstructuredGrid)\n- thresh = dataset.threshold([100, 500], invert=True, progress_bar=True)\n- assert thresh is not None\n- assert isinstance(thresh, pyvista.UnstructuredGrid)\n+ if pyvista.vtk_version_info >= (9,):\n+ thresh = dataset.threshold([100, 500], invert=True, progress_bar=True)\n+ assert thresh is not None\n+ assert isinstance(thresh, pyvista.UnstructuredGrid)\n # allow Sequence but not Iterable\n with pytest.raises(TypeError):\n dataset.threshold({100, 500}, progress_bar=True)\n@@ -364,6 +365,16 @@ def test_threshold(datasets):\n with pytest.raises(ValueError):\n dataset.threshold([10, 100, 300], progress_bar=True)\n \n+ if pyvista.vtk_version_info < (9,):\n+ with pytest.raises(ValueError):\n+ dataset.threshold([100, 500], invert=True)\n+\n+ with pytest.raises(ValueError):\n+ dataset.threshold(100, method='between')\n+\n+ with pytest.raises(ValueError):\n+ dataset.threshold((2, 1))\n+\n \n def test_threshold_all_scalars():\n mesh = pyvista.Sphere()\n@@ -434,6 +445,8 @@ def test_threshold_percent(datasets):\n inverts = [False, True, False, True, False]\n # Only test data sets that have arrays\n for i, dataset in enumerate(datasets[0:3]):\n+ if inverts[i] and pyvista.vtk_version_info < (9,):\n+ continue\n thresh = dataset.threshold_percent(\n percent=percents[i], invert=inverts[i], progress_bar=True\n )\n@@ -450,6 +463,106 @@ def test_threshold_percent(datasets):\n dataset.threshold_percent({18.0, 85.0})\n \n \[email protected](\n+ pyvista.vtk_version_info < (9,),\n+ reason='The invert parameter is not supported for VTK<9. The general logic for the API differences is tested for VTK<9.1 though.',\n+)\n+def test_threshold_paraview_consistency():\n+ \"\"\"Validate expected results that match ParaView.\"\"\"\n+ x = np.arange(5, dtype=float)\n+ y = np.arange(6, dtype=float)\n+ z = np.arange(2, dtype=float)\n+ xx, yy, zz = np.meshgrid(x, y, z)\n+ mesh = pyvista.StructuredGrid(xx, yy, zz)\n+ mesh.cell_data.set_scalars(np.repeat(range(5), 4))\n+\n+ # Input mesh\n+ # [[0, 0, 0, 0, 1],\n+ # [1, 1, 1, 2, 2],\n+ # [2, 2, 3, 3, 3],\n+ # [3, 4, 4, 4, 4]]\n+\n+ # upper(0): extract all\n+ thresh = mesh.threshold(0, invert=False, method='upper')\n+ assert thresh.n_cells == mesh.n_cells\n+ assert np.allclose(thresh.active_scalars, mesh.active_scalars)\n+ # upper(0),invert: extract none\n+ thresh = mesh.threshold(0, invert=True, method='upper')\n+ assert thresh.n_cells == 0\n+\n+ # lower(0)\n+ # [[0, 0, 0, 0 ]]\n+ thresh = mesh.threshold(0, invert=False, method='lower')\n+ assert thresh.n_cells == 4\n+ assert np.allclose(thresh.active_scalars, np.array([0, 0, 0, 0]))\n+ # lower(0),invert\n+ # [[ 1],\n+ # [1, 1, 1, 2, 2],\n+ # [2, 2, 3, 3, 3],\n+ # [3, 4, 4, 4, 4]]\n+ thresh = mesh.threshold(0, invert=True, method='lower')\n+ assert thresh.n_cells == 16\n+ assert thresh.get_data_range() == (1, 4)\n+\n+ # upper(2)\n+ # [[ 2, 2],\n+ # [2, 2, 3, 3, 3],\n+ # [3, 4, 4, 4, 4]]\n+ thresh = mesh.threshold(2, invert=False, method='upper')\n+ assert thresh.n_cells == 12\n+ assert thresh.get_data_range() == (2, 4)\n+ # upper(2),invert\n+ # [[0, 0, 0, 0, 1],\n+ # [1, 1, 1, ]]\n+ thresh = mesh.threshold(2, invert=True, method='upper')\n+ assert thresh.n_cells == 8\n+ assert thresh.get_data_range() == (0, 1)\n+\n+ # lower(2)\n+ # [[0, 0, 0, 0, 1],\n+ # [1, 1, 1, 2, 2],\n+ # [2, 2, ]]\n+ thresh = mesh.threshold(2, invert=False, method='lower')\n+ assert thresh.n_cells == 12\n+ assert thresh.get_data_range() == (0, 2)\n+ # lower(2),invert\n+ # [[ 3, 3, 3],\n+ # [3, 4, 4, 4, 4]]\n+ thresh = mesh.threshold(2, invert=True, method='lower')\n+ assert thresh.n_cells == 8\n+ assert thresh.get_data_range() == (3, 4)\n+\n+ # between(0, 0)\n+ # [[0, 0, 0, 0 ]]\n+ thresh = mesh.threshold((0, 0), invert=False)\n+ assert thresh.n_cells == 4\n+ assert np.allclose(thresh.active_scalars, np.array([0, 0, 0, 0]))\n+ # between(0,0),invert\n+ # [[ 1],\n+ # [1, 1, 1, 2, 2],\n+ # [2, 2, 3, 3, 3],\n+ # [3, 4, 4, 4, 4]]\n+ thresh = mesh.threshold((0, 0), invert=True)\n+ assert thresh.n_cells == 16\n+ assert thresh.get_data_range() == (1, 4)\n+\n+ # between(2,3)\n+ # [[ 2, 2],\n+ # [2, 2, 3, 3, 3],\n+ # [3, ]]\n+ thresh = mesh.threshold((2, 3), invert=False)\n+ assert thresh.n_cells == 8\n+ assert thresh.get_data_range() == (2, 3)\n+ # between(2,3),invert\n+ # [[0, 0, 0, 0, 1],\n+ # [1, 1, 1, ],\n+ # [ ],\n+ # [ 4, 4, 4, 4]]\n+ thresh = mesh.threshold((2, 3), invert=True)\n+ assert thresh.n_cells == 12\n+ assert thresh.get_data_range() == (0, 4)\n+\n+\n def test_outline(datasets):\n for dataset in datasets:\n outline = dataset.outline(progress_bar=True)\n@@ -911,6 +1024,10 @@ def test_glyph_orient_and_scale():\n assert glyph4.bounds[0] == geom.bounds[0] and glyph4.bounds[1] == geom.bounds[1]\n \n \[email protected](\n+ pyvista.vtk_version_info < (9,),\n+ reason='The invert parameter is not supported for VTK<9.',\n+)\n def test_split_and_connectivity():\n # Load a simple example mesh\n dataset = examples.load_uniform()\n", "problem_statement": "Unexpected threshold behavior\n### Describe the bug, what's wrong, and what you expected.\n\nI'm using simple structed grids of cells, and need to filter-out some \"nodata\" cells. To do this, I'm setting scalar values to the cell data, then using [threshold](https://docs.pyvista.org/api/core/_autosummary/pyvista.DataSetFilters.threshold.html) with the nodata value with `invert=True`. However, I'm getting confusing and inconsistent results compared to ParaView.\n\n### Steps to reproduce the bug.\n\n```python\r\nimport numpy as np\r\nimport pyvista\r\n\r\nx = np.arange(5, dtype=float)\r\ny = np.arange(6, dtype=float)\r\nz = np.arange(2, dtype=float)\r\nxx, yy, zz = np.meshgrid(x, y, z)\r\nmesh = pyvista.StructuredGrid(xx, yy, zz)\r\nmesh.cell_data.set_scalars(np.repeat(range(5), 4))\r\n\r\n# All data\r\nmesh.plot(show_edges=True)\r\n# output is normal\r\n\r\n# Filtering out nodata (zero) values\r\nmesh.threshold(0, invert=True).plot(show_edges=True)\r\n# output does not look normal, only 0-value cells are shown\r\n```\n\n### System Information\n\n```shell\n--------------------------------------------------------------------------------\r\n Date: Thu Nov 17 15:23:57 2022 New Zealand Daylight Time\r\n\r\n OS : Windows\r\n CPU(s) : 12\r\n Machine : AMD64\r\n Architecture : 64bit\r\n RAM : 31.7 GiB\r\n Environment : IPython\r\n GPU Vendor : NVIDIA Corporation\r\n GPU Renderer : NVIDIA RTX A4000/PCIe/SSE2\r\n GPU Version : 4.5.0 NVIDIA 472.39\r\n\r\n Python 3.9.13 | packaged by conda-forge | (main, May 27 2022, 16:50:36) [MSC\r\n v.1929 64 bit (AMD64)]\r\n\r\n pyvista : 0.37.0\r\n vtk : 9.1.0\r\n numpy : 1.22.3\r\n imageio : 2.22.0\r\n scooby : 0.7.0\r\n pooch : v1.6.0\r\n matplotlib : 3.6.2\r\n PyQt5 : 5.12.3\r\n IPython : 8.6.0\r\n colorcet : 3.0.1\r\n scipy : 1.8.0\r\n tqdm : 4.63.0\r\n meshio : 5.3.4\r\n--------------------------------------------------------------------------------\n```\n\n\n### Screenshots\n\nNormal looking whole grid:\r\n\r\n\r\nOdd-looking threshold attempt with pyvista, showing only 0-values:\r\n\r\n\r\nExpected result with ParaView theshold filter with upper/lower set to 0 and invert selected:\r\n\r\n\r\nApologies for any \"user error\", as I'm new to this package.\n", "hints_text": "Can confirm, and I am seeing quite a few inconsistent results with the threshold filter. So this is not a user error!\r\n\r\n For example `inverter=True/False` should produce two logical inverses for this mesh, but it doesn't:\r\n<img width=\"624\" alt=\"Screen Shot 2022-11-16 at 11 18 48 PM\" src=\"https://user-images.githubusercontent.com/22067021/202371190-7dcd64df-1882-4876-b4c3-43fe614913a6.png\">\r\n\r\n\r\nSecond, depending on if `value` is a single value `0` or a range `[0, 0]` yields completely different results from the PyVista filter (but not in ParaView):\r\n\r\n\r\n```py\r\np = pv.Plotter(notebook=0, shape=(1,2))\r\np.add_mesh(mesh.threshold(0, invert=False))\r\np.subplot(0,1)\r\np.add_mesh(mesh.threshold(0, invert=True))\r\np.link_views()\r\np.view_isometric()\r\np.show()\r\n```\r\n\r\n<img width=\"624\" alt=\"Screen Shot 2022-11-16 at 11 20 01 PM\" src=\"https://user-images.githubusercontent.com/22067021/202371391-393280c1-1091-4c61-82b2-e95e76b49327.png\">\r\n\r\n\r\nvs.\r\n\r\n```py\r\np = pv.Plotter(notebook=0, shape=(1,2))\r\np.add_mesh(mesh.threshold([0, 0], invert=False))\r\np.subplot(0,1)\r\np.add_mesh(mesh.threshold([0, 0], invert=True))\r\np.link_views()\r\np.view_isometric()\r\np.show()\r\n```\r\n\r\n<img width=\"624\" alt=\"Screen Shot 2022-11-16 at 11 20 34 PM\" src=\"https://user-images.githubusercontent.com/22067021/202371476-cfd0fabb-daad-47db-acc5-855b43504f21.png\">\r\n\r\n\r\nThis is not good... I'll start digging into this and see if I can fix the `threshold` filter such that I has consistency with itself and with ParaView\r\n\nThanks for taking a closer look. I should have mentioned that I get the same behavior on linux using a similar conda-forge setup.\r\n\r\nI've found that ranges like `[1, 1]` work as expected to filter on values == 1, but to filter on zero, it needs to span a very small range:\r\n```python\r\np = pv.Plotter(notebook=0, shape=(1,2))\r\np.add_mesh(mesh.threshold([-1e-30, 1e-30], invert=False))\r\np.subplot(0,1)\r\np.add_mesh(mesh.threshold([-1e-30, 1e-30], invert=True))\r\np.link_views()\r\np.view_isometric()\r\np.show()\r\n```\r\nwhich also logs this message three times:\r\n> 2022-11-17 22:30:30.021 ( 559.089s) [ 20F0C740] vtkThreshold.cxx:96 WARN| vtkThreshold::ThresholdBetween was deprecated for VTK 9.1 and will be removed in a future version.\r\n\nAnother solution is to use [`extract_cells`](https://docs.pyvista.org/api/core/_autosummary/pyvista.StructuredGrid.extract_cells.html):\r\n```python\r\nmesh.extract_cells(mesh.cell_data.active_scalars != 0).plot()\r\nmesh.extract_cells(mesh.cell_data.active_scalars != 1).plot()\r\n```", "created_at": "2022-12-25T02:44:32Z", "version": "0.38", "FAIL_TO_PASS": ["tests/test_filters.py::test_threshold", "tests/test_filters.py::test_threshold_paraview_consistency"], "PASS_TO_PASS": ["tests/test_filters.py::test_datasetfilters_init", "tests/test_filters.py::test_clip_filter", "tests/test_filters.py::test_clip_by_scalars_filter[False-False]", "tests/test_filters.py::test_clip_by_scalars_filter[False-True]", "tests/test_filters.py::test_clip_by_scalars_filter[True-False]", "tests/test_filters.py::test_clip_by_scalars_filter[True-True]", "tests/test_filters.py::test_clip_filter_no_active", "tests/test_filters.py::test_clip_filter_scalar_multiple", "tests/test_filters.py::test_clip_filter_composite", "tests/test_filters.py::test_clip_box", "tests/test_filters.py::test_clip_box_composite", "tests/test_filters.py::test_clip_surface", "tests/test_filters.py::test_clip_closed_surface", "tests/test_filters.py::test_implicit_distance", "tests/test_filters.py::test_slice_filter", "tests/test_filters.py::test_slice_filter_composite", "tests/test_filters.py::test_slice_orthogonal_filter", "tests/test_filters.py::test_slice_orthogonal_filter_composite", "tests/test_filters.py::test_slice_along_axis", "tests/test_filters.py::test_slice_along_axis_composite", "tests/test_filters.py::test_threshold_all_scalars", "tests/test_filters.py::test_threshold_multicomponent", "tests/test_filters.py::test_threshold_percent", "tests/test_filters.py::test_outline", "tests/test_filters.py::test_outline_composite", "tests/test_filters.py::test_outline_corners", "tests/test_filters.py::test_outline_corners_composite", "tests/test_filters.py::test_extract_geometry", "tests/test_filters.py::test_extract_geometry_extent", "tests/test_filters.py::test_extract_all_edges", "tests/test_filters.py::test_wireframe_composite", "tests/test_filters.py::test_delaunay_2d_unstructured", "tests/test_filters.py::test_contour[contour]", "tests/test_filters.py::test_contour[marching_cubes]", "tests/test_filters.py::test_contour[flying_edges]", "tests/test_filters.py::test_contour_errors", "tests/test_filters.py::test_elevation", "tests/test_filters.py::test_elevation_composite", "tests/test_filters.py::test_texture_map_to_plane", "tests/test_filters.py::test_texture_map_to_sphere", "tests/test_filters.py::test_compute_cell_sizes", "tests/test_filters.py::test_compute_cell_sizes_composite", "tests/test_filters.py::test_cell_centers", "tests/test_filters.py::test_cell_centers_composite", "tests/test_filters.py::test_glyph", "tests/test_filters.py::test_glyph_cell_point_data", "tests/test_filters.py::test_glyph_settings", "tests/test_filters.py::test_glyph_orient_and_scale", "tests/test_filters.py::test_split_and_connectivity", "tests/test_filters.py::test_warp_by_scalar", "tests/test_filters.py::test_warp_by_vector", "tests/test_filters.py::test_invalid_warp_scalar", "tests/test_filters.py::test_invalid_warp_scalar_inplace", "tests/test_filters.py::test_invalid_warp_vector", "tests/test_filters.py::test_cell_data_to_point_data", "tests/test_filters.py::test_cell_data_to_point_data_composite", "tests/test_filters.py::test_point_data_to_cell_data", "tests/test_filters.py::test_point_data_to_cell_data_composite", "tests/test_filters.py::test_triangulate", "tests/test_filters.py::test_triangulate_composite", "tests/test_filters.py::test_delaunay_3d", "tests/test_filters.py::test_smooth", "tests/test_filters.py::test_smooth_taubin", "tests/test_filters.py::test_resample", "tests/test_filters.py::test_probe[None-True-True]", "tests/test_filters.py::test_probe[None-True-False]", "tests/test_filters.py::test_probe[None-False-True]", "tests/test_filters.py::test_probe[None-False-False]", "tests/test_filters.py::test_probe[locator1-True-True]", "tests/test_filters.py::test_probe[locator1-True-False]", "tests/test_filters.py::test_probe[locator1-False-True]", "tests/test_filters.py::test_probe[locator1-False-False]", "tests/test_filters.py::test_streamlines_dir[forward]", "tests/test_filters.py::test_streamlines_dir[backward]", "tests/test_filters.py::test_streamlines_dir[both]", "tests/test_filters.py::test_streamlines_type[2]", "tests/test_filters.py::test_streamlines_type[4]", "tests/test_filters.py::test_streamlines_type[45]", "tests/test_filters.py::test_streamlines_cell_point[point]", "tests/test_filters.py::test_streamlines_cell_point[cell]", "tests/test_filters.py::test_streamlines_return_source", "tests/test_filters.py::test_streamlines_start_position", "tests/test_filters.py::test_streamlines_errors", "tests/test_filters.py::test_streamlines_from_source", "tests/test_filters.py::test_streamlines_from_source_structured_grids", "tests/test_filters.py::test_streamlines_evenly_spaced_2D", "tests/test_filters.py::test_streamlines_evenly_spaced_2D_sep_dist_ratio", "tests/test_filters.py::test_streamlines_evenly_spaced_2D_start_position", "tests/test_filters.py::test_streamlines_evenly_spaced_2D_vectors", "tests/test_filters.py::test_streamlines_evenly_spaced_2D_integrator_type", "tests/test_filters.py::test_streamlines_evenly_spaced_2D_interpolator_type", "tests/test_filters.py::test_streamlines_evenly_spaced_2D_errors", "tests/test_filters.py::test_sample_over_line", "tests/test_filters.py::test_plot_over_line", "tests/test_filters.py::test_sample_over_multiple_lines", "tests/test_filters.py::test_sample_over_circular_arc", "tests/test_filters.py::test_sample_over_circular_arc_normal", "tests/test_filters.py::test_plot_over_circular_arc", "tests/test_filters.py::test_plot_over_circular_arc_normal", "tests/test_filters.py::test_slice_along_line", "tests/test_filters.py::test_extract_points", "tests/test_filters.py::test_slice_along_line_composite", "tests/test_filters.py::test_interpolate", "tests/test_filters.py::test_select_enclosed_points", "tests/test_filters.py::test_decimate_boundary", "tests/test_filters.py::test_extract_surface", "tests/test_filters.py::test_merge_general", "tests/test_filters.py::test_iadd_general", "tests/test_filters.py::test_compute_cell_quality", "tests/test_filters.py::test_compute_derivatives", "tests/test_filters.py::test_extract_subset", "tests/test_filters.py::test_gaussian_smooth_output_type", "tests/test_filters.py::test_gaussian_smooth_constant_data", "tests/test_filters.py::test_gaussian_smooth_outlier", "tests/test_filters.py::test_gaussian_smooth_cell_data_specified", "tests/test_filters.py::test_gaussian_smooth_cell_data_active", "tests/test_filters.py::test_median_smooth_output_type", "tests/test_filters.py::test_median_smooth_constant_data", "tests/test_filters.py::test_median_smooth_outlier", "tests/test_filters.py::test_image_dilate_erode_output_type", "tests/test_filters.py::test_image_dilate_erode_dilation", "tests/test_filters.py::test_image_dilate_erode_erosion", "tests/test_filters.py::test_image_dilate_erode_cell_data_specified", "tests/test_filters.py::test_image_dilate_erode_cell_data_active", "tests/test_filters.py::test_image_threshold_output_type", "tests/test_filters.py::test_image_threshold_wrong_threshold_length", "tests/test_filters.py::test_image_threshold_wrong_threshold_type", "tests/test_filters.py::test_image_threshold_upper[0-1]", "tests/test_filters.py::test_image_threshold_upper[0-None]", "tests/test_filters.py::test_image_threshold_upper[None-1]", "tests/test_filters.py::test_image_threshold_upper[None-None]", "tests/test_filters.py::test_image_threshold_between[0-1]", "tests/test_filters.py::test_image_threshold_between[0-None]", "tests/test_filters.py::test_image_threshold_between[None-1]", "tests/test_filters.py::test_image_threshold_between[None-None]", "tests/test_filters.py::test_extract_subset_structured", "tests/test_filters.py::test_concatenate_structured", "tests/test_filters.py::test_concatenate_structured_bad_dimensions", "tests/test_filters.py::test_concatenate_structured_bad_inputs", "tests/test_filters.py::test_concatenate_structured_bad_point_data", "tests/test_filters.py::test_concatenate_structured_disconnected", "tests/test_filters.py::test_concatenate_structured_different_arrays", "tests/test_filters.py::test_structured_add_non_grid", "tests/test_filters.py::test_poly_data_strip", "tests/test_filters.py::test_shrink", "tests/test_filters.py::test_tessellate", "tests/test_filters.py::test_transform_mesh[0-0]", "tests/test_filters.py::test_transform_mesh[0-1]", "tests/test_filters.py::test_transform_mesh[0-2]", "tests/test_filters.py::test_transform_mesh[1-0]", "tests/test_filters.py::test_transform_mesh[1-1]", "tests/test_filters.py::test_transform_mesh[1-2]", "tests/test_filters.py::test_transform_mesh[2-0]", "tests/test_filters.py::test_transform_mesh[2-1]", "tests/test_filters.py::test_transform_mesh[2-2]", "tests/test_filters.py::test_transform_mesh_and_vectors[0-0]", "tests/test_filters.py::test_transform_mesh_and_vectors[0-1]", "tests/test_filters.py::test_transform_mesh_and_vectors[0-2]", "tests/test_filters.py::test_transform_mesh_and_vectors[1-0]", "tests/test_filters.py::test_transform_mesh_and_vectors[1-1]", "tests/test_filters.py::test_transform_mesh_and_vectors[1-2]", "tests/test_filters.py::test_transform_mesh_and_vectors[2-0]", "tests/test_filters.py::test_transform_mesh_and_vectors[2-1]", "tests/test_filters.py::test_transform_mesh_and_vectors[2-2]", "tests/test_filters.py::test_transform_int_vectors_warning[0-0]", "tests/test_filters.py::test_transform_int_vectors_warning[0-1]", "tests/test_filters.py::test_transform_int_vectors_warning[0-2]", "tests/test_filters.py::test_transform_int_vectors_warning[1-0]", "tests/test_filters.py::test_transform_int_vectors_warning[1-1]", "tests/test_filters.py::test_transform_int_vectors_warning[1-2]", "tests/test_filters.py::test_transform_int_vectors_warning[2-0]", "tests/test_filters.py::test_transform_int_vectors_warning[2-1]", "tests/test_filters.py::test_transform_int_vectors_warning[2-2]", "tests/test_filters.py::test_transform_inplace_bad_types[dataset0]", "tests/test_filters.py::test_transform_inplace_bad_types[dataset1]", "tests/test_filters.py::test_reflect_mesh_about_point", "tests/test_filters.py::test_reflect_mesh_with_vectors", "tests/test_filters.py::test_reflect_inplace[dataset0]", "tests/test_filters.py::test_reflect_inplace[dataset1]", "tests/test_filters.py::test_reflect_inplace[dataset2]", "tests/test_filters.py::test_transform_inplace_bad_types_2[dataset0]", "tests/test_filters.py::test_transform_inplace_bad_types_2[dataset1]", "tests/test_filters.py::test_extrude_rotate", "tests/test_filters.py::test_extrude_rotate_inplace", "tests/test_filters.py::test_extrude_trim", "tests/test_filters.py::test_extrude_trim_strategy[intersection-boundary_edges]", "tests/test_filters.py::test_extrude_trim_strategy[intersection-all_edges]", "tests/test_filters.py::test_extrude_trim_strategy[minimum_distance-boundary_edges]", "tests/test_filters.py::test_extrude_trim_strategy[minimum_distance-all_edges]", "tests/test_filters.py::test_extrude_trim_strategy[maximum_distance-boundary_edges]", "tests/test_filters.py::test_extrude_trim_strategy[maximum_distance-all_edges]", "tests/test_filters.py::test_extrude_trim_strategy[average_distance-boundary_edges]", "tests/test_filters.py::test_extrude_trim_strategy[average_distance-all_edges]", "tests/test_filters.py::test_extrude_trim_catch", "tests/test_filters.py::test_extrude_trim_inplace", "tests/test_filters.py::test_subdivide_adaptive[True]", "tests/test_filters.py::test_subdivide_adaptive[False]", "tests/test_filters.py::test_invalid_subdivide_adaptive", "tests/test_filters.py::test_collision", "tests/test_filters.py::test_collision_solid_non_triangle", "tests/test_filters.py::test_reconstruct_surface_poly", "tests/test_filters.py::test_is_manifold", "tests/test_filters.py::test_reconstruct_surface_unstructured", "tests/test_filters.py::test_integrate_data_datasets", "tests/test_filters.py::test_integrate_data", "tests/test_filters.py::test_subdivide_tetra"], "environment_setup_commit": "8dd8eeb80248cea4360c753847bd622e8652e059"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-3747", "base_commit": "0f800862380f60efb1841e5e0b116e945a3079a9", "patch": "diff --git a/pyvista/core/composite.py b/pyvista/core/composite.py\n--- a/pyvista/core/composite.py\n+++ b/pyvista/core/composite.py\n@@ -132,7 +132,7 @@ def wrap_nested(self):\n self.SetBlock(i, pyvista.wrap(block))\n \n @property\n- def bounds(self) -> List[float]:\n+ def bounds(self) -> Tuple[float, float, float, float, float, float]:\n \"\"\"Find min/max for bounds across blocks.\n \n Returns\n@@ -148,21 +148,23 @@ def bounds(self) -> List[float]:\n >>> data = [pv.Sphere(center=(2, 0, 0)), pv.Cube(center=(0, 2, 0)), pv.Cone()]\n >>> blocks = pv.MultiBlock(data)\n >>> blocks.bounds\n- [-0.5, 2.5, -0.5, 2.5, -0.5, 0.5]\n+ (-0.5, 2.5, -0.5, 2.5, -0.5, 0.5)\n \n \"\"\"\n # apply reduction of min and max over each block\n all_bounds = [block.bounds for block in self if block]\n # edge case where block has no bounds\n if not all_bounds: # pragma: no cover\n- minima = np.array([0, 0, 0])\n- maxima = np.array([0, 0, 0])\n+ minima = np.array([0.0, 0.0, 0.0])\n+ maxima = np.array([0.0, 0.0, 0.0])\n else:\n minima = np.minimum.reduce(all_bounds)[::2]\n maxima = np.maximum.reduce(all_bounds)[1::2]\n \n # interleave minima and maxima for bounds\n- return np.stack([minima, maxima]).ravel('F').tolist()\n+ the_bounds = np.stack([minima, maxima]).ravel('F')\n+\n+ return cast(Tuple[float, float, float, float, float, float], tuple(the_bounds))\n \n @property\n def center(self) -> Any:\ndiff --git a/pyvista/plotting/actor.py b/pyvista/plotting/actor.py\n--- a/pyvista/plotting/actor.py\n+++ b/pyvista/plotting/actor.py\n@@ -1,6 +1,6 @@\n \"\"\"Wrap vtkActor.\"\"\"\n \n-from typing import Optional, Union\n+from typing import Optional, Tuple, Union\n import weakref\n \n import numpy as np\n@@ -556,7 +556,7 @@ def user_matrix(self, value: Union[pv._vtk.vtkMatrix4x4, np.ndarray]):\n self.SetUserMatrix(value)\n \n @property\n- def bounds(self) -> tuple:\n+ def bounds(self) -> Tuple[float, float, float, float, float, float]:\n \"\"\"Return the bounds of the actor.\n \n Bounds are ``(-X, +X, -Y, +Y, -Z, +Z)``\ndiff --git a/pyvista/plotting/plotting.py b/pyvista/plotting/plotting.py\n--- a/pyvista/plotting/plotting.py\n+++ b/pyvista/plotting/plotting.py\n@@ -11,7 +11,7 @@\n import textwrap\n from threading import Thread\n import time\n-from typing import Dict\n+from typing import Dict, Tuple\n import warnings\n import weakref\n \n@@ -1388,7 +1388,7 @@ def camera_set(self, is_set):\n self.renderer.camera_set = is_set\n \n @property\n- def bounds(self):\n+ def bounds(self) -> Tuple[float, float, float, float, float, float]:\n \"\"\"Return the bounds of the active renderer.\n \n Returns\n@@ -1402,7 +1402,7 @@ def bounds(self):\n >>> pl = pyvista.Plotter()\n >>> _ = pl.add_mesh(pyvista.Cube())\n >>> pl.bounds\n- [-0.5, 0.5, -0.5, 0.5, -0.5, 0.5]\n+ (-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)\n \n \"\"\"\n return self.renderer.bounds\ndiff --git a/pyvista/plotting/renderer.py b/pyvista/plotting/renderer.py\n--- a/pyvista/plotting/renderer.py\n+++ b/pyvista/plotting/renderer.py\n@@ -2,7 +2,7 @@\n \n import collections.abc\n from functools import partial\n-from typing import Sequence\n+from typing import Sequence, Tuple, cast\n import warnings\n from weakref import proxy\n \n@@ -325,7 +325,7 @@ def camera(self, source):\n self.camera_set = True\n \n @property\n- def bounds(self):\n+ def bounds(self) -> Tuple[float, float, float, float, float, float]:\n \"\"\"Return the bounds of all actors present in the rendering window.\"\"\"\n the_bounds = np.array([np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf])\n \n@@ -354,7 +354,7 @@ def update_axis(ax):\n the_bounds[the_bounds == np.inf] = -1.0\n the_bounds[the_bounds == -np.inf] = 1.0\n \n- return the_bounds.tolist()\n+ return cast(Tuple[float, float, float, float, float, float], tuple(the_bounds))\n \n @property\n def length(self):\n", "test_patch": "diff --git a/tests/test_composite.py b/tests/test_composite.py\n--- a/tests/test_composite.py\n+++ b/tests/test_composite.py\n@@ -135,7 +135,7 @@ def test_multi_block_set_get_ers():\n for i in [0, 2, 3, 4, 5]:\n assert multi[i] is None\n # Check the bounds\n- assert multi.bounds == list(data.bounds)\n+ assert multi.bounds == data.bounds\n multi[5] = ex.load_uniform()\n multi.set_block_name(5, 'uni')\n multi.set_block_name(5, None) # Make sure it doesn't get overwritten\n", "problem_statement": "`bounds` property return type is mutable from `MultiBlock`\nThe `bounds` property has a different return type for meshes and `MultiBlock` objects:\r\n\r\n```\r\n>>> import pyvista as pv\r\n>>> slices = pv.Sphere().slice_orthogonal()\r\n# MultiBlock returns list (mutable)\r\n>>> slices.bounds\r\n[-0.49926671385765076, 0.49926671385765076, -0.4965316653251648, 0.4965316653251648, -0.5, 0.5]\r\n# Mesh returns tuple (immutable)\r\n>>> slices[0].bounds\r\n(-6.162975822039155e-33, 0.0, -0.4965316653251648, 0.4965316653251648, -0.5, 0.5)\r\n```\r\n\r\nIMO, the return value should be immutable and the `bounds` property should be cast to a tuple before returning.\n", "hints_text": "@banesullivan Possibly related to #3180 .", "created_at": "2022-12-24T21:01:09Z", "version": "0.38", "FAIL_TO_PASS": ["tests/test_composite.py::test_multi_block_set_get_ers"], "PASS_TO_PASS": ["tests/test_composite.py::test_multi_block_init_vtk", "tests/test_composite.py::test_multi_block_init_dict", "tests/test_composite.py::test_multi_block_keys", "tests/test_composite.py::test_multi_block_init_list", "tests/test_composite.py::test_multi_block_append", "tests/test_composite.py::test_replace", "tests/test_composite.py::test_pop", "tests/test_composite.py::test_del_slice", "tests/test_composite.py::test_slicing_multiple_in_setitem", "tests/test_composite.py::test_reverse", "tests/test_composite.py::test_insert", "tests/test_composite.py::test_extend", "tests/test_composite.py::test_multi_block_clean", "tests/test_composite.py::test_multi_block_repr", "tests/test_composite.py::test_multi_block_eq", "tests/test_composite.py::test_multi_block_io[True-.vtm-True]", "tests/test_composite.py::test_multi_block_io[True-.vtm-False]", "tests/test_composite.py::test_multi_block_io[True-.vtmb-True]", "tests/test_composite.py::test_multi_block_io[True-.vtmb-False]", "tests/test_composite.py::test_multi_block_io[False-.vtm-True]", "tests/test_composite.py::test_multi_block_io[False-.vtm-False]", "tests/test_composite.py::test_multi_block_io[False-.vtmb-True]", "tests/test_composite.py::test_multi_block_io[False-.vtmb-False]", "tests/test_composite.py::test_ensight_multi_block_io[vtm-True]", "tests/test_composite.py::test_ensight_multi_block_io[vtm-False]", "tests/test_composite.py::test_ensight_multi_block_io[vtmb-True]", "tests/test_composite.py::test_ensight_multi_block_io[vtmb-False]", "tests/test_composite.py::test_invalid_arg", "tests/test_composite.py::test_multi_io_erros", "tests/test_composite.py::test_extract_geometry", "tests/test_composite.py::test_combine_filter", "tests/test_composite.py::test_multi_block_copy", "tests/test_composite.py::test_multi_block_negative_index", "tests/test_composite.py::test_multi_slice_index", "tests/test_composite.py::test_slice_defaults", "tests/test_composite.py::test_slice_negatives", "tests/test_composite.py::test_multi_block_volume", "tests/test_composite.py::test_multi_block_length", "tests/test_composite.py::test_multi_block_save_lines", "tests/test_composite.py::test_multi_block_data_range", "tests/test_composite.py::test_multiblock_ref", "tests/test_composite.py::test_set_active_scalars", "tests/test_composite.py::test_set_active_scalars_multi", "tests/test_composite.py::test_set_active_scalars_components", "tests/test_composite.py::test_set_active_multi_multi", "tests/test_composite.py::test_set_active_scalars_mixed", "tests/test_composite.py::test_to_polydata", "tests/test_composite.py::test_compute_normals", "tests/test_composite.py::test_activate_plotting_scalars"], "environment_setup_commit": "8dd8eeb80248cea4360c753847bd622e8652e059"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4329", "base_commit": "b9ee9b9c0625d737dfd4a60e9ed10609e7e0b7fd", "patch": "diff --git a/pyvista/core/pointset.py b/pyvista/core/pointset.py\n--- a/pyvista/core/pointset.py\n+++ b/pyvista/core/pointset.py\n@@ -13,7 +13,7 @@\n import pyvista\n from pyvista import _vtk\n from pyvista.utilities import abstract_class\n-from pyvista.utilities.cells import CellArray, create_mixed_cells, get_mixed_cells\n+from pyvista.utilities.cells import CellArray, create_mixed_cells, get_mixed_cells, numpy_to_idarr\n \n from .._typing import BoundsLike\n from ..utilities.fileio import get_ext\n@@ -751,12 +751,32 @@ def lines(self, lines):\n \n @property\n def faces(self) -> np.ndarray:\n- \"\"\"Return a pointer to the faces as a numpy array.\n+ \"\"\"Return the connectivity array of the faces of this PolyData.\n+\n+ The faces array is organized as::\n+\n+ [n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ...]\n+\n+ where ``n0`` is the number of points in face 0, and ``pX_Y`` is the\n+ Y'th point in face X.\n+\n+ For example, a triangle and a quadrilateral might be represented as::\n+\n+ [3, 0, 1, 2, 4, 0, 1, 3, 4]\n+\n+ Where the two individual faces would be ``[3, 0, 1, 2]`` and ``[4, 0, 1, 3, 4]``.\n \n Returns\n -------\n numpy.ndarray\n- Array of face indices.\n+ Array of face connectivity.\n+\n+ Notes\n+ -----\n+ The array returned cannot be modified in place and will raise a\n+ ``ValueError`` if attempted.\n+\n+ You can, however, set the faces directly. See the example.\n \n Examples\n --------\n@@ -773,8 +793,21 @@ def faces(self) -> np.ndarray:\n [4, 1, 2, 5, 4],\n [4, 3, 4, 7, 6],\n [4, 4, 5, 8, 7]])\n+\n+ Set the faces directly. The following example creates a simple plane\n+ with a single square faces and modifies it to have two triangles\n+ instead.\n+\n+ >>> mesh = pv.Plane(i_resolution=1, j_resolution=1)\n+ >>> mesh.faces = [3, 0, 1, 2, 3, 3, 2, 1]\n+ >>> mesh.faces\n+ array([3, 0, 1, 2, 3, 3, 2, 1])\n+\n \"\"\"\n- return _vtk.vtk_to_numpy(self.GetPolys().GetData())\n+ array = _vtk.vtk_to_numpy(self.GetPolys().GetData())\n+ # Flag this array as read only to ensure users do not attempt to write to it.\n+ array.flags['WRITEABLE'] = False\n+ return array\n \n @faces.setter\n def faces(self, faces):\n@@ -1576,11 +1609,33 @@ def _check_for_consistency(self):\n \n @property\n def cells(self) -> np.ndarray:\n- \"\"\"Return a pointer to the cells as a numpy object.\n+ \"\"\"Return the cell data as a numpy object.\n+\n+ This is the old style VTK data layout::\n+\n+ [n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ...]\n+\n+ where ``n0`` is the number of points in cell 0, and ``pX_Y`` is the\n+ Y'th point in cell X.\n+\n+ For example, a triangle and a line might be represented as::\n+\n+ [3, 0, 1, 2, 2, 0, 1]\n+\n+ Where the two individual cells would be ``[3, 0, 1, 2]`` and ``[2, 0, 1]``.\n \n See Also\n --------\n pyvista.DataSet.get_cell\n+ pyvista.UnstructuredGrid.cell_connectivity\n+ pyvista.UnstructuredGrid.offset\n+\n+ Notes\n+ -----\n+ The array returned cannot be modified in place and will raise a\n+ ``ValueError`` if attempted.\n+\n+ You can, however, set the cells directly. See the example.\n \n Examples\n --------\n@@ -1590,13 +1645,25 @@ def cells(self) -> np.ndarray:\n \n >>> import pyvista\n >>> from pyvista import examples\n- >>> hex_beam = pyvista.read(examples.hexbeamfile)\n- >>> hex_beam.cells[:18] # doctest:+SKIP\n- array([ 8, 0, 2, 8, 7, 27, 36, 90, 81, 8, 2, 1, 4,\n- 8, 36, 18, 54, 90])\n+ >>> grid = examples.load_hexbeam()\n+ >>> grid.cells[:18]\n+ array([ 8, 0, 2, 8, 7, 27, 36, 90, 81, 8, 2, 1, 4, 8, 36, 18, 54,\n+ 90])\n+\n+ While you cannot change the array inplace, you can overwrite it. For example:\n+\n+ >>> grid.cells = [8, 0, 1, 2, 3, 4, 5, 6, 7]\n \n \"\"\"\n- return _vtk.vtk_to_numpy(self.GetCells().GetData())\n+ # Flag this array as read only to ensure users do not attempt to write to it.\n+ array = _vtk.vtk_to_numpy(self.GetCells().GetData())\n+ array.flags['WRITEABLE'] = False\n+ return array\n+\n+ @cells.setter\n+ def cells(self, cells):\n+ vtk_idarr = numpy_to_idarr(cells, deep=False, return_ind=False)\n+ self.GetCells().ImportLegacyFormat(vtk_idarr)\n \n @property\n def cells_dict(self) -> dict:\ndiff --git a/pyvista/demos/logo.py b/pyvista/demos/logo.py\n--- a/pyvista/demos/logo.py\n+++ b/pyvista/demos/logo.py\n@@ -148,7 +148,7 @@ def plot_logo(\n v_grid_atom = atomize(v_grid)\n v_grid_atom['scalars'] = v_grid_atom.points[:, 0]\n v_grid_atom_surf = v_grid_atom.extract_surface()\n- faces = v_grid_atom_surf.faces.reshape(-1, 5)\n+ faces = v_grid_atom_surf.faces.reshape(-1, 5).copy()\n faces[:, 1:] = faces[:, 1:][:, ::-1]\n v_grid_atom_surf.faces = faces\n plotter.add_mesh(\n", "test_patch": "diff --git a/tests/test_grid.py b/tests/test_grid.py\n--- a/tests/test_grid.py\n+++ b/tests/test_grid.py\n@@ -146,6 +146,14 @@ def test_init_from_arrays(specify_offset):\n assert np.allclose(cells, grid.cells)\n assert np.allclose(grid.cell_connectivity, np.arange(16))\n \n+ # grid.cells is not mutable\n+ assert not grid.cells.flags['WRITEABLE']\n+\n+ # but attribute can be set\n+ new_cells = [8, 0, 1, 2, 3, 4, 5, 6, 7]\n+ grid.cells = [8, 0, 1, 2, 3, 4, 5, 6, 7]\n+ assert np.allclose(grid.cells, new_cells)\n+\n \n @pytest.mark.parametrize('multiple_cell_types', [False, True])\n @pytest.mark.parametrize('flat_cells', [False, True])\ndiff --git a/tests/test_polydata.py b/tests/test_polydata.py\n--- a/tests/test_polydata.py\n+++ b/tests/test_polydata.py\n@@ -82,6 +82,15 @@ def test_init_from_arrays():\n with pytest.warns(Warning):\n mesh = pyvista.PolyData(vertices.astype(np.int32), faces)\n \n+ # array must be immutable\n+ with pytest.raises(ValueError):\n+ mesh.faces[0] += 1\n+\n+ # attribute is mutable\n+ faces = [4, 0, 1, 2, 3]\n+ mesh.faces = faces\n+ assert np.allclose(faces, mesh.faces)\n+\n \n def test_init_from_arrays_with_vert():\n vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0.5, 0.5, -1], [0, 1.5, 1.5]])\n", "problem_statement": "PolyData faces array is not updatable in-place and has unexpected behavior\n### Describe the bug, what's wrong, and what you expected.\n\nWhen accessing `PolyData.faces` (and likely other cell data), we cannot update the array in place. Further, there is some unexpected behavior where accessing `PolyData.faces` will override existing, modified views of the array.\n\n### Steps to reproduce the bug.\n\n```python \r\n>>> import pyvista as pv\r\n>>> mesh = pv.Sphere()\r\n>>> f = mesh.faces\r\n>>> f\r\narray([ 3, 2, 30, ..., 840, 29, 28])\r\n>>> a = f[1:4]\r\n>>> a\r\narray([ 2, 30, 0])\r\n>>> b = f[5:8]\r\n>>> b\r\narray([30, 58, 0])\r\n>>> f[1:4] = b\r\n>>> f[5:8] = a\r\n>>> f\r\narray([ 3, 30, 58, ..., 840, 29, 28])\r\n>>> assert all(f[1:4] == b) and all(f[5:8] == a)\r\n>>> mesh.faces # access overwrites `f` in place which is unexpected and causes the check above to now fail\r\n>>> assert all(f[1:4] == b) and all(f[5:8] == a)\r\n---------------------------------------------------------------------------\r\nAssertionError Traceback (most recent call last)\r\n<ipython-input-82-08205e08097f> in <cell line: 13>()\r\n 11 assert all(f[1:4] == b) and all(f[5:8] == a)\r\n 12 mesh.faces # access overwrites `f` in place\r\n---> 13 assert all(f[1:4] == b) and all(f[5:8] == a)\r\n\r\nAssertionError: \r\n ```\n\n### System Information\n\n```shell\n--------------------------------------------------------------------------------\r\n Date: Thu May 26 11:45:54 2022 MDT\r\n\r\n OS : Darwin\r\n CPU(s) : 16\r\n Machine : x86_64\r\n Architecture : 64bit\r\n RAM : 64.0 GiB\r\n Environment : Jupyter\r\n File system : apfs\r\n GPU Vendor : ATI Technologies Inc.\r\n GPU Renderer : AMD Radeon Pro 5500M OpenGL Engine\r\n GPU Version : 4.1 ATI-4.8.13\r\n\r\n Python 3.8.8 | packaged by conda-forge | (default, Feb 20 2021, 16:12:38)\r\n [Clang 11.0.1 ]\r\n\r\n pyvista : 0.35.dev0\r\n vtk : 9.1.0\r\n numpy : 1.22.1\r\n imageio : 2.9.0\r\n appdirs : 1.4.4\r\n scooby : 0.5.12\r\n matplotlib : 3.5.2\r\n IPython : 7.32.0\r\n colorcet : 3.0.0\r\n cmocean : 2.0\r\n ipyvtklink : 0.2.2\r\n scipy : 1.8.0\r\n itkwidgets : 0.32.1\r\n tqdm : 4.60.0\r\n meshio : 5.3.4\r\n--------------------------------------------------------------------------------\n```\n\n\n### Screenshots\n\n_No response_\n\n### Code of Conduct\n\n- [X] I agree to follow this project's Code of Conduct\n", "hints_text": "Considering we are purely using VTK for this interface through the `vtk_to_numpy` function, I'm inclined to think this may be an upstream bug where the array doesn't interface completely\r\n\r\nhttps://github.com/pyvista/pyvista/blob/eaa71a640264765c8a9b40d485b6ccdb970c87b0/pyvista/core/pointset.py#L762 \r\n\r\nor perhaps there is a better way to access the Polys from the VTK object?\nA pure VTK demonstration of the issue:\r\n\r\n```py\r\nimport vtk\r\nfrom vtkmodules.util.numpy_support import vtk_to_numpy\r\n\r\n# https://github.com/pyvista/pyvista/issues/2705\r\nsphere = vtk.vtkSphereSource()\r\nsphere.Update()\r\nmesh = sphere.GetOutput()\r\n\r\n\r\nf = vtk_to_numpy(mesh.GetPolys().GetData())\r\n\r\n>>> f\r\narray([ 3, 2, 30, ..., 840, 29, 28])\r\n>>> a = f[1:4]\r\n>>> a\r\narray([ 2, 30, 0])\r\n>>> b = f[5:8]\r\n>>> b\r\narray([30, 58, 0])\r\n>>> f[1:4] = b\r\n>>> f[5:8] = a\r\n>>> f\r\narray([ 3, 30, 58, ..., 840, 29, 28])\r\n\r\nassert all(f[1:4] == b) and all(f[5:8] == a), 'if this fails, we have more serious problems'\r\n\r\n# access overwrites `f` in place which is unexpected and causes the check above to now fail\r\nvtk_to_numpy(mesh.GetPolys().GetData())\r\nassert all(f[1:4] == b) and all(f[5:8] == a), 'well, this is not expected'\r\n```\nWell, this was a joy to track down. The short answer: Use `vtkCellArray.GetConnectivityArray()` instead of `vtkCellArray.GetData()`.\r\n\r\nThe long explanation: A while ago, `vtkCellArray` was changed so that it can store either 32 bit or 64 bit connectivity data. This enabled saving memory when VTK is compiled with 64 bit ids (`vtkIdType`) AND if the mesh has less than 2 billion connectivity entries. This meant that `vtkCellArray` can store either a 32 bit or 64 bit array for connectivity. However, `GetData()` returns a `vtkIdTypeArray` which is usually compiled to be 64 bit so `vtkCellArray` could no longer return its internal array in this method. So, the placeholder implementation now makes a copy from its internal array to return. So changing this array does not actually affect the connectivity. The issue shown here is a side effect of this implementation. `vtkCellArray.GetConnectivityArray()` actually returns the internal array and can be safely changed to affect the connectivity. pyvista and VTK Python classes have to be changed to use `vtkCellArray.GetConnectivityArray()` and `vtkCellArray.GetOffsetsArray()`. Also don't use `vtkCellArray.SetCells()`. Use `vtkCellArray.SetData()` instead.\nUnfortunately for PyVista, this is not an easy fix as `GetConnectivityArray()` is not a direct stand-in for `GetData()`. \r\n\r\n`GetData()` array has connectivity offsets (`GetOffsetsArray()`) embedded in the array, whereas `GetConnectivityArray()` does not. This is quite nice for `vtkPolyData.GetPolys()` if and only if all of the polys are the same size (e.g., 3 for triangulated mesh), but if there are mixed polys, this is pretty tough to work with when trying to update the array in-place:\r\n\r\n```py\r\nimport numpy as np\r\nimport pyvista as pv\r\nfrom pyvista import _vtk\r\n\r\nvertices = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0.5, 0.5, -1]])\r\n\r\n# mesh faces\r\nfaces = np.hstack(\r\n [\r\n [4, 0, 1, 2, 3], # square\r\n [3, 0, 1, 4], # triangle\r\n [3, 1, 2, 4], # triangle\r\n ]\r\n)\r\n\r\nsurf = pv.PolyData(vertices, faces)\r\n```\r\n\r\n```py\r\n>>> _vtk.vtk_to_numpy(surf.GetPolys().GetData())\r\narray([4, 0, 1, 2, 3, 3, 0, 1, 4, 3, 1, 2, 4])\r\n```\r\n\r\n```py\r\n>>> _vtk.vtk_to_numpy(surf.GetPolys().GetConnectivityArray())\r\narray([0, 1, 2, 3, 0, 1, 4, 1, 2, 4])\r\n```\r\n\r\n```py\r\n>>> _vtk.vtk_to_numpy(surf.GetPolys().GetOffsetsArray())\r\narray([ 0, 4, 7, 10])\r\n```\r\n\r\nIn PyVista, we designed the `.cells`, `.faces`, `.strips`, `.lines`, etc. APIs around the assumption of having the connectivity offsets embedded in the array. This means we'd have to redesign these accessors entirely (breaking a lot of downstream code) just to enable this in-place operation. Further, changing the API to require users to deal with both connectivities and offsets as separate arrays will likely be too much of a burden.\r\n\r\n------\r\n\r\n> the placeholder implementation now makes a copy from its internal array to return. So changing this array does not actually affect the connectivity.\r\n\r\n@berkgeveci, I'm curious if you think this copy could/will be fixed upstream in VTK so that `GetData()` could work with in-place operations?\nAh I see. Unfortunately, what you want is not possible. The underlying structure for `vtkCellArray` changed and it does not store the number of vertices per cell anymore. This is the main reason why `GetData()` creates a new array (something that I forgot). For backwards compatibility. But it has the side effect of this array being \"detached\" from the actual topology of the mesh. There are good reasons for this change:\r\n\r\n- Most other codes and OpenGL prefer the new structure so there is more likelihood that VTK will be binary compatible with them.\r\n- When we get rid of the vertex count and always have the offsets, we can have random access at no additional memory cost. In the past, for polydata, the offsets were built when needed to save memory.\r\n\r\nNote that there is no loss of information here. You can simply recover the number of vertices of a cell by doing `offset[cellId+1]-offset[cellId]`. To make this work, the offsets array actually is of size `ncells+1` so that you can get the number of vertices for the last cell.\r\n\r\nI understand that this will be a backwards incompatible change for PyVista but there is no other way. You can still support\r\n\r\n```\r\n# mesh faces\r\nfaces = np.hstack(\r\n [\r\n [4, 0, 1, 2, 3], # square\r\n [3, 0, 1, 4], # triangle\r\n [3, 1, 2, 4], # triangle\r\n ]\r\n)\r\n\r\nsurf = pv.PolyData(vertices, faces)\r\n```\r\n\r\nbut it will have to create the connectivity and offsets array under the covers (or let VTK do it). But if you want to avoid the deep copy, you have to support `pv.PolyData(vertices, offsets, connectivity)`, which has to create a `vtkCellArray` and call `SetData()` on it.\r\nI suggest avoiding the use of `GetData()` all together.\r\n\r\nAlso note that there is a bug in how `SetData()` works currently and when called from Python, it does not cause `vtkCellArray()` to hold a reference to the underlying numpy buffer. Unless you are keeping a reference to that object from the Python side, the VTK object will hold a reference to a junk pointer once the numpy array goes out of scope. I am working on a fix for this issue.\r\n", "created_at": "2023-04-24T18:15:27Z", "version": "0.39", "FAIL_TO_PASS": ["tests/test_grid.py::test_init_from_arrays[False]", "tests/test_grid.py::test_init_from_arrays[True]", "tests/test_polydata.py::test_init_from_arrays"], "PASS_TO_PASS": ["tests/test_grid.py::test_volume", "tests/test_grid.py::test_init_from_polydata", "tests/test_grid.py::test_init_from_structured", "tests/test_grid.py::test_init_from_unstructured", "tests/test_grid.py::test_init_from_numpy_arrays", "tests/test_grid.py::test_init_bad_input", "tests/test_grid.py::test_init_from_dict[False-False]", "tests/test_grid.py::test_init_from_dict[False-True]", "tests/test_grid.py::test_init_from_dict[True-False]", "tests/test_grid.py::test_init_from_dict[True-True]", "tests/test_grid.py::test_init_polyhedron", "tests/test_grid.py::test_cells_dict_hexbeam_file", "tests/test_grid.py::test_cells_dict_variable_length", "tests/test_grid.py::test_cells_dict_empty_grid", "tests/test_grid.py::test_cells_dict_alternating_cells", "tests/test_grid.py::test_destructor", "tests/test_grid.py::test_surface_indices", "tests/test_grid.py::test_extract_feature_edges", "tests/test_grid.py::test_triangulate_inplace", "tests/test_grid.py::test_save[.vtu-True]", "tests/test_grid.py::test_save[.vtu-False]", "tests/test_grid.py::test_save[.vtk-True]", "tests/test_grid.py::test_save[.vtk-False]", "tests/test_grid.py::test_pathlib_read_write", "tests/test_grid.py::test_init_bad_filename", "tests/test_grid.py::test_save_bad_extension", "tests/test_grid.py::test_linear_copy", "tests/test_grid.py::test_linear_copy_surf_elem", "tests/test_grid.py::test_extract_cells[True]", "tests/test_grid.py::test_extract_cells[False]", "tests/test_grid.py::test_merge", "tests/test_grid.py::test_merge_not_main", "tests/test_grid.py::test_merge_list", "tests/test_grid.py::test_merge_invalid", "tests/test_grid.py::test_init_structured_raise", "tests/test_grid.py::test_init_structured", "tests/test_grid.py::test_no_copy_polydata_init", "tests/test_grid.py::test_no_copy_polydata_points_setter", "tests/test_grid.py::test_no_copy_structured_mesh_init", "tests/test_grid.py::test_no_copy_structured_mesh_points_setter", "tests/test_grid.py::test_no_copy_pointset_init", "tests/test_grid.py::test_no_copy_pointset_points_setter", "tests/test_grid.py::test_no_copy_unstructured_grid_points_setter", "tests/test_grid.py::test_no_copy_rectilinear_grid", "tests/test_grid.py::test_grid_repr", "tests/test_grid.py::test_slice_structured", "tests/test_grid.py::test_invalid_init_structured", "tests/test_grid.py::test_save_structured[.vtk-True]", "tests/test_grid.py::test_save_structured[.vtk-False]", "tests/test_grid.py::test_save_structured[.vts-True]", "tests/test_grid.py::test_save_structured[.vts-False]", "tests/test_grid.py::test_load_structured_bad_filename", "tests/test_grid.py::test_instantiate_by_filename", "tests/test_grid.py::test_create_rectilinear_grid_from_specs", "tests/test_grid.py::test_create_rectilinear_after_init", "tests/test_grid.py::test_create_rectilinear_grid_from_file", "tests/test_grid.py::test_read_rectilinear_grid_from_file", "tests/test_grid.py::test_read_rectilinear_grid_from_pathlib", "tests/test_grid.py::test_raise_rectilinear_grid_non_unique", "tests/test_grid.py::test_cast_rectilinear_grid", "tests/test_grid.py::test_create_uniform_grid_from_specs", "tests/test_grid.py::test_uniform_grid_invald_args", "tests/test_grid.py::test_uniform_setters", "tests/test_grid.py::test_create_uniform_grid_from_file", "tests/test_grid.py::test_read_uniform_grid_from_file", "tests/test_grid.py::test_read_uniform_grid_from_pathlib", "tests/test_grid.py::test_cast_uniform_to_structured", "tests/test_grid.py::test_cast_uniform_to_rectilinear", "tests/test_grid.py::test_uniform_grid_to_tetrahedra", "tests/test_grid.py::test_fft_and_rfft", "tests/test_grid.py::test_fft_low_pass", "tests/test_grid.py::test_fft_high_pass", "tests/test_grid.py::test_save_rectilinear[.vtk-True]", "tests/test_grid.py::test_save_rectilinear[.vtk-False]", "tests/test_grid.py::test_save_rectilinear[.vtr-True]", "tests/test_grid.py::test_save_rectilinear[.vtr-False]", "tests/test_grid.py::test_save_uniform[.vtk-True]", "tests/test_grid.py::test_save_uniform[.vtk-False]", "tests/test_grid.py::test_save_uniform[.vti-True]", "tests/test_grid.py::test_save_uniform[.vti-False]", "tests/test_grid.py::test_grid_points", "tests/test_grid.py::test_grid_extract_selection_points", "tests/test_grid.py::test_gaussian_smooth", "tests/test_grid.py::test_remove_cells[ind0]", "tests/test_grid.py::test_remove_cells[ind1]", "tests/test_grid.py::test_remove_cells[ind2]", "tests/test_grid.py::test_remove_cells_not_inplace[ind0]", "tests/test_grid.py::test_remove_cells_not_inplace[ind1]", "tests/test_grid.py::test_remove_cells_not_inplace[ind2]", "tests/test_grid.py::test_remove_cells_invalid", "tests/test_grid.py::test_hide_cells[ind0]", "tests/test_grid.py::test_hide_cells[ind1]", "tests/test_grid.py::test_hide_cells[ind2]", "tests/test_grid.py::test_hide_points[ind0]", "tests/test_grid.py::test_hide_points[ind1]", "tests/test_grid.py::test_hide_points[ind2]", "tests/test_grid.py::test_set_extent", "tests/test_grid.py::test_UnstructuredGrid_cast_to_explicit_structured_grid", "tests/test_grid.py::test_ExplicitStructuredGrid_init", "tests/test_grid.py::test_ExplicitStructuredGrid_cast_to_unstructured_grid", "tests/test_grid.py::test_ExplicitStructuredGrid_save", "tests/test_grid.py::test_ExplicitStructuredGrid_hide_cells", "tests/test_grid.py::test_ExplicitStructuredGrid_show_cells", "tests/test_grid.py::test_ExplicitStructuredGrid_dimensions", "tests/test_grid.py::test_ExplicitStructuredGrid_visible_bounds", "tests/test_grid.py::test_ExplicitStructuredGrid_cell_id", "tests/test_grid.py::test_ExplicitStructuredGrid_cell_coords", "tests/test_grid.py::test_ExplicitStructuredGrid_neighbors", "tests/test_grid.py::test_ExplicitStructuredGrid_compute_connectivity", "tests/test_grid.py::test_ExplicitStructuredGrid_compute_connections", "tests/test_grid.py::test_ExplicitStructuredGrid_raise_init", "tests/test_grid.py::test_copy_no_copy_wrap_object", "tests/test_grid.py::test_copy_no_copy_wrap_object_vtk9", "tests/test_polydata.py::test_init", "tests/test_polydata.py::test_init_from_pdata", "tests/test_polydata.py::test_init_from_arrays_with_vert", "tests/test_polydata.py::test_init_from_arrays_triangular", "tests/test_polydata.py::test_init_as_points", "tests/test_polydata.py::test_init_as_points_from_list", "tests/test_polydata.py::test_invalid_init", "tests/test_polydata.py::test_invalid_file", "tests/test_polydata.py::test_lines_on_init", "tests/test_polydata.py::test_polydata_repr_str", "tests/test_polydata.py::test_geodesic", "tests/test_polydata.py::test_geodesic_fail", "tests/test_polydata.py::test_geodesic_distance", "tests/test_polydata.py::test_ray_trace", "tests/test_polydata.py::test_edge_mask", "tests/test_polydata.py::test_boolean_union_intersection", "tests/test_polydata.py::test_boolean_difference", "tests/test_polydata.py::test_boolean_difference_fail", "tests/test_polydata.py::test_subtract", "tests/test_polydata.py::test_merge", "tests/test_polydata.py::test_add", "tests/test_polydata.py::test_intersection", "tests/test_polydata.py::test_curvature[mean]", "tests/test_polydata.py::test_curvature[gaussian]", "tests/test_polydata.py::test_curvature[maximum]", "tests/test_polydata.py::test_curvature[minimum]", "tests/test_polydata.py::test_invalid_curvature", "tests/test_polydata.py::test_save[.ply-True]", "tests/test_polydata.py::test_save[.ply-False]", "tests/test_polydata.py::test_save[.vtp-True]", "tests/test_polydata.py::test_save[.vtp-False]", "tests/test_polydata.py::test_save[.stl-True]", "tests/test_polydata.py::test_save[.stl-False]", "tests/test_polydata.py::test_save[.vtk-True]", "tests/test_polydata.py::test_save[.vtk-False]", "tests/test_polydata.py::test_save_ply_texture_array[3-True]", "tests/test_polydata.py::test_save_ply_texture_array[3-False]", "tests/test_polydata.py::test_save_ply_texture_array[4-True]", "tests/test_polydata.py::test_save_ply_texture_array[4-False]", "tests/test_polydata.py::test_save_ply_texture_array_catch[True]", "tests/test_polydata.py::test_save_ply_texture_array_catch[False]", "tests/test_polydata.py::test_pathlib_read_write", "tests/test_polydata.py::test_invalid_save", "tests/test_polydata.py::test_triangulate_filter", "tests/test_polydata.py::test_subdivision[butterfly]", "tests/test_polydata.py::test_subdivision[loop]", "tests/test_polydata.py::test_subdivision[linear]", "tests/test_polydata.py::test_invalid_subdivision", "tests/test_polydata.py::test_extract_feature_edges", "tests/test_polydata.py::test_extract_feature_edges_no_data", "tests/test_polydata.py::test_decimate", "tests/test_polydata.py::test_decimate_pro", "tests/test_polydata.py::test_compute_normals", "tests/test_polydata.py::test_compute_normals_inplace", "tests/test_polydata.py::test_compute_normals_split_vertices", "tests/test_polydata.py::test_point_normals", "tests/test_polydata.py::test_cell_normals", "tests/test_polydata.py::test_face_normals", "tests/test_polydata.py::test_clip_plane", "tests/test_polydata.py::test_extract_largest", "tests/test_polydata.py::test_clean", "tests/test_polydata.py::test_area", "tests/test_polydata.py::test_volume", "tests/test_polydata.py::test_remove_points_any", "tests/test_polydata.py::test_remove_points_all", "tests/test_polydata.py::test_remove_points_fail", "tests/test_polydata.py::test_vertice_cells_on_read", "tests/test_polydata.py::test_center_of_mass", "tests/test_polydata.py::test_project_points_to_plane", "tests/test_polydata.py::test_tube", "tests/test_polydata.py::test_smooth_inplace", "tests/test_polydata.py::test_delaunay_2d", "tests/test_polydata.py::test_lines", "tests/test_polydata.py::test_strips", "tests/test_polydata.py::test_ribbon_filter", "tests/test_polydata.py::test_is_all_triangles", "tests/test_polydata.py::test_extrude", "tests/test_polydata.py::test_extrude_capping_warnings", "tests/test_polydata.py::test_flip_normals", "tests/test_polydata.py::test_n_verts", "tests/test_polydata.py::test_n_lines", "tests/test_polydata.py::test_geodesic_disconnected"], "environment_setup_commit": "4c2d1aed10b1600d520271beba8579c71433e808"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4225", "base_commit": "18694fa1a4e95027a055a958fef61ffdc5dba4d7", "patch": "diff --git a/doc/source/conf.py b/doc/source/conf.py\n--- a/doc/source/conf.py\n+++ b/doc/source/conf.py\n@@ -209,6 +209,8 @@\n # Type alias\n r'\\.ColorLike$',\n r'\\.Chart$',\n+ # PointSet *args and **kwargs for wrapped parameters\n+ r'\\.PointSet(\\.|$)',\n # Mixin methods from collections.abc\n r'\\.MultiBlock\\.clear$',\n r'\\.MultiBlock\\.count$',\ndiff --git a/pyvista/core/errors.py b/pyvista/core/errors.py\n--- a/pyvista/core/errors.py\n+++ b/pyvista/core/errors.py\n@@ -46,3 +46,29 @@ def __init__(\n ):\n \"\"\"Empty init.\"\"\"\n RuntimeError.__init__(self, message)\n+\n+\n+class PointSetNotSupported(TypeError):\n+ \"\"\"Requested filter or property is not supported by the PointSet class.\"\"\"\n+\n+ def __init__(self, message='The requested operation is not supported for PointSets.'):\n+ \"\"\"Empty init.\"\"\"\n+ TypeError.__init__(self, message)\n+\n+\n+class PointSetCellOperationError(PointSetNotSupported):\n+ \"\"\"Requested filter or property is not supported by the PointSet class.\"\"\"\n+\n+ def __init__(self, message='Cell operations are not supported. PointSets contain no cells.'):\n+ \"\"\"Empty init.\"\"\"\n+ PointSetNotSupported.__init__(self, message)\n+\n+\n+class PointSetDimensionReductionError(PointSetNotSupported):\n+ \"\"\"Requested filter or property is not supported by the PointSet class.\"\"\"\n+\n+ def __init__(\n+ self, message='Slice and other dimension reducing filters are not supported on PointSets.'\n+ ):\n+ \"\"\"Empty init.\"\"\"\n+ PointSetNotSupported.__init__(self, message)\ndiff --git a/pyvista/core/pointset.py b/pyvista/core/pointset.py\n--- a/pyvista/core/pointset.py\n+++ b/pyvista/core/pointset.py\n@@ -19,7 +19,13 @@\n from ..utilities.fileio import get_ext\n from .celltype import CellType\n from .dataset import DataSet\n-from .errors import DeprecationError, VTKVersionError\n+from .errors import (\n+ DeprecationError,\n+ PointSetCellOperationError,\n+ PointSetDimensionReductionError,\n+ PointSetNotSupported,\n+ VTKVersionError,\n+)\n from .filters import PolyDataFilters, StructuredGridFilters, UnstructuredGridFilters, _get_output\n \n DEFAULT_INPLACE_WARNING = (\n@@ -323,6 +329,112 @@ def plot(self, *args, **kwargs):\n kwargs.setdefault('style', 'points')\n return pdata.plot(*args, **kwargs)\n \n+ @wraps(PolyDataFilters.threshold)\n+ def threshold(self, *args, **kwargs):\n+ \"\"\"Cast to PolyData and threshold.\n+\n+ Need this because cell-wise operations fail for PointSets.\n+ \"\"\"\n+ return self.cast_to_polydata(False).threshold(*args, **kwargs).cast_to_pointset()\n+\n+ @wraps(PolyDataFilters.threshold_percent)\n+ def threshold_percent(self, *args, **kwargs):\n+ \"\"\"Cast to PolyData and threshold.\n+\n+ Need this because cell-wise operations fail for PointSets.\n+ \"\"\"\n+ return self.cast_to_polydata(False).threshold_percent(*args, **kwargs).cast_to_pointset()\n+\n+ @wraps(PolyDataFilters.explode)\n+ def explode(self, *args, **kwargs):\n+ \"\"\"Cast to PolyData and explode.\n+\n+ The explode filter relies on cells.\n+\n+ \"\"\"\n+ return self.cast_to_polydata(False).explode(*args, **kwargs).cast_to_pointset()\n+\n+ @wraps(PolyDataFilters.delaunay_3d)\n+ def delaunay_3d(self, *args, **kwargs):\n+ \"\"\"Cast to PolyData and run delaunay_3d.\"\"\"\n+ return self.cast_to_polydata(False).delaunay_3d(*args, **kwargs)\n+\n+ @property\n+ def area(self) -> float:\n+ \"\"\"Return 0.0 since a PointSet has no area.\"\"\"\n+ return 0.0\n+\n+ @property\n+ def volume(self) -> float:\n+ \"\"\"Return 0.0 since a PointSet has no volume.\"\"\"\n+ return 0.0\n+\n+ def contour(self, *args, **kwargs):\n+ \"\"\"Raise dimension reducing operations are not supported.\"\"\"\n+ raise PointSetNotSupported(\n+ 'Contour and other dimension reducing filters are not supported on PointSets'\n+ )\n+\n+ def cell_data_to_point_data(self, *args, **kwargs):\n+ \"\"\"Raise PointSets do not have cells.\"\"\"\n+ raise PointSetNotSupported('PointSets contain no cells or cell data.')\n+\n+ def point_data_to_cell_data(self, *args, **kwargs):\n+ \"\"\"Raise PointSets do not have cells.\"\"\"\n+ raise PointSetNotSupported('PointSets contain no cells or cell data.')\n+\n+ def triangulate(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n+ def decimate_boundary(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n+ def find_cells_along_line(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n+ def tessellate(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n+ def slice(self, *args, **kwargs):\n+ \"\"\"Raise dimension reducing operations are not supported.\"\"\"\n+ raise PointSetDimensionReductionError\n+\n+ def slice_along_axis(self, *args, **kwargs):\n+ \"\"\"Raise dimension reducing operations are not supported.\"\"\"\n+ raise PointSetDimensionReductionError\n+\n+ def slice_along_line(self, *args, **kwargs):\n+ \"\"\"Raise dimension reducing operations are not supported.\"\"\"\n+ raise PointSetDimensionReductionError\n+\n+ def slice_implicit(self, *args, **kwargs):\n+ \"\"\"Raise dimension reducing operations are not supported.\"\"\"\n+ raise PointSetDimensionReductionError\n+\n+ def slice_orthogonal(self, *args, **kwargs):\n+ \"\"\"Raise dimension reducing operations are not supported.\"\"\"\n+ raise PointSetDimensionReductionError\n+\n+ def shrink(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n+ def separate_cells(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n+ def remove_cells(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n+ def point_is_inside_cell(self, *args, **kwargs):\n+ \"\"\"Raise cell operations are not supported.\"\"\"\n+ raise PointSetCellOperationError\n+\n \n class PolyData(_vtk.vtkPolyData, _PointSet, PolyDataFilters):\n \"\"\"Dataset consisting of surface geometry (e.g. vertices, lines, and polygons).\n", "test_patch": "diff --git a/tests/test_pointset.py b/tests/test_pointset.py\n--- a/tests/test_pointset.py\n+++ b/tests/test_pointset.py\n@@ -5,6 +5,11 @@\n import vtk\n \n import pyvista\n+from pyvista.core.errors import (\n+ PointSetCellOperationError,\n+ PointSetDimensionReductionError,\n+ PointSetNotSupported,\n+)\n \n # skip all tests if concrete pointset unavailable\n pytestmark = pytest.mark.skipif(\n@@ -19,6 +24,8 @@ def test_pointset_basic():\n assert pset.n_cells == 0\n assert 'PointSet' in str(pset)\n assert 'PointSet' in repr(pset)\n+ assert pset.area == 0\n+ assert pset.volume == 0\n \n \n def test_pointset_from_vtk():\n@@ -210,6 +217,84 @@ def test_flip_normal():\n )\n \n \n+def test_threshold(pointset):\n+ pointset['scalars'] = range(pointset.n_points)\n+ out = pointset.threshold(pointset.n_points // 2)\n+ assert isinstance(out, pyvista.PointSet)\n+ assert out.n_points == pointset.n_points // 2\n+\n+\n+def test_threshold_percent(pointset):\n+ pointset['scalars'] = range(pointset.n_points)\n+ out = pointset.threshold_percent(50)\n+ assert isinstance(out, pyvista.PointSet)\n+ assert out.n_points == pointset.n_points // 2\n+\n+\n+def test_explode(pointset):\n+ out = pointset.explode(1)\n+ assert isinstance(out, pyvista.PointSet)\n+ ori_xlen = pointset.bounds[1] - pointset.bounds[0]\n+ new_xlen = out.bounds[1] - out.bounds[0]\n+ assert np.isclose(2 * ori_xlen, new_xlen)\n+\n+\n+def test_delaunay_3d(pointset):\n+ out = pointset.delaunay_3d()\n+ assert isinstance(out, pyvista.UnstructuredGrid)\n+ assert out.n_cells > 10\n+\n+\n+def test_raise_unsupported(pointset):\n+ with pytest.raises(PointSetNotSupported):\n+ pointset.contour()\n+\n+ with pytest.raises(PointSetNotSupported):\n+ pointset.cell_data_to_point_data()\n+\n+ with pytest.raises(PointSetNotSupported):\n+ pointset.point_data_to_cell_data()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.triangulate()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.decimate_boundary()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.find_cells_along_line()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.tessellate()\n+\n+ with pytest.raises(PointSetDimensionReductionError):\n+ pointset.slice()\n+\n+ with pytest.raises(PointSetDimensionReductionError):\n+ pointset.slice_along_axis()\n+\n+ with pytest.raises(PointSetDimensionReductionError):\n+ pointset.slice_along_line()\n+\n+ with pytest.raises(PointSetDimensionReductionError):\n+ pointset.slice_implicit()\n+\n+ with pytest.raises(PointSetDimensionReductionError):\n+ pointset.slice_orthogonal()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.shrink()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.separate_cells()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.remove_cells()\n+\n+ with pytest.raises(PointSetCellOperationError):\n+ pointset.point_is_inside_cell()\n+\n+\n def test_rotate_x():\n np_points = np.array([1, 1, 1], dtype=float)\n pset = pyvista.PointSet(np_points)\n", "problem_statement": "Cell wise and dimension reducing filters do not work for PointSet\n### Describe the bug, what's wrong, and what you expected.\n\n`PointSet` is an odd data type as it has no cells and simply represents a 0-dimensional geometry: point clouds.\r\n\r\nThis means that two common types of operations are not possible on this data type:\r\n\r\n1. Cell-wise operations like thresholding\r\n2. Dimension-reducing operations like contouring\r\n\r\nCell wise operations can easily be fixed by adding cells. This can be done with `cast_to_polydata()`\r\n\r\nDimension-reducing operations, on the other hand, have no solution and should not be allowed on `PointSet`.\r\n\r\nHow can we properly error out or convert to `PolyData` when calling dataset filters like `threshold()` and `contour()`? Should these types of filters be overridden on the `PointSet` class?\n\n### Steps to reproduce the bug.\n\n### Cell wise operation produces *invalid* output\r\n\r\n```python\r\nimport pyvista as pv\r\nimport numpy as np\r\npc = pv.PointSet(np.random.random((100, 3)))\r\npc['foo'] = np.arange(pc.n_points)\r\npc.threshold()\r\n```\r\n\r\n<img width=\"575\" alt=\"Screen Shot 2023-01-11 at 5 47 02 PM 1\" src=\"https://user-images.githubusercontent.com/22067021/211949301-8d10e9ac-172e-4f27-ad81-c3ec2d335263.png\">\r\n\r\n\r\n### Dimension reducing operation produces *no* output\r\n\r\n```py\r\nimport pyvista as pv\r\nimport numpy as np\r\npc = pv.PointSet(np.random.random((100, 3)))\r\npc['foo'] = np.arange(pc.n_points)\r\npc.contour()\r\n```\r\n<img width=\"417\" alt=\"Screen Shot 2023-01-11 at 5 47 57 PM\" src=\"https://user-images.githubusercontent.com/22067021/211949430-a3e77292-6b1e-4d2d-b2e3-b2a640ed65fc.png\">\r\n\r\n\n\n### System Information\n\n```shell\nn/a\n```\n\n\n### Screenshots\n\nn/a\n", "hints_text": "", "created_at": "2023-04-03T23:24:53Z", "version": "0.39", "FAIL_TO_PASS": ["tests/test_pointset.py::test_pointset_basic", "tests/test_pointset.py::test_pointset_from_vtk", "tests/test_pointset.py::test_pointset_wrap", "tests/test_pointset.py::test_pointset", "tests/test_pointset.py::test_save", "tests/test_pointset.py::test_cast_to_polydata[True]", "tests/test_pointset.py::test_cast_to_polydata[False]", "tests/test_pointset.py::test_filters_return_pointset", "tests/test_pointset.py::test_pointset_force_float[False-int64]", "tests/test_pointset.py::test_pointset_force_float[True-float32]", "tests/test_pointset.py::test_center_of_mass", "tests/test_pointset.py::test_points_to_double", "tests/test_pointset.py::test_translate", "tests/test_pointset.py::test_scale", "tests/test_pointset.py::test_flip_x", "tests/test_pointset.py::test_flip_y", "tests/test_pointset.py::test_flip_z", "tests/test_pointset.py::test_flip_normal", "tests/test_pointset.py::test_threshold", "tests/test_pointset.py::test_threshold_percent", "tests/test_pointset.py::test_explode", "tests/test_pointset.py::test_delaunay_3d", "tests/test_pointset.py::test_raise_unsupported", "tests/test_pointset.py::test_rotate_x", "tests/test_pointset.py::test_rotate_y", "tests/test_pointset.py::test_rotate_z", "tests/test_pointset.py::test_rotate_vector"], "PASS_TO_PASS": [], "environment_setup_commit": "4c2d1aed10b1600d520271beba8579c71433e808"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-432", "base_commit": "e1bac62d2f3df7bcba25d58ed5e83d89f9a6be98", "patch": "diff --git a/examples/01-filter/decimate.py b/examples/01-filter/decimate.py\n--- a/examples/01-filter/decimate.py\n+++ b/examples/01-filter/decimate.py\n@@ -13,10 +13,10 @@\n \n # Define a camera potion the shows this mesh properly\n cpos = [(0.4, -0.07, -0.31), (0.05, -0.13, -0.06), (-0.1, 1, 0.08)]\n-dargs = dict(cpos=cpos, show_edges=True, color=True)\n+dargs = dict(show_edges=True, color=True)\n \n # Preview the mesh\n-mesh.plot(**dargs)\n+mesh.plot(cpos=cpos, **dargs)\n \n ###############################################################################\n # Now let's define a target reduction and compare the\n@@ -28,13 +28,13 @@\n ###############################################################################\n decimated = mesh.decimate(target_reduction)\n \n-decimated.plot(**dargs)\n+decimated.plot(cpos=cpos, **dargs)\n \n \n ###############################################################################\n pro_decimated = mesh.decimate_pro(target_reduction, preserve_topology=True)\n \n-pro_decimated.plot(**dargs)\n+pro_decimated.plot(cpos=cpos, **dargs)\n \n \n ###############################################################################\ndiff --git a/examples/01-filter/streamlines.py b/examples/01-filter/streamlines.py\n--- a/examples/01-filter/streamlines.py\n+++ b/examples/01-filter/streamlines.py\n@@ -62,7 +62,7 @@\n boundary = mesh.decimate_boundary().wireframe()\n \n p = pv.Plotter()\n-p.add_mesh(streamlines.tube(radius=0.2), ligthing=False)\n+p.add_mesh(streamlines.tube(radius=0.2), lighting=False)\n p.add_mesh(src)\n p.add_mesh(boundary, color=\"grey\", opacity=0.25)\n p.camera_position = [(10, 9.5, -43), (87.0, 73.5, 123.0), (-0.5, -0.7, 0.5)]\ndiff --git a/pyvista/core/filters.py b/pyvista/core/filters.py\n--- a/pyvista/core/filters.py\n+++ b/pyvista/core/filters.py\n@@ -32,7 +32,8 @@\n \n import pyvista\n from pyvista.utilities import (CELL_DATA_FIELD, POINT_DATA_FIELD, NORMALS,\n- generate_plane, get_array, wrap)\n+ assert_empty_kwargs, generate_plane, get_array,\n+ wrap)\n \n \n def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalar=None,\n@@ -1031,14 +1032,13 @@ def warp_by_scalar(dataset, scalars=None, factor=1.0, normal=None,\n inplace : bool\n If True, the points of the give dataset will be updated.\n \"\"\"\n+ factor = kwargs.pop('scale_factor', factor)\n+ assert_empty_kwargs(**kwargs)\n if scalars is None:\n field, scalars = dataset.active_scalar_info\n arr, field = get_array(dataset, scalars, preference='point', info=True)\n if field != pyvista.POINT_DATA_FIELD:\n raise AssertionError('Dataset can only by warped by a point data array.')\n- scale_factor = kwargs.get('scale_factor', None)\n- if scale_factor is not None:\n- factor = scale_factor\n # Run the algorithm\n alg = vtk.vtkWarpScalar()\n alg.SetInputDataObject(dataset)\n@@ -2374,7 +2374,7 @@ def plot_curvature(poly_data, curv_type='mean', **kwargs):\n - Minimum\n \n **kwargs : optional\n- See help(pyvista.plot)\n+ See :func:`pyvista.plot`\n \n Returns\n -------\n@@ -2973,6 +2973,7 @@ def clean(poly_data, point_merging=True, tolerance=None, lines_to_points=True,\n \"\"\"\n if tolerance is None:\n tolerance = kwargs.pop('merge_tol', None)\n+ assert_empty_kwargs(**kwargs)\n clean = vtk.vtkCleanPolyData()\n clean.SetPointMerging(point_merging)\n clean.SetConvertLinesToPoints(lines_to_points)\n@@ -3133,14 +3134,26 @@ def ray_trace(poly_data, origin, end_point, first_point=False, plot=False,\n return intersection_points, intersection_cells\n \n \n- def plot_boundaries(poly_data, **kwargs):\n- \"\"\" Plots boundaries of a mesh \"\"\"\n+ def plot_boundaries(poly_data, edge_color=\"red\", **kwargs):\n+ \"\"\" Plots boundaries of a mesh\n+\n+ Parameters\n+ ----------\n+ edge_color : str, etc.\n+ The color of the edges when they are added to the plotter.\n+\n+ kwargs : optional\n+ All additional keyword arguments will be passed to\n+ :func:`pyvista.BasePlotter.add_mesh`\n+\n+ \"\"\"\n edges = DataSetFilters.extract_edges(poly_data)\n \n plotter = pyvista.Plotter(off_screen=kwargs.pop('off_screen', False),\n notebook=kwargs.pop('notebook', None))\n- plotter.add_mesh(edges, 'r', style='wireframe', legend='Edges')\n- plotter.add_mesh(poly_data, legend='Mesh', **kwargs)\n+ plotter.add_mesh(edges, color=edge_color, style='wireframe', label='Edges')\n+ plotter.add_mesh(poly_data, label='Mesh', **kwargs)\n+ plotter.add_legend()\n return plotter.show()\n \n \ndiff --git a/pyvista/core/objects.py b/pyvista/core/objects.py\n--- a/pyvista/core/objects.py\n+++ b/pyvista/core/objects.py\n@@ -5,8 +5,9 @@\n import vtk\n \n import pyvista\n-from pyvista.utilities import (ROW_DATA_FIELD, convert_array, get_array,\n- parse_field_choice, row_array, vtk_bit_array_to_char)\n+from pyvista.utilities import (ROW_DATA_FIELD, assert_empty_kwargs,\n+ convert_array, get_array, parse_field_choice,\n+ row_array, vtk_bit_array_to_char)\n \n from .common import DataObject, _ScalarsDict\n \n@@ -409,6 +410,8 @@ def adder(self, scalars, name, set_active=False, deep=True):\n class Texture(vtk.vtkTexture):\n \"\"\"A helper class for vtkTextures\"\"\"\n def __init__(self, *args, **kwargs):\n+ assert_empty_kwargs(**kwargs)\n+\n if len(args) == 1:\n if isinstance(args[0], vtk.vtkTexture):\n self._from_texture(args[0])\ndiff --git a/pyvista/plotting/helpers.py b/pyvista/plotting/helpers.py\n--- a/pyvista/plotting/helpers.py\n+++ b/pyvista/plotting/helpers.py\n@@ -74,6 +74,11 @@ def plot(var_item, off_screen=None, full_screen=False, screenshot=None,\n if notebook is None:\n notebook = scooby.in_ipykernel()\n \n+ eye_dome_lighting = kwargs.pop(\"edl\", eye_dome_lighting)\n+ show_grid = kwargs.pop('show_grid', False)\n+ height = kwargs.get('height', 400)\n+ auto_close = kwargs.get('auto_close', rcParams['auto_close'])\n+\n if notebook:\n off_screen = notebook\n plotter = Plotter(off_screen=off_screen, notebook=notebook)\n@@ -109,11 +114,10 @@ def plot(var_item, off_screen=None, full_screen=False, screenshot=None,\n if text:\n plotter.add_text(text)\n \n- if show_bounds or kwargs.get('show_grid', False):\n- if kwargs.get('show_grid', False):\n- plotter.show_grid()\n- else:\n- plotter.show_bounds()\n+ if show_grid:\n+ plotter.show_grid()\n+ elif show_bounds:\n+ plotter.show_bounds()\n \n if cpos is None:\n cpos = plotter.get_default_cam_pos()\n@@ -122,7 +126,6 @@ def plot(var_item, off_screen=None, full_screen=False, screenshot=None,\n else:\n plotter.camera_position = cpos\n \n- eye_dome_lighting = kwargs.pop(\"edl\", eye_dome_lighting)\n if eye_dome_lighting:\n plotter.enable_eye_dome_lighting()\n \n@@ -136,10 +139,10 @@ def plot(var_item, off_screen=None, full_screen=False, screenshot=None,\n screenshot=screenshot,\n return_img=return_img,\n use_panel=use_panel,\n- height=kwargs.get('height', 400))\n+ height=height)\n \n # close and return camera position and maybe image\n- if kwargs.get('auto_close', rcParams['auto_close']):\n+ if auto_close:\n plotter.close()\n \n # Result will be handled by plotter.show(): cpos or [cpos, img]\ndiff --git a/pyvista/plotting/plotting.py b/pyvista/plotting/plotting.py\n--- a/pyvista/plotting/plotting.py\n+++ b/pyvista/plotting/plotting.py\n@@ -15,8 +15,9 @@\n import warnings\n \n import pyvista\n-from pyvista.utilities import (convert_array, convert_string_array,\n- get_array, is_pyvista_dataset, numpy_to_texture,\n+from pyvista.utilities import (assert_empty_kwargs, convert_array,\n+ convert_string_array, get_array,\n+ is_pyvista_dataset, numpy_to_texture,\n raise_not_matching, try_callback, wrap)\n \n from .colors import get_cmap_safe\n@@ -580,7 +581,7 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n specular_power=100.0, nan_color=None, nan_opacity=1.0,\n loc=None, culling=None, rgb=False, categories=False,\n use_transparency=False, below_color=None, above_color=None,\n- annotations=None, pickable=True, **kwargs):\n+ annotations=None, pickable=True, preference=\"point\", **kwargs):\n \"\"\"\n Adds any PyVista/VTK mesh or dataset that PyVista can wrap to the\n scene. This method using a mesh representation to view the surfaces\n@@ -804,8 +805,10 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n if lighting is None:\n lighting = rcParams['lighting']\n \n- if clim is None:\n- clim = kwargs.get('rng', None)\n+ # supported aliases\n+ clim = kwargs.pop('rng', clim)\n+ cmap = kwargs.pop('colormap', cmap)\n+ culling = kwargs.pop(\"backface_culling\", culling)\n \n if render_points_as_spheres is None:\n render_points_as_spheres = rcParams['render_points_as_spheres']\n@@ -815,18 +818,22 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n \n if nan_color is None:\n nan_color = rcParams['nan_color']\n- nanr, nanb, nang = parse_color(nan_color)\n- nan_color = nanr, nanb, nang, nan_opacity\n+ nan_color = list(parse_color(nan_color))\n+ nan_color.append(nan_opacity)\n if color is True:\n color = rcParams['color']\n \n if texture is False:\n texture = None\n \n- if culling is None:\n- culling = kwargs.get(\"backface_culling\", False)\n- if culling is True:\n- culling = 'backface'\n+ if culling is True:\n+ culling = 'backface'\n+\n+ rgb = kwargs.pop('rgba', rgb)\n+\n+ if \"scalar\" in kwargs:\n+ raise TypeError(\"`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?\")\n+ assert_empty_kwargs(**kwargs)\n \n ##### Handle composite datasets #####\n \n@@ -846,9 +853,9 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n raise RuntimeError('Scalar array must be given as a string name for multiblock datasets.')\n \n the_arguments = locals()\n- the_arguments.update(kwargs)\n the_arguments.pop('self')\n the_arguments.pop('mesh')\n+ the_arguments.pop('kwargs')\n \n if multi_colors:\n # Compute unique colors for each index of the block\n@@ -965,7 +972,7 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n self.mapper.SetArrayName(scalars)\n original_scalar_name = scalars\n scalars = get_array(mesh, scalars,\n- preference=kwargs.get('preference', 'cell'), err=True)\n+ preference=preference, err=True)\n if stitle is None:\n stitle = original_scalar_name\n \n@@ -995,7 +1002,7 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n try:\n # Get array from mesh\n opacity = get_array(mesh, opacity,\n- preference=kwargs.get('preference', 'cell'), err=True)\n+ preference=preference, err=True)\n opacity = normalize(opacity)\n _custom_opac = True\n except:\n@@ -1018,8 +1025,6 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n opacity = 255 - opacity\n \n # Scalar formatting ===================================================\n- if cmap is None: # grab alias for cmaps: colormap\n- cmap = kwargs.get('colormap', None)\n if cmap is None: # Set default map if matplotlib is avaialble\n if has_matplotlib:\n cmap = rcParams['cmap']\n@@ -1049,8 +1054,6 @@ def add_mesh(self, mesh, color=None, style=None, scalars=None,\n scalar_bar_args.setdefault('n_labels', 0)\n _using_labels = True\n \n- if rgb is False or rgb is None:\n- rgb = kwargs.get('rgba', False)\n if rgb:\n if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4:\n raise ValueError('RGB array must be n_points/n_cells by 3/4 in shape.')\n@@ -1229,7 +1232,7 @@ def add_volume(self, volume, scalars=None, clim=None, resolution=None,\n loc=None, culling=False, multi_colors=False,\n blending='composite', mapper='fixed_point',\n stitle=None, scalar_bar_args=None, show_scalar_bar=None,\n- annotations=None, pickable=True, **kwargs):\n+ annotations=None, pickable=True, preference=\"point\", **kwargs):\n \"\"\"\n Adds a volume, rendered using a fixed point ray cast mapper by default.\n \n@@ -1355,8 +1358,14 @@ def add_volume(self, volume, scalars=None, clim=None, resolution=None,\n if name is None:\n name = '{}({})'.format(type(volume).__name__, str(hex(id(volume))))\n \n- if clim is None:\n- clim = kwargs.get('rng', None)\n+ # Supported aliases\n+ clim = kwargs.pop('rng', clim)\n+ cmap = kwargs.pop('colormap', cmap)\n+ culling = kwargs.pop(\"backface_culling\", culling)\n+\n+ if \"scalar\" in kwargs:\n+ raise TypeError(\"`scalar` is an invalid keyword argument for `add_mesh`. Perhaps you mean `scalars` with an s?\")\n+ assert_empty_kwargs(**kwargs)\n \n if scalar_bar_args is None:\n scalar_bar_args = {}\n@@ -1364,10 +1373,8 @@ def add_volume(self, volume, scalars=None, clim=None, resolution=None,\n if show_scalar_bar is None:\n show_scalar_bar = rcParams['show_scalar_bar']\n \n- if culling is None:\n- culling = kwargs.get(\"backface_culling\", False)\n- if culling is True:\n- culling = 'backface'\n+ if culling is True:\n+ culling = 'backface'\n \n # Convert the VTK data object to a pyvista wrapped object if neccessary\n if not is_pyvista_dataset(volume):\n@@ -1416,7 +1423,7 @@ def add_volume(self, volume, scalars=None, clim=None, resolution=None,\n reset_camera=reset_camera, name=next_name,\n ambient=ambient, categories=categories, loc=loc,\n culling=culling, clim=clim,\n- mapper=mapper, pickable=pickable, **kwargs)\n+ mapper=mapper, pickable=pickable)\n \n actors.append(a)\n return actors\n@@ -1444,7 +1451,7 @@ def add_volume(self, volume, scalars=None, clim=None, resolution=None,\n if isinstance(scalars, str):\n title = scalars\n scalars = get_array(volume, scalars,\n- preference=kwargs.get('preference', 'point'), err=True)\n+ preference=preference, err=True)\n if stitle is None:\n stitle = title\n else:\n@@ -1512,11 +1519,9 @@ def add_volume(self, volume, scalars=None, clim=None, resolution=None,\n for val, anno in annotations.items():\n table.SetAnnotation(float(val), str(anno))\n \n- if cmap is None: # grab alias for cmaps: colormap\n- cmap = kwargs.get('colormap', None)\n- if cmap is None: # Set default map if matplotlib is avaialble\n- if has_matplotlib:\n- cmap = rcParams['cmap']\n+ if cmap is None: # Set default map if matplotlib is avaialble\n+ if has_matplotlib:\n+ cmap = rcParams['cmap']\n \n if cmap is not None:\n if not has_matplotlib:\n@@ -2971,7 +2976,7 @@ def add_point_labels(self, points, labels, italic=False, bold=True,\n name=None, shape_color='grey', shape='rounded_rect',\n fill_shape=True, margin=3, shape_opacity=1.0,\n pickable=False, render_points_as_spheres=False,\n- tolerance=0.001, **kwargs):\n+ tolerance=0.001):\n \"\"\"\n Creates a point actor with one label from list labels assigned to\n each point.\n@@ -3060,9 +3065,6 @@ def add_point_labels(self, points, labels, italic=False, bold=True,\n font_family = rcParams['font']['family']\n if font_size is None:\n font_size = rcParams['font']['size']\n- if point_color is None and text_color is None and kwargs.get('color', None) is not None:\n- point_color = kwargs.get('color', None)\n- text_color = kwargs.get('color', None)\n if point_color is None:\n point_color = rcParams['color']\n if text_color is None:\ndiff --git a/pyvista/plotting/qt_plotting.py b/pyvista/plotting/qt_plotting.py\n--- a/pyvista/plotting/qt_plotting.py\n+++ b/pyvista/plotting/qt_plotting.py\n@@ -311,7 +311,7 @@ def __init__(self, parent=None, title=None, shape=(1, 1), off_screen=None,\n border=None, border_color='k', border_width=2.0,\n multi_samples=None, line_smoothing=False,\n point_smoothing=False, polygon_smoothing=False,\n- splitting_position=None, **kwargs):\n+ splitting_position=None):\n \"\"\" Initialize Qt interactor \"\"\"\n if not has_pyqt:\n raise AssertionError('Requires PyQt5')\ndiff --git a/pyvista/plotting/widgets.py b/pyvista/plotting/widgets.py\n--- a/pyvista/plotting/widgets.py\n+++ b/pyvista/plotting/widgets.py\n@@ -13,7 +13,7 @@ class WidgetHelper(object):\n \n def add_box_widget(self, callback, bounds=None, factor=1.25,\n rotation_enabled=True, color=None, use_planes=False,\n- outline_translation=True, pass_widget=False, **kwargs):\n+ outline_translation=True, pass_widget=False):\n \"\"\"Add a box widget to the scene. This is useless without a callback\n function. You can pass a callable function that takes a single\n argument, the PolyData box output from this widget, and performs a\n@@ -174,7 +174,7 @@ def add_plane_widget(self, callback, normal='x', origin=None,\n assign_to_axis=None, tubing=False,\n outline_translation=False,\n origin_translation=True, implicit=True,\n- pass_widget=False, test_callback=True, **kwargs):\n+ pass_widget=False, test_callback=True):\n \"\"\"Add a plane widget to the scene. This is useless without a callback\n function. You can pass a callable function that takes two\n arguments, the normal and origin of the plane in that order output\n@@ -492,7 +492,7 @@ def add_mesh_slice_orthogonal(self, mesh, generate_triangles=False,\n \n def add_line_widget(self, callback, bounds=None, factor=1.25,\n resolution=100, color=None, use_vertices=False,\n- pass_widget=False, **kwargs):\n+ pass_widget=False):\n \"\"\"Add a line widget to the scene. This is useless without a callback\n function. You can pass a callable function that takes a single\n argument, the PolyData line output from this widget, and performs a\n@@ -825,7 +825,7 @@ def callback(value):\n def add_spline_widget(self, callback, bounds=None, factor=1.25,\n n_hanldes=5, resolution=25, color=\"yellow\",\n show_ribbon=False, ribbon_color=\"pink\",\n- ribbon_opacity=0.5, pass_widget=False, **kwargs):\n+ ribbon_opacity=0.5, pass_widget=False):\n \"\"\"Create and add a spline widget to the scene. Use the bounds\n argument to place this widget. Several \"handles\" are used to control a\n parametric function for building this spline. Click directly on the\ndiff --git a/pyvista/utilities/__init__.py b/pyvista/utilities/__init__.py\n--- a/pyvista/utilities/__init__.py\n+++ b/pyvista/utilities/__init__.py\n@@ -1,8 +1,8 @@\n-from .errors import (Observer, Report, send_errors_to_logging,\n- set_error_output_file)\n+from .errors import (Observer, Report, assert_empty_kwargs,\n+ send_errors_to_logging, set_error_output_file)\n from .features import *\n from .fileio import *\n from .geometric_objects import *\n from .parametric_objects import *\n from .sphinx_gallery import Scraper, _get_sg_image_scraper\n-from .utilities import *\n+from .helpers import *\ndiff --git a/pyvista/utilities/errors.py b/pyvista/utilities/errors.py\n--- a/pyvista/utilities/errors.py\n+++ b/pyvista/utilities/errors.py\n@@ -2,6 +2,7 @@\n import os\n import re\n import scooby\n+import sys\n \n import vtk\n \n@@ -125,3 +126,21 @@ def __init__(self, additional=None, ncol=3, text_width=80, sort=False):\n scooby.Report.__init__(self, additional=additional, core=core,\n optional=optional, ncol=ncol,\n text_width=text_width, sort=sort)\n+\n+\n+def assert_empty_kwargs(**kwargs):\n+ \"\"\"An internal helper to assert that all keyword arguments have been used.\n+ If any keyword arguments are passed, a ``TypeError`` is raised.\n+ \"\"\"\n+ n = len(kwargs)\n+ if n == 0:\n+ return True\n+ caller = sys._getframe(1).f_code.co_name\n+ keys = list(kwargs.keys())\n+ bad_arguments = \"[\" + (\"{}, \" * (n - 1) + \"{}\").format(*keys) + \"]\"\n+ if n == 1:\n+ grammar = \"is an invalid keyword argument\"\n+ else:\n+ grammar = \"are invalid keyword arguments\"\n+ message = \"{} {} for `{}`\".format(bad_arguments, grammar, caller)\n+ raise TypeError(message)\ndiff --git a/pyvista/utilities/geometric_objects.py b/pyvista/utilities/geometric_objects.py\n--- a/pyvista/utilities/geometric_objects.py\n+++ b/pyvista/utilities/geometric_objects.py\n@@ -17,6 +17,7 @@\n import vtk\n \n import pyvista\n+from pyvista.utilities import assert_empty_kwargs\n \n \n NORMALS = {\n@@ -51,7 +52,7 @@ def translate(surf, center=[0., 0., 0.], direction=[1., 0., 0.]):\n \n \n def Cylinder(center=(0.,0.,0.), direction=(1.,0.,0.), radius=0.5, height=1.0,\n- resolution=100, **kwargs):\n+ resolution=100, capping=True, **kwargs):\n \n \"\"\"\n Create the surface of a cylinder.\n@@ -91,7 +92,8 @@ def Cylinder(center=(0.,0.,0.), direction=(1.,0.,0.), radius=0.5, height=1.0,\n >>> cylinder.plot() # doctest:+SKIP\n \n \"\"\"\n- capping = kwargs.get('capping', kwargs.get('cap_ends', True))\n+ capping = kwargs.pop('cap_ends', capping)\n+ assert_empty_kwargs(**kwargs)\n cylinderSource = vtk.vtkCylinderSource()\n cylinderSource.SetRadius(radius)\n cylinderSource.SetHeight(height)\n@@ -528,12 +530,12 @@ def Text3D(string, depth=0.5):\n return pyvista.wrap(tri_filter.GetOutput())\n \n \n-def SuperToroid(**kwargs):\n+def SuperToroid(*args, **kwargs):\n \"\"\"DEPRECATED: use :func:`pyvista.ParametricSuperToroid`\"\"\"\n raise RuntimeError('use `pyvista.ParametricSuperToroid` instead')\n \n \n-def Ellipsoid(**kwargs):\n+def Ellipsoid(*args, **kwargs):\n \"\"\"DEPRECATED: use :func:`pyvista.ParametricEllipsoid`\"\"\"\n raise RuntimeError('use `pyvista.ParametricEllipsoid` instead')\n \ndiff --git a/pyvista/utilities/utilities.py b/pyvista/utilities/helpers.py\nsimilarity index 100%\nrename from pyvista/utilities/utilities.py\nrename to pyvista/utilities/helpers.py\ndiff --git a/pyvista/utilities/parametric_objects.py b/pyvista/utilities/parametric_objects.py\n--- a/pyvista/utilities/parametric_objects.py\n+++ b/pyvista/utilities/parametric_objects.py\n@@ -3,6 +3,7 @@\n import vtk\n \n import pyvista\n+from pyvista.utilities import assert_empty_kwargs\n \n from .geometric_objects import translate\n \n@@ -361,7 +362,15 @@ def ParametricEllipsoid(xradius=None, yradius=None, zradius=None,\n >>> mesh.plot(color='w', smooth_shading=True) # doctest:+SKIP\n \"\"\"\n parametric_function = vtk.vtkParametricEllipsoid()\n- parametric_keywords(parametric_function, **kwargs)\n+ parametric_keywords(parametric_function, min_u=kwargs.pop(\"min_u\", 0),\n+ max_u=kwargs.pop(\"max_u\", 2*pi),\n+ min_v=kwargs.pop(\"min_v\", 0.0),\n+ max_v=kwargs.pop(\"max_v\", 2*pi),\n+ join_u=kwargs.pop(\"join_u\", False),\n+ join_v=kwargs.pop(\"join_v\", False),\n+ twist_u=kwargs.pop(\"twist_u\", False),\n+ twist_v=kwargs.pop(\"twist_v\", False),\n+ clockwise=kwargs.pop(\"clockwise\", True),)\n \n if xradius is not None:\n parametric_function.SetXRadius(xradius)\n@@ -964,7 +973,7 @@ def ParametricTorus(ringradius=None, crosssectionradius=None, **kwargs):\n \n def parametric_keywords(parametric_function, min_u=0, max_u=2*pi,\n min_v=0.0, max_v=2*pi, join_u=False, join_v=False,\n- twist_u=False, twist_v=False, clockwise=True, **kwargs):\n+ twist_u=False, twist_v=False, clockwise=True):\n \"\"\"Applys keyword arguments to a parametric function.\n \n Parameters\n@@ -1013,7 +1022,7 @@ def parametric_keywords(parametric_function, min_u=0, max_u=2*pi,\n \n \n def surface_from_para(parametric_function, u_res=100, v_res=100,\n- w_res=100, **kwargs):\n+ w_res=100):\n \"\"\"Construct a mesh from a parametric function.\n \n Parameters\n", "test_patch": "diff --git a/tests/test_plotting.py b/tests/test_plotting.py\n--- a/tests/test_plotting.py\n+++ b/tests/test_plotting.py\n@@ -837,3 +837,21 @@ def test_fail_plot_table():\n with pytest.raises(TypeError):\n plotter = pyvista.Plotter(off_screen=OFF_SCREEN)\n plotter.add_mesh(table)\n+\n+\[email protected](NO_PLOTTING, reason=\"Requires system to support plotting\")\n+def test_bad_keyword_arguments():\n+ \"\"\"Make sure bad keyword arguments raise an error\"\"\"\n+ mesh = examples.load_uniform()\n+ with pytest.raises(TypeError):\n+ pyvista.plot(mesh, foo=5, off_screen=OFF_SCREEN)\n+ with pytest.raises(TypeError):\n+ pyvista.plot(mesh, scalar=mesh.active_scalar_name, off_screen=OFF_SCREEN)\n+ with pytest.raises(TypeError):\n+ plotter = pyvista.Plotter(off_screen=OFF_SCREEN)\n+ plotter.add_mesh(mesh, scalar=mesh.active_scalar_name)\n+ plotter.show()\n+ with pytest.raises(TypeError):\n+ plotter = pyvista.Plotter(off_screen=OFF_SCREEN)\n+ plotter.add_mesh(mesh, foo=\"bad\")\n+ plotter.show()\ndiff --git a/tests/test_utilities.py b/tests/test_utilities.py\n--- a/tests/test_utilities.py\n+++ b/tests/test_utilities.py\n@@ -6,8 +6,9 @@\n \n import pyvista\n from pyvista import examples as ex\n-from pyvista import utilities\n-from pyvista import fileio\n+from pyvista.utilities import helpers\n+from pyvista.utilities import fileio\n+from pyvista.utilities import errors\n \n # Only set this here just the once.\n pyvista.set_error_output_file(os.path.join(os.path.dirname(__file__), 'ERROR_OUTPUT.txt'))\n@@ -17,13 +18,13 @@ def test_createvectorpolydata_error():\n orig = np.random.random((3, 1))\n vec = np.random.random((3, 1))\n with pytest.raises(Exception):\n- utilities.vector_poly_data(orig, vec)\n+ helpers.vector_poly_data(orig, vec)\n \n \n def test_createvectorpolydata_1D():\n orig = np.random.random(3)\n vec = np.random.random(3)\n- vdata = utilities.vector_poly_data(orig, vec)\n+ vdata = helpers.vector_poly_data(orig, vec)\n assert np.any(vdata.points)\n assert np.any(vdata.point_arrays['vectors'])\n \n@@ -31,7 +32,7 @@ def test_createvectorpolydata_1D():\n def test_createvectorpolydata():\n orig = np.random.random((100, 3))\n vec = np.random.random((100, 3))\n- vdata = utilities.vector_poly_data(orig, vec)\n+ vdata = helpers.vector_poly_data(orig, vec)\n assert np.any(vdata.points)\n assert np.any(vdata.point_arrays['vectors'])\n \n@@ -72,12 +73,12 @@ def test_get_array():\n grid._add_point_array(oarr, 'other')\n farr = np.random.rand(grid.n_points * grid.n_cells)\n grid._add_field_array(farr, 'field_data')\n- assert np.allclose(carr, utilities.get_array(grid, 'test_data', preference='cell'))\n- assert np.allclose(parr, utilities.get_array(grid, 'test_data', preference='point'))\n- assert np.allclose(oarr, utilities.get_array(grid, 'other'))\n- assert utilities.get_array(grid, 'foo') is None\n- assert utilities.get_array(grid, 'test_data', preference='field') is None\n- assert np.allclose(farr, utilities.get_array(grid, 'field_data', preference='field'))\n+ assert np.allclose(carr, helpers.get_array(grid, 'test_data', preference='cell'))\n+ assert np.allclose(parr, helpers.get_array(grid, 'test_data', preference='point'))\n+ assert np.allclose(oarr, helpers.get_array(grid, 'other'))\n+ assert helpers.get_array(grid, 'foo') is None\n+ assert helpers.get_array(grid, 'test_data', preference='field') is None\n+ assert np.allclose(farr, helpers.get_array(grid, 'field_data', preference='field'))\n \n \n \n@@ -85,11 +86,11 @@ def test_get_array():\n def test_is_inside_bounds():\n data = ex.load_uniform()\n bnds = data.bounds\n- assert utilities.is_inside_bounds((0.5, 0.5, 0.5), bnds)\n- assert not utilities.is_inside_bounds((12, 5, 5), bnds)\n- assert not utilities.is_inside_bounds((5, 12, 5), bnds)\n- assert not utilities.is_inside_bounds((5, 5, 12), bnds)\n- assert not utilities.is_inside_bounds((12, 12, 12), bnds)\n+ assert helpers.is_inside_bounds((0.5, 0.5, 0.5), bnds)\n+ assert not helpers.is_inside_bounds((12, 5, 5), bnds)\n+ assert not helpers.is_inside_bounds((5, 12, 5), bnds)\n+ assert not helpers.is_inside_bounds((5, 5, 12), bnds)\n+ assert not helpers.is_inside_bounds((12, 12, 12), bnds)\n \n \n def test_get_sg_image_scraper():\n@@ -166,3 +167,13 @@ def test_transform_vectors_sph_to_cart():\n [uu[-1, -1], vv[-1, -1], ww[-1, -1]],\n [67.80403533828323, 360.8359915416445, -70000.0],\n )\n+\n+def test_assert_empty_kwargs():\n+ kwargs = {}\n+ assert errors.assert_empty_kwargs(**kwargs)\n+ with pytest.raises(TypeError):\n+ kwargs = {\"foo\":6}\n+ errors.assert_empty_kwargs(**kwargs)\n+ with pytest.raises(TypeError):\n+ kwargs = {\"foo\":6, \"goo\":\"bad\"}\n+ errors.assert_empty_kwargs(**kwargs)\n", "problem_statement": "Strictly enforce keyword arguments\nI see folks quite often forget the s in the `scalars` argument for the `BasePlotter.add_mesh()` method. We should allow `scalar` as an alias much like how we allow `rng` and `clim` for the colorbar range/limits\n", "hints_text": "I would disagree. 2 arguments:\r\n\r\n`There should be one-- and preferably only one --obvious way to do it.` as says https://www.python.org/dev/peps/pep-0020/\r\n\r\nit makes documentation harder.\nRaise an exception to tell the user to use `scalars` when `scalar` is used as a keyword arg. \nOkay, I'm convinced. \r\n\r\nWe may want to do some keyword refactoring and not just allow an endless dict of `**kwargs` to be passed to `add_mesh`. For example, you can pass all types of typos and not have an error thrown:\r\n\r\n```py\r\nimport pyvista as pv\r\np = pv.Plotter()\r\np.add_mesh(pv.Cube(), my_crazy_argument=\"foooooooo\")\r\np.show()\r\n```\r\n\r\nThere are several places in the API where this can happen that will need to be refactored \nWhat we could do is pop out the allowed aliases like `rng` and then raise an exception if the `kwargs` dict is not empty that might say something like:\r\n\r\n> \"[list of arguments still in the kwargs] are not valid keyword arguments.\"", "created_at": "2019-10-31T03:34:40Z", "version": "0.22", "FAIL_TO_PASS": ["tests/test_plotting.py::test_invalid_color", "tests/test_plotting.py::test_invalid_font", "tests/test_plotting.py::test_themes", "tests/test_utilities.py::test_createvectorpolydata_error", "tests/test_utilities.py::test_createvectorpolydata_1D", "tests/test_utilities.py::test_createvectorpolydata", "tests/test_utilities.py::test_read", "tests/test_utilities.py::test_is_inside_bounds", "tests/test_utilities.py::test_get_sg_image_scraper", "tests/test_utilities.py::test_report", "tests/test_utilities.py::test_grid_from_sph_coords", "tests/test_utilities.py::test_transform_vectors_sph_to_cart", "tests/test_utilities.py::test_assert_empty_kwargs"], "PASS_TO_PASS": [], "environment_setup_commit": "1affc211d8b93024fa3e163584f235975d3536ed"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-3710", "base_commit": "846f1834f7428acff9395ef4b8a3bd39b42c99e6", "patch": "diff --git a/pyvista/utilities/geometric_objects.py b/pyvista/utilities/geometric_objects.py\n--- a/pyvista/utilities/geometric_objects.py\n+++ b/pyvista/utilities/geometric_objects.py\n@@ -1282,15 +1282,22 @@ def Circle(radius=0.5, resolution=100):\n pyvista.PolyData\n Circle mesh.\n \n+ Notes\n+ -----\n+ .. versionchanged:: 0.38.0\n+ Prior to version 0.38, this method had incorrect results, producing\n+ inconsistent edge lengths and a duplicated point which is now fixed.\n+\n Examples\n --------\n >>> import pyvista\n >>> radius = 0.5\n >>> circle = pyvista.Circle(radius)\n >>> circle.plot(show_edges=True, line_width=5)\n+\n \"\"\"\n points = np.zeros((resolution, 3))\n- theta = np.linspace(0.0, 2.0 * np.pi, resolution)\n+ theta = np.linspace(0.0, 2.0 * np.pi, resolution, endpoint=False)\n points[:, 0] = radius * np.cos(theta)\n points[:, 1] = radius * np.sin(theta)\n cells = np.array([np.append(np.array([resolution]), np.arange(resolution))])\n", "test_patch": "diff --git a/tests/test_geometric_objects.py b/tests/test_geometric_objects.py\n--- a/tests/test_geometric_objects.py\n+++ b/tests/test_geometric_objects.py\n@@ -275,6 +275,11 @@ def test_circle():\n assert mesh.n_cells\n diameter = np.max(mesh.points[:, 0]) - np.min(mesh.points[:, 0])\n assert np.isclose(diameter, radius * 2.0, rtol=1e-3)\n+ line_lengths = np.linalg.norm(\n+ np.roll(mesh.points, shift=1, axis=0) - mesh.points,\n+ axis=1,\n+ )\n+ assert np.allclose(line_lengths[0], line_lengths)\n \n \n def test_ellipse():\n", "problem_statement": "circle creates creates one zero length edge\n### Describe the bug, what's wrong, and what you expected.\n\nI expected that:\r\n> circle = pv.Circle(radius, resolution=n)\r\n\r\n1. would create a circle with n points and edge. \r\nIt does yay :-) \r\n\r\n3. That each edge of the would have similar length.\r\nIt does _not_ :-(\r\n\r\nThe problems seems circle closed is doubly:\r\n- once by the coordinates (circle.points[:, 0] == approx(circle.points[:, -1])\r\n- and a second time by the face (circle.faces[0] == [n, 0, 1, 2, ... n-1])\r\n\r\n\r\n\r\n\n\n### Steps to reproduce the bug.\n\n```python\r\nimport pyvista as pv\r\n\r\ncircle = pv.Circle(radius=1, resolution=4) # lets make a low res circle\r\nprint(circle.faces) # out: array([4, 0, 1, 2, 3])\r\nprint(circle.n_points) # out: 4\r\n\r\n# the print outputs gives the expectation that circle.plot() will look like a square \r\ncircle.plot()\r\n```\r\n\r\n\r\n\r\n\n\n### System Information\n\n```shell\n--------------------------------------------------------------------------------\r\n Date: Mon Dec 12 13:55:16 2022 CET\r\n\r\n OS : Linux\r\n CPU(s) : 8\r\n Machine : x86_64\r\n Architecture : 64bit\r\n Environment : IPython\r\n GPU Details : error\r\n\r\n Python 3.10.4 (main, Mar 23 2022, 20:25:24) [GCC 11.3.0]\r\n\r\n pyvista : 0.36.1\r\n vtk : 9.1.0\r\n numpy : 1.23.5\r\n imageio : 2.22.4\r\n appdirs : 1.4.4\r\n scooby : 0.7.0\r\n matplotlib : 3.6.2\r\n pyvistaqt : 0.9.0\r\n PyQt5 : Version unknown\r\n IPython : 8.2.0\r\n scipy : 1.9.3\r\n--------------------------------------------------------------------------------\n```\n\n\n### Screenshots\n\n_No response_\n", "hints_text": "", "created_at": "2022-12-12T14:53:20Z", "version": "0.38", "FAIL_TO_PASS": ["tests/test_geometric_objects.py::test_circle"], "PASS_TO_PASS": ["tests/test_geometric_objects.py::test_cylinder", "tests/test_geometric_objects.py::test_cylinder_structured", "tests/test_geometric_objects.py::test_arrow[None]", "tests/test_geometric_objects.py::test_arrow[2.0]", "tests/test_geometric_objects.py::test_arrow[4]", "tests/test_geometric_objects.py::test_arrow[auto]", "tests/test_geometric_objects.py::test_arrow_raises_error", "tests/test_geometric_objects.py::test_sphere", "tests/test_geometric_objects.py::test_plane", "tests/test_geometric_objects.py::test_line", "tests/test_geometric_objects.py::test_multiple_lines", "tests/test_geometric_objects.py::test_tube", "tests/test_geometric_objects.py::test_cube", "tests/test_geometric_objects.py::test_cone", "tests/test_geometric_objects.py::test_box", "tests/test_geometric_objects.py::test_polygon", "tests/test_geometric_objects.py::test_disc", "tests/test_geometric_objects.py::test_superquadric", "tests/test_geometric_objects.py::test_text_3d", "tests/test_geometric_objects.py::test_wavelet", "tests/test_geometric_objects.py::test_circular_arc", "tests/test_geometric_objects.py::test_circular_arc_from_normal", "tests/test_geometric_objects.py::test_pyramid", "tests/test_geometric_objects.py::test_triangle", "tests/test_geometric_objects.py::test_rectangle", "tests/test_geometric_objects.py::test_ellipse", "tests/test_geometric_objects.py::test_platonic_solids[tetrahedron-0-4-4]", "tests/test_geometric_objects.py::test_platonic_solids[cube-1-8-6]", "tests/test_geometric_objects.py::test_platonic_solids[octahedron-2-6-8]", "tests/test_geometric_objects.py::test_platonic_solids[icosahedron-3-12-20]", "tests/test_geometric_objects.py::test_platonic_solids[dodecahedron-4-20-12]", "tests/test_geometric_objects.py::test_platonic_invalids", "tests/test_geometric_objects.py::test_tetrahedron", "tests/test_geometric_objects.py::test_octahedron", "tests/test_geometric_objects.py::test_dodecahedron", "tests/test_geometric_objects.py::test_icosahedron"], "environment_setup_commit": "8dd8eeb80248cea4360c753847bd622e8652e059"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-3675", "base_commit": "905044f26df65188c6c612695c3370fcc2d007f0", "patch": "diff --git a/pyvista/_vtk.py b/pyvista/_vtk.py\n--- a/pyvista/_vtk.py\n+++ b/pyvista/_vtk.py\n@@ -499,6 +499,7 @@\n vtkPointPicker,\n vtkPolyDataMapper,\n vtkPolyDataMapper2D,\n+ vtkProp3D,\n vtkPropAssembly,\n vtkProperty,\n vtkPropPicker,\ndiff --git a/pyvista/plotting/actor.py b/pyvista/plotting/actor.py\n--- a/pyvista/plotting/actor.py\n+++ b/pyvista/plotting/actor.py\n@@ -6,15 +6,16 @@\n import numpy as np\n \n import pyvista as pv\n+from pyvista import _vtk\n from pyvista.utilities.misc import no_new_attr\n \n-from .._typing import BoundsLike\n from ._property import Property\n from .mapper import _BaseMapper\n+from .prop3d import Prop3D\n \n \n @no_new_attr\n-class Actor(pv._vtk.vtkActor):\n+class Actor(Prop3D, _vtk.vtkActor):\n \"\"\"Wrap vtkActor.\n \n This class represents the geometry & properties in a rendered\n@@ -239,29 +240,6 @@ def visibility(self) -> bool:\n def visibility(self, value: bool):\n return self.SetVisibility(value)\n \n- @property\n- def scale(self) -> tuple:\n- \"\"\"Return or set actor scale.\n-\n- Examples\n- --------\n- Create an actor using the :class:`pyvista.Plotter` and then change the\n- scale of the actor.\n-\n- >>> import pyvista as pv\n- >>> pl = pv.Plotter()\n- >>> actor = pl.add_mesh(pv.Sphere())\n- >>> actor.scale = (2.0, 2.0, 2.0)\n- >>> actor.scale\n- (2.0, 2.0, 2.0)\n-\n- \"\"\"\n- return self.GetScale()\n-\n- @scale.setter\n- def scale(self, value: tuple):\n- return self.SetScale(value)\n-\n def plot(self, **kwargs):\n \"\"\"Plot just the actor.\n \n@@ -290,159 +268,6 @@ def plot(self, **kwargs):\n pl.add_actor(self)\n pl.show(**kwargs)\n \n- @property\n- def position(self):\n- \"\"\"Return or set the actor position.\n-\n- Examples\n- --------\n- Change the position of an actor. Note how this does not change the\n- position of the underlying dataset, just the relative location of the\n- actor in the :class:`pyvista.Plotter`.\n-\n- >>> import pyvista as pv\n- >>> mesh = pv.Sphere()\n- >>> pl = pv.Plotter()\n- >>> _ = pl.add_mesh(mesh, color='b')\n- >>> actor = pl.add_mesh(mesh, color='r')\n- >>> actor.position = (0, 0, 1) # shifts the red sphere up\n- >>> pl.show()\n-\n- \"\"\"\n- return self.GetPosition()\n-\n- @position.setter\n- def position(self, value: tuple):\n- self.SetPosition(value)\n-\n- def rotate_x(self, angle: float):\n- \"\"\"Rotate the actor about the x axis.\n-\n- Parameters\n- ----------\n- angle : float\n- Angle to rotate the actor about the x axis in degrees.\n-\n- Examples\n- --------\n- Rotate the actor about the x axis 45 degrees. Note how this does not\n- change the location of the underlying dataset.\n-\n- >>> import pyvista as pv\n- >>> mesh = pv.Cube()\n- >>> pl = pv.Plotter()\n- >>> _ = pl.add_mesh(mesh, color='b')\n- >>> actor = pl.add_mesh(\n- ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n- ... )\n- >>> actor.rotate_x(45)\n- >>> pl.show_axes()\n- >>> pl.show()\n-\n- \"\"\"\n- self.RotateX(angle)\n-\n- def rotate_y(self, angle: float):\n- \"\"\"Rotate the actor about the y axis.\n-\n- Parameters\n- ----------\n- angle : float\n- Angle to rotate the actor about the y axis in degrees.\n-\n- Examples\n- --------\n- Rotate the actor about the y axis 45 degrees. Note how this does not\n- change the location of the underlying dataset.\n-\n- >>> import pyvista as pv\n- >>> mesh = pv.Cube()\n- >>> pl = pv.Plotter()\n- >>> _ = pl.add_mesh(mesh, color='b')\n- >>> actor = pl.add_mesh(\n- ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n- ... )\n- >>> actor.rotate_y(45)\n- >>> pl.show_axes()\n- >>> pl.show()\n-\n- \"\"\"\n- self.RotateY(angle)\n-\n- def rotate_z(self, angle: float):\n- \"\"\"Rotate the actor about the z axis.\n-\n- Parameters\n- ----------\n- angle : float\n- Angle to rotate the actor about the z axis in degrees.\n-\n- Examples\n- --------\n- Rotate the actor about the Z axis 45 degrees. Note how this does not\n- change the location of the underlying dataset.\n-\n- >>> import pyvista as pv\n- >>> mesh = pv.Cube()\n- >>> pl = pv.Plotter()\n- >>> _ = pl.add_mesh(mesh, color='b')\n- >>> actor = pl.add_mesh(\n- ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n- ... )\n- >>> actor.rotate_z(45)\n- >>> pl.show_axes()\n- >>> pl.show()\n-\n- \"\"\"\n- self.RotateZ(angle)\n-\n- @property\n- def orientation(self) -> tuple:\n- \"\"\"Return or set the actor orientation.\n-\n- Orientation is defined as the rotation from the global axes in degrees\n- about the actor's x, y, and z axes.\n-\n- Examples\n- --------\n- Show that the orientation changes with rotation.\n-\n- >>> import pyvista as pv\n- >>> mesh = pv.Cube()\n- >>> pl = pv.Plotter()\n- >>> actor = pl.add_mesh(mesh)\n- >>> actor.rotate_x(90)\n- >>> actor.orientation # doctest:+SKIP\n- (90, 0, 0)\n-\n- Set the orientation directly.\n-\n- >>> actor.orientation = (0, 45, 45)\n- >>> actor.orientation # doctest:+SKIP\n- (0, 45, 45)\n-\n- Reorient just the actor and plot it. Note how the actor is rotated\n- about its own axes as defined by its position.\n-\n- >>> import pyvista as pv\n- >>> mesh = pv.Cube()\n- >>> pl = pv.Plotter()\n- >>> _ = pl.add_mesh(mesh, color='b')\n- >>> actor = pl.add_mesh(\n- ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n- ... )\n- >>> actor.position = (0, 0, 1)\n- >>> actor.orientation = (45, 0, 0)\n- >>> pl.show_axes()\n- >>> pl.show()\n-\n- \"\"\"\n- return self.GetOrientation()\n-\n- @orientation.setter\n- def orientation(self, value: tuple):\n- self.SetOrientation(value)\n-\n def copy(self, deep=True) -> 'Actor':\n \"\"\"Create a copy of this actor.\n \n@@ -556,38 +381,6 @@ def user_matrix(self, value: Union[pv._vtk.vtkMatrix4x4, np.ndarray]):\n value = pv.vtkmatrix_from_array(value)\n self.SetUserMatrix(value)\n \n- @property\n- def bounds(self) -> BoundsLike:\n- \"\"\"Return the bounds of the actor.\n-\n- Bounds are ``(-X, +X, -Y, +Y, -Z, +Z)``\n-\n- Examples\n- --------\n- >>> import pyvista as pv\n- >>> pl = pv.Plotter()\n- >>> mesh = pv.Cube(x_length=0.1, y_length=0.2, z_length=0.3)\n- >>> actor = pl.add_mesh(mesh)\n- >>> actor.bounds\n- (-0.05, 0.05, -0.1, 0.1, -0.15, 0.15)\n-\n- \"\"\"\n- return self.GetBounds()\n-\n- @property\n- def center(self) -> tuple:\n- \"\"\"Return the center of the actor.\n-\n- Examples\n- --------\n- >>> import pyvista as pv\n- >>> pl = pv.Plotter()\n- >>> actor = pl.add_mesh(pv.Sphere(center=(0.5, 0.5, 1)))\n- >>> actor.center # doctest:+SKIP\n- (0.5, 0.5, 1)\n- \"\"\"\n- return self.GetCenter()\n-\n @property\n def backface_prop(self) -> Optional['pv.Property']:\n \"\"\"Return or set the backface property.\ndiff --git a/pyvista/plotting/mapper.py b/pyvista/plotting/mapper.py\n--- a/pyvista/plotting/mapper.py\n+++ b/pyvista/plotting/mapper.py\n@@ -1,6 +1,6 @@\n \"\"\"An internal module for wrapping the use of mappers.\"\"\"\n import sys\n-from typing import Optional\n+from typing import Optional, Union\n \n import numpy as np\n \n@@ -14,6 +14,7 @@\n )\n from pyvista.utilities.misc import has_module, no_new_attr\n \n+from .._typing import BoundsLike\n from .colors import Color, get_cmap_safe\n from .lookup_table import LookupTable\n from .tools import normalize\n@@ -29,6 +30,20 @@ def __init__(self, theme=None, **kwargs):\n self._theme = theme\n self.lookup_table = LookupTable()\n \n+ @property\n+ def bounds(self) -> BoundsLike:\n+ \"\"\"Return the bounds of this mapper.\n+\n+ Examples\n+ --------\n+ >>> import pyvista as pv\n+ >>> mapper = pv.DataSetMapper(dataset=pv.Cube())\n+ >>> mapper.bounds\n+ (-0.5, 0.5, -0.5, 0.5, -0.5, 0.5)\n+\n+ \"\"\"\n+ return self.GetBounds()\n+\n def copy(self) -> '_BaseMapper':\n \"\"\"Create a copy of this mapper.\n \n@@ -501,16 +516,16 @@ def set_scalars(\n than zero are mapped to the smallest representable\n positive float.\n \n- nan_color : ColorLike, optional\n+ nan_color : color_like, optional\n The color to use for all ``NaN`` values in the plotted\n scalar array.\n \n- above_color : ColorLike, optional\n+ above_color : color_like, optional\n Solid color for values below the scalars range\n (``clim``). This will automatically set the scalar bar\n ``above_label`` to ``'Above'``.\n \n- below_color : ColorLike, optional\n+ below_color : color_like, optional\n Solid color for values below the scalars range\n (``clim``). This will automatically set the scalar bar\n ``below_label`` to ``'Below'``.\n@@ -721,7 +736,7 @@ def set_custom_opacity(self, opacity, color, n_colors, preference='point'):\n Opacity array to color the dataset. Array length must match either\n the number of points or cells.\n \n- color : ColorLike\n+ color : color_like\n The color to use with the opacity array.\n \n n_colors : int\n@@ -869,7 +884,8 @@ def __init__(self, theme=None):\n @property\n def dataset(self):\n \"\"\"Return or set the dataset assigned to this mapper.\"\"\"\n- return self.GetInputAsDataSet()\n+ # GetInputAsDataSet unavailable on volume mappers\n+ return self.GetDataSetInput()\n \n @dataset.setter\n def dataset(self, new_dataset: 'pv.core.dataset.DataSet'):\n@@ -894,6 +910,64 @@ def scalar_range(self, clim):\n self.lookup_table.SetRange(*clim)\n self._scalar_range = clim\n \n+ @property\n+ def blend_mode(self) -> str:\n+ \"\"\"Return or set the blend mode.\n+\n+ One of the following:\n+\n+ * ``\"composite\"``\n+ * ``\"maximum\"``\n+ * ``\"minimum\"``\n+ * ``\"average\"``\n+ * ``\"additive\"``\n+\n+ Also accepts integer values corresponding to\n+ ``vtk.vtkVolumeMapper.BlendModes``. For example\n+ ``vtk.vtkVolumeMapper.COMPOSITE_BLEND``.\n+\n+ \"\"\"\n+ value = self.GetBlendMode()\n+ if value == 0:\n+ return 'composite'\n+ elif value == 1:\n+ return 'maximum'\n+ elif value == 2:\n+ return 'minimum'\n+ elif value == 3:\n+ return 'average'\n+ elif value == 4:\n+ return 'additive'\n+\n+ raise NotImplementedError(\n+ f'Unsupported blend mode return value {value}'\n+ ) # pragma: no cover\n+\n+ @blend_mode.setter\n+ def blend_mode(self, value: Union[str, int]):\n+ if isinstance(value, int):\n+ self.SetBlendMode(value)\n+ elif isinstance(value, str):\n+ value = value.lower()\n+ if value in ['additive', 'add', 'sum']:\n+ self.SetBlendModeToAdditive()\n+ elif value in ['average', 'avg', 'average_intensity']:\n+ self.SetBlendModeToAverageIntensity()\n+ elif value in ['composite', 'comp']:\n+ self.SetBlendModeToComposite()\n+ elif value in ['maximum', 'max', 'maximum_intensity']:\n+ self.SetBlendModeToMaximumIntensity()\n+ elif value in ['minimum', 'min', 'minimum_intensity']:\n+ self.SetBlendModeToMinimumIntensity()\n+ else:\n+ raise ValueError(\n+ f'Blending mode {value!r} invalid. '\n+ 'Please choose either \"additive\", '\n+ '\"composite\", \"minimum\" or \"maximum\".'\n+ )\n+ else:\n+ raise TypeError(f'`blend_mode` should be either an int or str, not `{type(value)}`')\n+\n def __del__(self):\n self._lut = None\n \ndiff --git a/pyvista/plotting/plotting.py b/pyvista/plotting/plotting.py\n--- a/pyvista/plotting/plotting.py\n+++ b/pyvista/plotting/plotting.py\n@@ -20,6 +20,7 @@\n \n import pyvista\n from pyvista import _vtk\n+from pyvista.plotting.volume import Volume\n from pyvista.utilities import (\n FieldAssociation,\n abstract_class,\n@@ -62,6 +63,7 @@\n from .renderers import Renderers\n from .scalar_bars import ScalarBars\n from .tools import FONTS, normalize, opacity_transfer_function, parse_font_family # noqa\n+from .volume_property import VolumeProperty\n from .widgets import WidgetHelper\n \n SUPPORTED_FORMATS = [\".png\", \".jpeg\", \".jpg\", \".bmp\", \".tif\", \".tiff\"]\n@@ -3687,39 +3689,21 @@ def add_volume(\n self.mapper.lookup_table.annotations = annotations\n \n self.mapper.dataset = volume\n-\n- blending = blending.lower()\n- if blending in ['additive', 'add', 'sum']:\n- self.mapper.SetBlendModeToAdditive()\n- elif blending in ['average', 'avg', 'average_intensity']:\n- self.mapper.SetBlendModeToAverageIntensity()\n- elif blending in ['composite', 'comp']:\n- self.mapper.SetBlendModeToComposite()\n- elif blending in ['maximum', 'max', 'maximum_intensity']:\n- self.mapper.SetBlendModeToMaximumIntensity()\n- elif blending in ['minimum', 'min', 'minimum_intensity']:\n- self.mapper.SetBlendModeToMinimumIntensity()\n- else:\n- raise ValueError(\n- f'Blending mode {blending!r} invalid. '\n- 'Please choose either \"additive\", '\n- '\"composite\", \"minimum\" or \"maximum\".'\n- )\n+ self.mapper.blend_mode = blending\n self.mapper.update()\n \n- self.volume = _vtk.vtkVolume()\n- self.volume.SetMapper(self.mapper)\n-\n- prop = _vtk.vtkVolumeProperty()\n- prop.SetColor(self.mapper.lookup_table.to_color_tf())\n- prop.SetScalarOpacity(self.mapper.lookup_table.to_opacity_tf())\n- prop.SetAmbient(ambient)\n- prop.SetScalarOpacityUnitDistance(opacity_unit_distance)\n- prop.SetShade(shade)\n- prop.SetDiffuse(diffuse)\n- prop.SetSpecular(specular)\n- prop.SetSpecularPower(specular_power)\n- self.volume.SetProperty(prop)\n+ self.volume = Volume()\n+ self.volume.mapper = self.mapper\n+\n+ self.volume.prop = VolumeProperty(\n+ lookup_table=self.mapper.lookup_table,\n+ ambient=ambient,\n+ shade=shade,\n+ specular=specular,\n+ specular_power=specular_power,\n+ diffuse=diffuse,\n+ opacity_unit_distance=opacity_unit_distance,\n+ )\n \n actor, prop = self.add_actor(\n self.volume,\ndiff --git a/pyvista/plotting/prop3d.py b/pyvista/plotting/prop3d.py\nnew file mode 100644\n--- /dev/null\n+++ b/pyvista/plotting/prop3d.py\n@@ -0,0 +1,227 @@\n+\"\"\"Prop3D module.\"\"\"\n+from typing import Tuple\n+\n+from pyvista import _vtk\n+\n+from .._typing import BoundsLike, Vector\n+\n+\n+class Prop3D(_vtk.vtkProp3D):\n+ \"\"\"Prop3D wrapper for vtkProp3D.\n+\n+ Used to represent an entity in a rendering scene. It handles functions\n+ related to the position, orientation and scaling. Used as parent class\n+ in Actor and Volume class.\n+ \"\"\"\n+\n+ def __init__(self):\n+ \"\"\"Initialize Prop3D.\"\"\"\n+ super().__init__()\n+\n+ @property\n+ def scale(self) -> Tuple[float, float, float]:\n+ \"\"\"Return or set entity scale.\n+\n+ Examples\n+ --------\n+ Create an actor using the :class:`pyvista.Plotter` and then change the\n+ scale of the actor.\n+\n+ >>> import pyvista as pv\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_mesh(pv.Sphere())\n+ >>> actor.scale = (2.0, 2.0, 2.0)\n+ >>> actor.scale\n+ (2.0, 2.0, 2.0)\n+\n+ \"\"\"\n+ return self.GetScale()\n+\n+ @scale.setter\n+ def scale(self, value: Vector):\n+ return self.SetScale(value)\n+\n+ @property\n+ def position(self) -> Tuple[float, float, float]:\n+ \"\"\"Return or set the entity position.\n+\n+ Examples\n+ --------\n+ Change the position of an actor. Note how this does not change the\n+ position of the underlying dataset, just the relative location of the\n+ actor in the :class:`pyvista.Plotter`.\n+\n+ >>> import pyvista as pv\n+ >>> mesh = pv.Sphere()\n+ >>> pl = pv.Plotter()\n+ >>> _ = pl.add_mesh(mesh, color='b')\n+ >>> actor = pl.add_mesh(mesh, color='r')\n+ >>> actor.position = (0, 0, 1) # shifts the red sphere up\n+ >>> pl.show()\n+\n+ \"\"\"\n+ return self.GetPosition()\n+\n+ @position.setter\n+ def position(self, value: Vector):\n+ self.SetPosition(value)\n+\n+ def rotate_x(self, angle: float):\n+ \"\"\"Rotate the entity about the x axis.\n+\n+ Parameters\n+ ----------\n+ angle : float\n+ Angle to rotate the entity about the x axis in degrees.\n+\n+ Examples\n+ --------\n+ Rotate the actor about the x axis 45 degrees. Note how this does not\n+ change the location of the underlying dataset.\n+\n+ >>> import pyvista as pv\n+ >>> mesh = pv.Cube()\n+ >>> pl = pv.Plotter()\n+ >>> _ = pl.add_mesh(mesh, color='b')\n+ >>> actor = pl.add_mesh(\n+ ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n+ ... )\n+ >>> actor.rotate_x(45)\n+ >>> pl.show_axes()\n+ >>> pl.show()\n+\n+ \"\"\"\n+ self.RotateX(angle)\n+\n+ def rotate_y(self, angle: float):\n+ \"\"\"Rotate the entity about the y axis.\n+\n+ Parameters\n+ ----------\n+ angle : float\n+ Angle to rotate the entity about the y axis in degrees.\n+\n+ Examples\n+ --------\n+ Rotate the actor about the y axis 45 degrees. Note how this does not\n+ change the location of the underlying dataset.\n+\n+ >>> import pyvista as pv\n+ >>> mesh = pv.Cube()\n+ >>> pl = pv.Plotter()\n+ >>> _ = pl.add_mesh(mesh, color='b')\n+ >>> actor = pl.add_mesh(\n+ ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n+ ... )\n+ >>> actor.rotate_y(45)\n+ >>> pl.show_axes()\n+ >>> pl.show()\n+\n+ \"\"\"\n+ self.RotateY(angle)\n+\n+ def rotate_z(self, angle: float):\n+ \"\"\"Rotate the entity about the z axis.\n+\n+ Parameters\n+ ----------\n+ angle : float\n+ Angle to rotate the entity about the z axis in degrees.\n+\n+ Examples\n+ --------\n+ Rotate the actor about the Z axis 45 degrees. Note how this does not\n+ change the location of the underlying dataset.\n+\n+ >>> import pyvista as pv\n+ >>> mesh = pv.Cube()\n+ >>> pl = pv.Plotter()\n+ >>> _ = pl.add_mesh(mesh, color='b')\n+ >>> actor = pl.add_mesh(\n+ ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n+ ... )\n+ >>> actor.rotate_z(45)\n+ >>> pl.show_axes()\n+ >>> pl.show()\n+\n+ \"\"\"\n+ self.RotateZ(angle)\n+\n+ @property\n+ def orientation(self) -> tuple:\n+ \"\"\"Return or set the entity orientation.\n+\n+ Orientation is defined as the rotation from the global axes in degrees\n+ about the actor's x, y, and z axes.\n+\n+ Examples\n+ --------\n+ Show that the orientation changes with rotation.\n+\n+ >>> import pyvista as pv\n+ >>> mesh = pv.Cube()\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_mesh(mesh)\n+ >>> actor.rotate_x(90)\n+ >>> actor.orientation # doctest:+SKIP\n+ (90, 0, 0)\n+\n+ Set the orientation directly.\n+\n+ >>> actor.orientation = (0, 45, 45)\n+ >>> actor.orientation # doctest:+SKIP\n+ (0, 45, 45)\n+\n+ Reorient just the actor and plot it. Note how the actor is rotated\n+ about its own axes as defined by its position.\n+\n+ >>> import pyvista as pv\n+ >>> mesh = pv.Cube()\n+ >>> pl = pv.Plotter()\n+ >>> _ = pl.add_mesh(mesh, color='b')\n+ >>> actor = pl.add_mesh(\n+ ... mesh, color='r', style='wireframe', line_width=5, lighting=False,\n+ ... )\n+ >>> actor.position = (0, 0, 1)\n+ >>> actor.orientation = (45, 0, 0)\n+ >>> pl.show_axes()\n+ >>> pl.show()\n+\n+ \"\"\"\n+ return self.GetOrientation()\n+\n+ @orientation.setter\n+ def orientation(self, value: tuple):\n+ self.SetOrientation(value)\n+\n+ @property\n+ def bounds(self) -> BoundsLike:\n+ \"\"\"Return the bounds of the entity.\n+\n+ Bounds are ``(-X, +X, -Y, +Y, -Z, +Z)``\n+\n+ Examples\n+ --------\n+ >>> import pyvista as pv\n+ >>> pl = pv.Plotter()\n+ >>> mesh = pv.Cube(x_length=0.1, y_length=0.2, z_length=0.3)\n+ >>> actor = pl.add_mesh(mesh)\n+ >>> actor.bounds\n+ (-0.05, 0.05, -0.1, 0.1, -0.15, 0.15)\n+\n+ \"\"\"\n+ return self.GetBounds()\n+\n+ @property\n+ def center(self) -> tuple:\n+ \"\"\"Return the center of the entity.\n+\n+ Examples\n+ --------\n+ >>> import pyvista as pv\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_mesh(pv.Sphere(center=(0.5, 0.5, 1)))\n+ >>> actor.center # doctest:+SKIP\n+ (0.5, 0.5, 1)\n+ \"\"\"\n+ return self.GetCenter()\ndiff --git a/pyvista/plotting/volume.py b/pyvista/plotting/volume.py\nnew file mode 100644\n--- /dev/null\n+++ b/pyvista/plotting/volume.py\n@@ -0,0 +1,65 @@\n+\"\"\"PyVista volume module.\"\"\"\n+from pyvista import _vtk\n+\n+from ._property import Property\n+from .mapper import _BaseMapper\n+from .prop3d import Prop3D\n+\n+\n+class Volume(Prop3D, _vtk.vtkVolume):\n+ \"\"\"Wrapper class for VTK volume.\n+\n+ This class represents a volume in a rendered scene. It inherits\n+ functions related to the volume's position, orientation and origin\n+ from Prop3D.\n+\n+ \"\"\"\n+\n+ def __init__(self):\n+ \"\"\"Initialize volume.\"\"\"\n+ super().__init__()\n+\n+ @property\n+ def mapper(self) -> _BaseMapper:\n+ \"\"\"Return or set the mapper of the volume.\n+\n+ Examples\n+ --------\n+ Add a volume to a :class:`pyvista.Plotter` and get its mapper.\n+\n+ >>> import pyvista as pv\n+ >>> vol = pv.UniformGrid(dimensions=(10, 10, 10))\n+ >>> vol['scalars'] = 255 - vol.z*25\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_volume(vol)\n+ >>> actor.mapper.bounds\n+ (0.0, 9.0, 0.0, 9.0, 0.0, 9.0)\n+ \"\"\"\n+ return self.GetMapper()\n+\n+ @mapper.setter\n+ def mapper(self, obj):\n+ return self.SetMapper(obj)\n+\n+ @property\n+ def prop(self):\n+ \"\"\"Return or set the property of this actor.\n+\n+ Examples\n+ --------\n+ Create an volume and get its properties.\n+\n+ >>> import pyvista as pv\n+ >>> vol = pv.UniformGrid(dimensions=(10, 10, 10))\n+ >>> vol['scalars'] = 255 - vol.z*25\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_volume(vol)\n+ >>> actor.prop.GetShade()\n+ 0\n+\n+ \"\"\"\n+ return self.GetProperty()\n+\n+ @prop.setter\n+ def prop(self, obj: Property):\n+ self.SetProperty(obj)\ndiff --git a/pyvista/plotting/volume_property.py b/pyvista/plotting/volume_property.py\nnew file mode 100644\n--- /dev/null\n+++ b/pyvista/plotting/volume_property.py\n@@ -0,0 +1,333 @@\n+\"\"\"This module contains the VolumeProperty class.\"\"\"\n+import pyvista as pv\n+from pyvista import _vtk\n+from pyvista.utilities.misc import no_new_attr\n+\n+\n+@no_new_attr\n+class VolumeProperty(_vtk.vtkVolumeProperty):\n+ \"\"\"Wrap the VTK class vtkVolumeProperty.\n+\n+ This class is used to represent common properties associated with volume\n+ rendering. This includes properties for determining the type of\n+ interpolation to use when sampling a volume, the color of a volume, the\n+ scalar opacity of a volume, the gradient opacity of a volume, and the\n+ shading parameters of a volume.\n+\n+ Parameters\n+ ----------\n+ lookup_table : pyvista.LookupTable, optional\n+ Lookup table to set the color and opacity transfer functions.\n+\n+ interpolation_type : str, optional\n+ Value must be either ``'linear'`` or ``'nearest'``.\n+\n+ ambient : float, optional\n+ When lighting is enabled, this is the amount of light in\n+ the range of 0 to 1 (default 0.0) that reaches the actor\n+ when not directed at the light source emitted from the\n+ viewer.\n+\n+ diffuse : float, optional\n+ The diffuse lighting coefficient. Default 1.0.\n+\n+ specular : float, optional\n+ The specular lighting coefficient. Default 0.0.\n+\n+ specular_power : float, optional\n+ The specular power. Between 0.0 and 128.0.\n+\n+ shade : bool, optional\n+ Enable or disable volume shading. If shading is turned off, then the\n+ mapper for the volume will not perform shading calculations. If shading\n+ is turned on, the mapper may perform shading calculations - in some\n+ cases shading does not apply (for example, in a maximum intensity\n+ projection) and therefore shading will not be performed even if this\n+ flag is on. For a compositing type of mapper, turning shading off is\n+ generally the same as setting ``ambient=1``, ``diffuse=0``,\n+ ``specular=0``. Shading can be independently turned on/off per\n+ component.\n+\n+ opacity_unit_distance : float, optional\n+ This is the unit distance on which the scalar opacity transfer function\n+ is defined. By default this is 1.0, meaning that over a distance of 1.0\n+ units, a given opacity (from the transfer function) is\n+ accumulated. This is adjusted for the actual sampling distance during\n+ rendering.\n+\n+ Examples\n+ --------\n+ Create a sample dataset from perlin noise and apply a lookup table to the\n+ :class:`VolumeProperty`.\n+\n+ >>> import pyvista as pv\n+ >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))\n+ >>> grid = pv.sample_function(noise, [0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40))\n+ >>> grid['scalars'] -= grid['scalars'].min()\n+ >>> grid['scalars']*= 255/grid['scalars'].max()\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_volume(grid, show_scalar_bar=False)\n+ >>> lut = pv.LookupTable(cmap='bwr')\n+ >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])\n+ >>> actor.prop.apply_lookup_table(lut)\n+ >>> pl.show()\n+\n+\n+ \"\"\"\n+\n+ def __init__(\n+ self,\n+ lookup_table=None,\n+ interpolation_type=None,\n+ ambient=None,\n+ diffuse=None,\n+ specular=None,\n+ specular_power=None,\n+ shade=None,\n+ opacity_unit_distance=None,\n+ ):\n+ \"\"\"Initialize the vtkVolumeProperty class.\"\"\"\n+ super().__init__()\n+ if lookup_table is not None:\n+ self.apply_lookup_table(lookup_table)\n+ if interpolation_type is not None:\n+ self.interpolation_type = interpolation_type\n+ if ambient is not None:\n+ self.ambient = ambient\n+ if diffuse is not None:\n+ self.diffuse = diffuse\n+ if specular is not None:\n+ self.specular = specular\n+ if specular_power is not None:\n+ self.specular_power = specular_power\n+ if shade is not None:\n+ self.shade = shade\n+ if opacity_unit_distance is not None:\n+ self.opacity_unit_distance = opacity_unit_distance\n+\n+ def apply_lookup_table(self, lookup_table: 'pv.LookupTable'):\n+ \"\"\"Apply a lookup table to the volume property.\n+\n+ Applies both the color and opacity of the lookup table as transfer\n+ functions.\n+\n+ Parameters\n+ ----------\n+ lookup_table : pyvista.LookupTable, optional\n+ Lookup table to set the color and opacity transfer functions.\n+\n+ Examples\n+ --------\n+ Plot perlin noise volumetrically using a custom lookup table.\n+\n+ >>> import pyvista as pv\n+ >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))\n+ >>> grid = pv.sample_function(noise, [0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40))\n+ >>> grid['scalars'] -= grid['scalars'].min()\n+ >>> grid['scalars']*= 255/grid['scalars'].max()\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_volume(grid, show_scalar_bar=False)\n+ >>> lut = pv.LookupTable(cmap='bwr')\n+ >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])\n+ >>> actor.prop.apply_lookup_table(lut)\n+ >>> pl.show()\n+\n+ \"\"\"\n+ if not isinstance(lookup_table, pv.LookupTable):\n+ raise TypeError('`lookup_table` must be a `pyvista.LookupTable`')\n+\n+ self.SetColor(lookup_table.to_color_tf())\n+ self.SetScalarOpacity(lookup_table.to_opacity_tf())\n+\n+ @property\n+ def interpolation_type(self) -> str:\n+ \"\"\"Return or set the interpolation type.\n+\n+ Value must be either ``'linear'`` or ``'nearest'``.\n+\n+ Examples\n+ --------\n+ Create a sample :class:`pyvista.UniformGrid` dataset.\n+\n+ >>> import numpy as np\n+ >>> import pyvista as pv\n+ >>> n = 21\n+ >>> c = -(n-1)/2\n+ >>> vol = pv.UniformGrid(dimensions=(n, n, n), origin=(c, c, c))\n+ >>> scalars = np.linalg.norm(vol.points, axis=1)\n+ >>> scalars *= 255/scalars.max()\n+ >>> vol['scalars'] = scalars\n+\n+ Demonstrate nearest (default) interpolation.\n+\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_volume(\n+ ... vol,\n+ ... show_scalar_bar=False,\n+ ... opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],\n+ ... cmap='plasma'\n+ ... )\n+ >>> actor.prop.interpolation_type = 'nearest'\n+ >>> pl.show()\n+\n+ Demonstrate linear interpolation.\n+\n+ >>> pl = pv.Plotter()\n+ >>> actor = pl.add_volume(\n+ ... vol,\n+ ... show_scalar_bar=False,\n+ ... opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],\n+ ... cmap='plasma'\n+ ... )\n+ >>> actor.prop.interpolation_type = 'linear'\n+ >>> pl.show()\n+\n+ \"\"\"\n+ return self.GetInterpolationTypeAsString().split()[0].lower()\n+\n+ @interpolation_type.setter\n+ def interpolation_type(self, value: str):\n+ if value == 'linear':\n+ self.SetInterpolationTypeToLinear()\n+ elif value == 'nearest':\n+ self.SetInterpolationTypeToNearest()\n+ else:\n+ raise ValueError('`interpolation_type` must be either \"linear\" or \"nearest\"')\n+\n+ @property\n+ def opacity_unit_distance(self) -> float:\n+ \"\"\"Return or set the opacity unit distance.\n+\n+ This is the unit distance on which the scalar opacity transfer function\n+ is defined.\n+\n+ By default this is 1.0, meaning that over a distance of 1.0 units, a\n+ given opacity (from the transfer function) is accumulated. This is\n+ adjusted for the actual sampling distance during rendering.\n+ \"\"\"\n+ return self.GetScalarOpacityUnitDistance()\n+\n+ @opacity_unit_distance.setter\n+ def opacity_unit_distance(self, value: float):\n+ self.SetScalarOpacityUnitDistance(value)\n+\n+ @property\n+ def shade(self) -> bool:\n+ \"\"\"Return or set shading of a volume.\n+\n+ If shading is turned off, then the mapper for the volume will not\n+ perform shading calculations. If shading is turned on, the mapper may\n+ perform shading calculations - in some cases shading does not apply\n+ (for example, in a maximum intensity projection) and therefore shading\n+ will not be performed even if this flag is on. For a compositing type\n+ of mapper, turning shading off is generally the same as setting\n+ ``ambient=1``, ``diffuse=0``, ``specular=0``. Shading can be\n+ independently turned on/off per component.\n+\n+ \"\"\"\n+ return bool(self.GetShade())\n+\n+ @shade.setter\n+ def shade(self, value: bool):\n+ self.SetShade(value)\n+\n+ @property\n+ def ambient(self) -> float:\n+ \"\"\"Return or set ambient lighting coefficient.\n+\n+ This is the amount of light in the range of 0 to 1 (default 0.0) that\n+ reaches the actor when not directed at the light source emitted from\n+ the viewer.\n+\n+ Changing attribute has no effect unless :attr:`VolumeProperty.shade` is\n+ set to ``True``.\n+\n+ \"\"\"\n+ return self.GetAmbient()\n+\n+ @ambient.setter\n+ def ambient(self, value: float):\n+ self.SetAmbient(value)\n+\n+ @property\n+ def diffuse(self) -> float:\n+ \"\"\"Return or set the diffuse lighting coefficient.\n+\n+ Default 1.0.\n+\n+ This is the scattering of light by reflection or transmission. Diffuse\n+ reflection results when light strikes an irregular surface such as a\n+ frosted window or the surface of a frosted or coated light bulb.\n+\n+ Changing attribute has no effect unless :attr:`VolumeProperty.shade` is\n+ set to ``True``.\n+\n+ \"\"\"\n+ return self.GetDiffuse()\n+\n+ @diffuse.setter\n+ def diffuse(self, value: float):\n+ self.SetDiffuse(value)\n+\n+ @property\n+ def specular(self) -> float:\n+ \"\"\"Return or set specular.\n+\n+ Default 0.0\n+\n+ Specular lighting simulates the bright spot of a light that appears on\n+ shiny objects.\n+\n+ Changing attribute has no effect unless :attr:`VolumeProperty.shade` is\n+ set to ``True``.\n+\n+ \"\"\"\n+ return self.GetSpecular()\n+\n+ @specular.setter\n+ def specular(self, value: float):\n+ self.SetSpecular(value)\n+\n+ @property\n+ def specular_power(self) -> float:\n+ \"\"\"Return or set specular power.\n+\n+ The specular power. Between 0.0 and 128.0. Default 10.0\n+\n+ \"\"\"\n+ return self.GetSpecularPower()\n+\n+ @specular_power.setter\n+ def specular_power(self, value: float):\n+ self.SetSpecularPower(value)\n+\n+ def copy(self) -> 'VolumeProperty':\n+ \"\"\"Create a deep copy of this property.\n+\n+ Returns\n+ -------\n+ pyvista.VolumeProperty\n+ Deep copy of this property.\n+\n+ \"\"\"\n+ new_prop = VolumeProperty()\n+ new_prop.DeepCopy(self)\n+ return new_prop\n+\n+ def __repr__(self):\n+ \"\"\"Representation of this property.\"\"\"\n+ props = [\n+ f'{type(self).__name__} ({hex(id(self))})',\n+ ]\n+\n+ for attr in dir(self):\n+ if not attr.startswith('_') and attr[0].islower():\n+ name = ' '.join(attr.split('_')).capitalize() + ':'\n+ value = getattr(self, attr)\n+ if callable(value):\n+ continue\n+ if isinstance(value, str):\n+ value = f'\"{value}\"'\n+ props.append(f' {name:28s} {value}')\n+\n+ return '\\n'.join(props)\n", "test_patch": "diff --git a/tests/mappers/test_mapper.py b/tests/mappers/test_mapper.py\n--- a/tests/mappers/test_mapper.py\n+++ b/tests/mappers/test_mapper.py\n@@ -25,6 +25,11 @@ def test_scalar_range(dataset_mapper):\n assert dataset_mapper.scalar_range == rng\n \n \n+def test_bounds(dataset_mapper):\n+ assert isinstance(dataset_mapper.bounds, tuple)\n+ assert dataset_mapper.bounds == (-126.0, 125.0, -127.0, 126.0, -127.0, 127.0)\n+\n+\n def test_lookup_table(dataset_mapper):\n assert isinstance(dataset_mapper.lookup_table, vtk.vtkLookupTable)\n \ndiff --git a/tests/mappers/test_volume_mapper.py b/tests/mappers/test_volume_mapper.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/mappers/test_volume_mapper.py\n@@ -0,0 +1,34 @@\n+import pytest\n+import vtk\n+\n+import pyvista as pv\n+\n+\[email protected]()\n+def volume_mapper():\n+ vol = pv.UniformGrid(dimensions=(10, 10, 10))\n+ vol['scalars'] = 255 - vol.z * 25\n+ pl = pv.Plotter()\n+ actor = pl.add_volume(vol)\n+ return actor.mapper\n+\n+\n+def test_volume_mapper_dataset(volume_mapper):\n+ assert isinstance(volume_mapper.dataset, pv.UniformGrid)\n+\n+\n+def test_volume_mapper_blend_mode(volume_mapper):\n+ assert isinstance(volume_mapper.blend_mode, str)\n+\n+ volume_mapper.blend_mode = vtk.vtkVolumeMapper.COMPOSITE_BLEND\n+ assert volume_mapper.blend_mode == 'composite'\n+\n+ for mode in ['average', 'minimum', 'maximum', 'composite', 'additive']:\n+ volume_mapper.blend_mode = mode\n+ assert volume_mapper.blend_mode == mode\n+\n+ with pytest.raises(ValueError, match='Please choose either \"additive\"'):\n+ volume_mapper.blend_mode = 'not a mode'\n+\n+ with pytest.raises(TypeError, match='int or str'):\n+ volume_mapper.blend_mode = 0.5\ndiff --git a/tests/test_actor.py b/tests/test_actor.py\n--- a/tests/test_actor.py\n+++ b/tests/test_actor.py\n@@ -2,6 +2,7 @@\n \n import numpy as np\n import pytest\n+import vtk\n \n import pyvista as pv\n from pyvista import examples\n@@ -16,6 +17,14 @@ def actor():\n return pv.Plotter().add_mesh(pv.Plane())\n \n \[email protected]()\n+def vol_actor():\n+ vol = pv.UniformGrid(dimensions=(10, 10, 10))\n+ vol['scalars'] = 255 - vol.z * 25\n+ pl = pv.Plotter()\n+ return pl.add_volume(vol)\n+\n+\n def test_actor_init_empty():\n actor = pv.Actor()\n assert 'Position' in repr(actor)\n@@ -143,3 +152,11 @@ def test_actor_backface_prop(actor):\n \n actor.backface_prop = None\n assert actor.backface_prop.opacity == actor.prop.opacity\n+\n+\n+def test_vol_actor_prop(vol_actor):\n+ assert isinstance(vol_actor.prop, vtk.vtkVolumeProperty)\n+\n+ prop = vtk.vtkVolumeProperty()\n+ vol_actor.prop = prop\n+ assert vol_actor.prop is prop\ndiff --git a/tests/test_volume_property.py b/tests/test_volume_property.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/test_volume_property.py\n@@ -0,0 +1,75 @@\n+import pytest\n+\n+import pyvista as pv\n+from pyvista.plotting.volume_property import VolumeProperty\n+\n+\[email protected]()\n+def vol_prop():\n+ return VolumeProperty()\n+\n+\n+def test_volume_lookup_table(vol_prop):\n+ lut = pv.LookupTable(cmap='bwr')\n+ lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])\n+ orig = vol_prop.GetRGBTransferFunction()\n+ vol_prop.apply_lookup_table(lut)\n+ assert vol_prop.GetRGBTransferFunction() is not orig\n+\n+\n+def test_interpolation_type(vol_prop):\n+ assert isinstance(vol_prop.interpolation_type, str)\n+\n+ for interpolation_type in ['nearest', 'linear']:\n+ vol_prop.interpolation_type = interpolation_type\n+ assert vol_prop.interpolation_type == interpolation_type\n+\n+ with pytest.raises(ValueError, match='must be either'):\n+ vol_prop.interpolation_type = 'not valid'\n+\n+\n+def test_volume_property_shade(vol_prop):\n+ assert isinstance(vol_prop.shade, bool)\n+ vol_prop.shade = True\n+ assert vol_prop.shade is True\n+ vol_prop.shade = False\n+ assert vol_prop.shade is False\n+\n+\n+def test_volume_property_ambient(vol_prop):\n+ assert isinstance(vol_prop.ambient, float)\n+ value = 0.45\n+ vol_prop.ambient = value\n+ assert vol_prop.ambient == value\n+\n+\n+def test_volume_property_diffuse(vol_prop):\n+ assert isinstance(vol_prop.diffuse, float)\n+ value = 0.45\n+ vol_prop.diffuse = value\n+ assert vol_prop.diffuse == value\n+\n+\n+def test_volume_property_specular(vol_prop):\n+ assert isinstance(vol_prop.specular, float)\n+ value = 0.45\n+ vol_prop.specular = value\n+ assert vol_prop.specular == value\n+\n+\n+def test_volume_property_specular_power(vol_prop):\n+ assert isinstance(vol_prop.specular_power, float)\n+ value = 0.45\n+ vol_prop.specular_power = value\n+ assert vol_prop.specular_power == value\n+\n+\n+def test_volume_property_copy(vol_prop):\n+ vol_prop.ambient = 1.0\n+ vol_prop_copy = vol_prop.copy()\n+ assert vol_prop_copy.ambient == vol_prop.ambient\n+\n+\n+def test_volume_property_repr(vol_prop):\n+ assert 'Interpolation type:' in repr(vol_prop)\n+ assert \"nearest\" in repr(vol_prop)\n", "problem_statement": "vtkVolume needs wrapping like vtkActor\nWe wrap vtkActor nicely and should do the same for vtkVolume to make lookup table modification during volume rendering nicer.\r\n\r\n```py\r\nimport pyvista as pv\r\nfrom pyvista import examples\r\n\r\nvol = examples.download_knee_full()\r\n\r\np = pv.Plotter(notebook=0)\r\nactor = p.add_volume(vol, cmap=\"bone\", opacity=\"sigmoid\")\r\nactor.mapper.lookup_table.cmap = 'viridis'\r\np.show()\r\n```\r\n\r\n```\r\n---------------------------------------------------------------------------\r\nAttributeError Traceback (most recent call last)\r\nInput In [3], in <cell line: 8>()\r\n 6 p = pv.Plotter(notebook=0)\r\n 7 actor = p.add_volume(vol, cmap=\"bone\", opacity=\"sigmoid\")\r\n----> 8 actor.mapper.lookup_table.cmap = 'viridis'\r\n 9 p.show()\r\n\r\nAttributeError: 'vtkmodules.vtkRenderingCore.vtkVolume' object has no attribute 'mapper'\r\n```\n", "hints_text": "", "created_at": "2022-12-02T09:57:52Z", "version": "0.38", "FAIL_TO_PASS": ["tests/mappers/test_mapper.py::test_init", "tests/mappers/test_mapper.py::test_scalar_range", "tests/mappers/test_mapper.py::test_bounds", "tests/mappers/test_mapper.py::test_lookup_table", "tests/mappers/test_mapper.py::test_interpolate_before_map", "tests/mappers/test_mapper.py::test_color_mode", "tests/mappers/test_mapper.py::test_set_scalars", "tests/mappers/test_mapper.py::test_array_name", "tests/mappers/test_mapper.py::test_do_not_set_attributes", "tests/mappers/test_mapper.py::test_copy", "tests/mappers/test_volume_mapper.py::test_volume_mapper_dataset", "tests/mappers/test_volume_mapper.py::test_volume_mapper_blend_mode", "tests/test_actor.py::test_actor_init_empty", "tests/test_actor.py::test_actor_from_plotter", "tests/test_actor.py::test_actor_copy_deep", "tests/test_actor.py::test_actor_copy_shallow", "tests/test_actor.py::test_actor_texture", "tests/test_actor.py::test_actor_pickable", "tests/test_actor.py::test_actor_visible", "tests/test_actor.py::test_actor_scale", "tests/test_actor.py::test_actor_position", "tests/test_actor.py::test_actor_rotate_x", "tests/test_actor.py::test_actor_rotate_y", "tests/test_actor.py::test_actor_rotate_z", "tests/test_actor.py::test_actor_orientation", "tests/test_actor.py::test_actor_unit_matrix", "tests/test_actor.py::test_actor_bounds", "tests/test_actor.py::test_actor_center", "tests/test_actor.py::test_actor_backface_prop", "tests/test_actor.py::test_vol_actor_prop", "tests/test_volume_property.py::test_volume_lookup_table", "tests/test_volume_property.py::test_interpolation_type", "tests/test_volume_property.py::test_volume_property_shade", "tests/test_volume_property.py::test_volume_property_ambient", "tests/test_volume_property.py::test_volume_property_diffuse", "tests/test_volume_property.py::test_volume_property_specular", "tests/test_volume_property.py::test_volume_property_specular_power", "tests/test_volume_property.py::test_volume_property_copy", "tests/test_volume_property.py::test_volume_property_repr"], "PASS_TO_PASS": [], "environment_setup_commit": "8dd8eeb80248cea4360c753847bd622e8652e059"}, {"repo": "pyvista/pyvista", "instance_id": "pyvista__pyvista-4315", "base_commit": "db6ee8dd4a747b8864caae36c5d05883976a3ae5", "patch": "diff --git a/pyvista/core/grid.py b/pyvista/core/grid.py\n--- a/pyvista/core/grid.py\n+++ b/pyvista/core/grid.py\n@@ -135,23 +135,30 @@ def __init__(self, *args, check_duplicates=False, deep=False, **kwargs):\n self.shallow_copy(args[0])\n elif isinstance(args[0], (str, pathlib.Path)):\n self._from_file(args[0], **kwargs)\n- elif isinstance(args[0], np.ndarray):\n- self._from_arrays(args[0], None, None, check_duplicates)\n+ elif isinstance(args[0], (np.ndarray, Sequence)):\n+ self._from_arrays(np.asanyarray(args[0]), None, None, check_duplicates)\n else:\n raise TypeError(f'Type ({type(args[0])}) not understood by `RectilinearGrid`')\n \n elif len(args) == 3 or len(args) == 2:\n- arg0_is_arr = isinstance(args[0], np.ndarray)\n- arg1_is_arr = isinstance(args[1], np.ndarray)\n+ arg0_is_arr = isinstance(args[0], (np.ndarray, Sequence))\n+ arg1_is_arr = isinstance(args[1], (np.ndarray, Sequence))\n if len(args) == 3:\n- arg2_is_arr = isinstance(args[2], np.ndarray)\n+ arg2_is_arr = isinstance(args[2], (np.ndarray, Sequence))\n else:\n arg2_is_arr = False\n \n if all([arg0_is_arr, arg1_is_arr, arg2_is_arr]):\n- self._from_arrays(args[0], args[1], args[2], check_duplicates)\n+ self._from_arrays(\n+ np.asanyarray(args[0]),\n+ np.asanyarray(args[1]),\n+ np.asanyarray(args[2]),\n+ check_duplicates,\n+ )\n elif all([arg0_is_arr, arg1_is_arr]):\n- self._from_arrays(args[0], args[1], None, check_duplicates)\n+ self._from_arrays(\n+ np.asanyarray(args[0]), np.asanyarray(args[1]), None, check_duplicates\n+ )\n else:\n raise TypeError(\"Arguments not understood by `RectilinearGrid`.\")\n \n", "test_patch": "diff --git a/tests/test_grid.py b/tests/test_grid.py\n--- a/tests/test_grid.py\n+++ b/tests/test_grid.py\n@@ -735,6 +735,21 @@ def test_create_rectilinear_grid_from_specs():\n assert grid.n_cells == 9 * 3 * 19\n assert grid.n_points == 10 * 4 * 20\n assert grid.bounds == (-10.0, 8.0, -10.0, 5.0, -10.0, 9.0)\n+\n+ # with Sequence\n+ xrng = [0, 1]\n+ yrng = [0, 1, 2]\n+ zrng = [0, 1, 2, 3]\n+ grid = pyvista.RectilinearGrid(xrng)\n+ assert grid.n_cells == 1\n+ assert grid.n_points == 2\n+ grid = pyvista.RectilinearGrid(xrng, yrng)\n+ assert grid.n_cells == 2\n+ assert grid.n_points == 6\n+ grid = pyvista.RectilinearGrid(xrng, yrng, zrng)\n+ assert grid.n_cells == 6\n+ assert grid.n_points == 24\n+\n # 2D example\n cell_spacings = np.array([1.0, 1.0, 2.0, 2.0, 5.0, 10.0])\n x_coordinates = np.cumsum(cell_spacings)\n", "problem_statement": "Rectilinear grid does not allow Sequences as inputs\n### Describe the bug, what's wrong, and what you expected.\r\n\r\nRectilinear grid gives an error when `Sequence`s are passed in, but `ndarray` are ok.\r\n\r\n### Steps to reproduce the bug.\r\n\r\nThis doesn't work\r\n```python\r\nimport pyvista as pv\r\npv.RectilinearGrid([0, 1], [0, 1], [0, 1])\r\n```\r\n\r\nThis works\r\n```py\r\nimport pyvista as pv\r\nimport numpy as np\r\npv.RectilinearGrid(np.ndarray([0, 1]), np.ndarray([0, 1]), np.ndarray([0, 1]))\r\n```\r\n### System Information\r\n\r\n```shell\r\n--------------------------------------------------------------------------------\r\n Date: Wed Apr 19 20:15:10 2023 UTC\r\n\r\n OS : Linux\r\n CPU(s) : 2\r\n Machine : x86_64\r\n Architecture : 64bit\r\n Environment : IPython\r\n GPU Vendor : Mesa/X.org\r\n GPU Renderer : llvmpipe (LLVM 11.0.1, 256 bits)\r\n GPU Version : 4.5 (Core Profile) Mesa 20.3.5\r\n\r\n Python 3.11.2 (main, Mar 23 2023, 17:12:29) [GCC 10.2.1 20210110]\r\n\r\n pyvista : 0.38.5\r\n vtk : 9.2.6\r\n numpy : 1.24.2\r\n imageio : 2.27.0\r\n scooby : 0.7.1\r\n pooch : v1.7.0\r\n matplotlib : 3.7.1\r\n IPython : 8.12.0\r\n--------------------------------------------------------------------------------\r\n```\r\n\r\n\r\n### Screenshots\r\n\r\n_No response_\n", "hints_text": "", "created_at": "2023-04-21T13:47:31Z", "version": "0.39", "FAIL_TO_PASS": ["tests/test_grid.py::test_create_rectilinear_grid_from_specs"], "PASS_TO_PASS": ["tests/test_grid.py::test_volume", "tests/test_grid.py::test_init_from_polydata", "tests/test_grid.py::test_init_from_structured", "tests/test_grid.py::test_init_from_unstructured", "tests/test_grid.py::test_init_from_numpy_arrays", "tests/test_grid.py::test_init_bad_input", "tests/test_grid.py::test_init_from_arrays[False]", "tests/test_grid.py::test_init_from_arrays[True]", "tests/test_grid.py::test_init_from_dict[False-False]", "tests/test_grid.py::test_init_from_dict[False-True]", "tests/test_grid.py::test_init_from_dict[True-False]", "tests/test_grid.py::test_init_from_dict[True-True]", "tests/test_grid.py::test_init_polyhedron", "tests/test_grid.py::test_cells_dict_hexbeam_file", "tests/test_grid.py::test_cells_dict_variable_length", "tests/test_grid.py::test_cells_dict_empty_grid", "tests/test_grid.py::test_cells_dict_alternating_cells", "tests/test_grid.py::test_destructor", "tests/test_grid.py::test_surface_indices", "tests/test_grid.py::test_extract_feature_edges", "tests/test_grid.py::test_triangulate_inplace", "tests/test_grid.py::test_save[.vtu-True]", "tests/test_grid.py::test_save[.vtu-False]", "tests/test_grid.py::test_save[.vtk-True]", "tests/test_grid.py::test_save[.vtk-False]", "tests/test_grid.py::test_pathlib_read_write", "tests/test_grid.py::test_init_bad_filename", "tests/test_grid.py::test_save_bad_extension", "tests/test_grid.py::test_linear_copy", "tests/test_grid.py::test_linear_copy_surf_elem", "tests/test_grid.py::test_extract_cells[True]", "tests/test_grid.py::test_extract_cells[False]", "tests/test_grid.py::test_merge", "tests/test_grid.py::test_merge_not_main", "tests/test_grid.py::test_merge_list", "tests/test_grid.py::test_merge_invalid", "tests/test_grid.py::test_init_structured_raise", "tests/test_grid.py::test_init_structured", "tests/test_grid.py::test_no_copy_polydata_init", "tests/test_grid.py::test_no_copy_polydata_points_setter", "tests/test_grid.py::test_no_copy_structured_mesh_init", "tests/test_grid.py::test_no_copy_structured_mesh_points_setter", "tests/test_grid.py::test_no_copy_pointset_init", "tests/test_grid.py::test_no_copy_pointset_points_setter", "tests/test_grid.py::test_no_copy_unstructured_grid_points_setter", "tests/test_grid.py::test_no_copy_rectilinear_grid", "tests/test_grid.py::test_grid_repr", "tests/test_grid.py::test_slice_structured", "tests/test_grid.py::test_invalid_init_structured", "tests/test_grid.py::test_save_structured[.vtk-True]", "tests/test_grid.py::test_save_structured[.vtk-False]", "tests/test_grid.py::test_save_structured[.vts-True]", "tests/test_grid.py::test_save_structured[.vts-False]", "tests/test_grid.py::test_load_structured_bad_filename", "tests/test_grid.py::test_instantiate_by_filename", "tests/test_grid.py::test_create_rectilinear_after_init", "tests/test_grid.py::test_create_rectilinear_grid_from_file", "tests/test_grid.py::test_read_rectilinear_grid_from_file", "tests/test_grid.py::test_read_rectilinear_grid_from_pathlib", "tests/test_grid.py::test_raise_rectilinear_grid_non_unique", "tests/test_grid.py::test_cast_rectilinear_grid", "tests/test_grid.py::test_create_uniform_grid_from_specs", "tests/test_grid.py::test_uniform_grid_invald_args", "tests/test_grid.py::test_uniform_setters", "tests/test_grid.py::test_create_uniform_grid_from_file", "tests/test_grid.py::test_read_uniform_grid_from_file", "tests/test_grid.py::test_read_uniform_grid_from_pathlib", "tests/test_grid.py::test_cast_uniform_to_structured", "tests/test_grid.py::test_cast_uniform_to_rectilinear", "tests/test_grid.py::test_uniform_grid_to_tetrahedra", "tests/test_grid.py::test_fft_and_rfft", "tests/test_grid.py::test_fft_low_pass", "tests/test_grid.py::test_fft_high_pass", "tests/test_grid.py::test_save_rectilinear[.vtk-True]", "tests/test_grid.py::test_save_rectilinear[.vtk-False]", "tests/test_grid.py::test_save_rectilinear[.vtr-True]", "tests/test_grid.py::test_save_rectilinear[.vtr-False]", "tests/test_grid.py::test_save_uniform[.vtk-True]", "tests/test_grid.py::test_save_uniform[.vtk-False]", "tests/test_grid.py::test_save_uniform[.vti-True]", "tests/test_grid.py::test_save_uniform[.vti-False]", "tests/test_grid.py::test_grid_points", "tests/test_grid.py::test_grid_extract_selection_points", "tests/test_grid.py::test_gaussian_smooth", "tests/test_grid.py::test_remove_cells[ind0]", "tests/test_grid.py::test_remove_cells[ind1]", "tests/test_grid.py::test_remove_cells[ind2]", "tests/test_grid.py::test_remove_cells_not_inplace[ind0]", "tests/test_grid.py::test_remove_cells_not_inplace[ind1]", "tests/test_grid.py::test_remove_cells_not_inplace[ind2]", "tests/test_grid.py::test_remove_cells_invalid", "tests/test_grid.py::test_hide_cells[ind0]", "tests/test_grid.py::test_hide_cells[ind1]", "tests/test_grid.py::test_hide_cells[ind2]", "tests/test_grid.py::test_hide_points[ind0]", "tests/test_grid.py::test_hide_points[ind1]", "tests/test_grid.py::test_hide_points[ind2]", "tests/test_grid.py::test_set_extent", "tests/test_grid.py::test_UnstructuredGrid_cast_to_explicit_structured_grid", "tests/test_grid.py::test_ExplicitStructuredGrid_init", "tests/test_grid.py::test_ExplicitStructuredGrid_cast_to_unstructured_grid", "tests/test_grid.py::test_ExplicitStructuredGrid_save", "tests/test_grid.py::test_ExplicitStructuredGrid_hide_cells", "tests/test_grid.py::test_ExplicitStructuredGrid_show_cells", "tests/test_grid.py::test_ExplicitStructuredGrid_dimensions", "tests/test_grid.py::test_ExplicitStructuredGrid_visible_bounds", "tests/test_grid.py::test_ExplicitStructuredGrid_cell_id", "tests/test_grid.py::test_ExplicitStructuredGrid_cell_coords", "tests/test_grid.py::test_ExplicitStructuredGrid_neighbors", "tests/test_grid.py::test_ExplicitStructuredGrid_compute_connectivity", "tests/test_grid.py::test_ExplicitStructuredGrid_compute_connections", "tests/test_grid.py::test_ExplicitStructuredGrid_raise_init", "tests/test_grid.py::test_copy_no_copy_wrap_object", "tests/test_grid.py::test_copy_no_copy_wrap_object_vtk9"], "environment_setup_commit": "4c2d1aed10b1600d520271beba8579c71433e808"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-996", "base_commit": "d21e97c9a35b5c225dc3340faaa7c293e7c8ee9b", "patch": "diff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -769,13 +769,7 @@ def __getattr__(self, name):\n if tag is not None: # `name` isn't a DICOM element keyword\n tag = Tag(tag)\n if tag in self._dict: # DICOM DataElement not in the Dataset\n- data_elem = self[tag]\n- value = data_elem.value\n- if data_elem.VR == 'SQ':\n- # let a sequence know its parent dataset, as sequence items\n- # may need parent dataset tags to resolve ambiguous tags\n- value.parent = self\n- return value\n+ return self[tag].value\n \n # no tag or tag not contained in the dataset\n if name == '_dict':\n@@ -854,6 +848,10 @@ def __getitem__(self, key):\n data_elem = self._dict[tag]\n \n if isinstance(data_elem, DataElement):\n+ if data_elem.VR == 'SQ' and data_elem.value:\n+ # let a sequence know its parent dataset, as sequence items\n+ # may need parent dataset tags to resolve ambiguous tags\n+ data_elem.value.parent = self\n return data_elem\n elif isinstance(data_elem, tuple):\n # If a deferred read, then go get the value now\n@@ -1289,7 +1287,7 @@ def convert_pixel_data(self, handler_name=''):\n Raises\n ------\n ValueError\n- If `name` is not a valid handler name.\n+ If `handler_name` is not a valid handler name.\n NotImplementedError\n If the given handler or any handler, if none given, is able to\n decompress pixel data with the current transfer syntax\ndiff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -70,8 +70,8 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):\n # For references, see the list at\n # https://github.com/darcymason/pydicom/pull/298\n # PixelRepresentation is usually set in the root dataset\n- while 'PixelRepresentation' not in ds and ds.parent:\n- ds = ds.parent\n+ while 'PixelRepresentation' not in ds and ds.parent and ds.parent():\n+ ds = ds.parent()\n # if no pixel data is present, none if these tags is used,\n # so we can just ignore a missing PixelRepresentation in this case\n if ('PixelRepresentation' not in ds and 'PixelData' not in ds or\ndiff --git a/pydicom/sequence.py b/pydicom/sequence.py\n--- a/pydicom/sequence.py\n+++ b/pydicom/sequence.py\n@@ -3,6 +3,7 @@\n \n Sequence is a list of pydicom Dataset objects.\n \"\"\"\n+import weakref\n \n from pydicom.dataset import Dataset\n from pydicom.multival import MultiValue\n@@ -57,7 +58,8 @@ def __init__(self, iterable=None):\n \n @property\n def parent(self):\n- \"\"\"Return the parent :class:`~pydicom.dataset.Dataset`.\"\"\"\n+ \"\"\"Return a weak reference to the parent\n+ :class:`~pydicom.dataset.Dataset`.\"\"\"\n return self._parent\n \n @parent.setter\n@@ -66,7 +68,7 @@ def parent(self, value):\n :class:`Sequence` items.\n \"\"\"\n if value != self._parent:\n- self._parent = value\n+ self._parent = weakref.ref(value)\n for item in self._list:\n item.parent = self._parent\n \n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -875,47 +875,90 @@ def test_write_new_ambiguous(self):\n assert ds[0x00283002].VR == 'US'\n assert ds.LUTDescriptor == [1, 0]\n \n- def test_ambiguous_element_in_sequence_explicit(self):\n- \"\"\"Test that writing a sequence with an ambiguous element\n- as explicit transfer syntax works.\"\"\"\n- # regression test for #804\n+ def dataset_with_modality_lut_sequence(self, pixel_repr):\n ds = Dataset()\n- ds.PixelRepresentation = 0\n+ ds.PixelRepresentation = pixel_repr\n ds.ModalityLUTSequence = [Dataset()]\n ds.ModalityLUTSequence[0].LUTDescriptor = [0, 0, 16]\n ds.ModalityLUTSequence[0].LUTExplanation = None\n ds.ModalityLUTSequence[0].ModalityLUTType = 'US' # US = unspecified\n ds.ModalityLUTSequence[0].LUTData = b'\\x0000\\x149a\\x1f1c\\xc2637'\n-\n ds.is_little_endian = True\n+ return ds\n+\n+ def test_ambiguous_element_in_sequence_explicit_using_attribute(self):\n+ \"\"\"Test that writing a sequence with an ambiguous element\n+ as explicit transfer syntax works if accessing the tag via keyword.\"\"\"\n+ # regression test for #804\n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=0)\n ds.is_implicit_VR = False\n fp = BytesIO()\n ds.save_as(fp, write_like_original=True)\n-\n ds = dcmread(fp, force=True)\n assert 'US' == ds.ModalityLUTSequence[0][0x00283002].VR\n \n- def test_ambiguous_element_in_sequence_implicit(self):\n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=1)\n+ ds.is_implicit_VR = False\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+ ds = dcmread(fp, force=True)\n+ assert 'SS' == ds.ModalityLUTSequence[0][0x00283002].VR\n+\n+ def test_ambiguous_element_in_sequence_explicit_using_index(self):\n+ \"\"\"Test that writing a sequence with an ambiguous element\n+ as explicit transfer syntax works if accessing the tag\n+ via the tag number.\"\"\"\n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=0)\n+ ds.is_implicit_VR = False\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+ ds = dcmread(fp, force=True)\n+ assert 'US' == ds[0x00283000][0][0x00283002].VR\n+\n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=1)\n+ ds.is_implicit_VR = False\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+ ds = dcmread(fp, force=True)\n+ assert 'SS' == ds[0x00283000][0][0x00283002].VR\n+\n+ def test_ambiguous_element_in_sequence_implicit_using_attribute(self):\n \"\"\"Test that reading a sequence with an ambiguous element\n- from a file with implicit transfer syntax works.\"\"\"\n+ from a file with implicit transfer syntax works if accessing the\n+ tag via keyword.\"\"\"\n # regression test for #804\n- ds = Dataset()\n- ds.PixelRepresentation = 0\n- ds.ModalityLUTSequence = [Dataset()]\n- ds.ModalityLUTSequence[0].LUTDescriptor = [0, 0, 16]\n- ds.ModalityLUTSequence[0].LUTExplanation = None\n- ds.ModalityLUTSequence[0].ModalityLUTType = 'US' # US = unspecified\n- ds.ModalityLUTSequence[0].LUTData = b'\\x0000\\x149a\\x1f1c\\xc2637'\n-\n- ds.is_little_endian = True\n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=0)\n ds.is_implicit_VR = True\n fp = BytesIO()\n ds.save_as(fp, write_like_original=True)\n ds = dcmread(fp, force=True)\n- # we first have to access the value to trigger correcting the VR\n- assert 16 == ds.ModalityLUTSequence[0].LUTDescriptor[2]\n assert 'US' == ds.ModalityLUTSequence[0][0x00283002].VR\n \n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=1)\n+ ds.is_implicit_VR = True\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+ ds = dcmread(fp, force=True)\n+ assert 'SS' == ds.ModalityLUTSequence[0][0x00283002].VR\n+\n+ def test_ambiguous_element_in_sequence_implicit_using_index(self):\n+ \"\"\"Test that reading a sequence with an ambiguous element\n+ from a file with implicit transfer syntax works if accessing the tag\n+ via the tag number.\"\"\"\n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=0)\n+ ds.is_implicit_VR = True\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+ ds = dcmread(fp, force=True)\n+ assert 'US' == ds[0x00283000][0][0x00283002].VR\n+\n+ ds = self.dataset_with_modality_lut_sequence(pixel_repr=1)\n+ ds.is_implicit_VR = True\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+ ds = dcmread(fp, force=True)\n+ assert 'SS' == ds[0x00283000][0][0x00283002].VR\n+\n \n class TestCorrectAmbiguousVRElement(object):\n \"\"\"Test filewriter.correct_ambiguous_vr_element\"\"\"\n", "problem_statement": "Memory leaks when accessing sequence tags with Dataset.__getattr__.\n**Describe the bug**\r\nAccessing sequences via `Dataset.__getattr__` seems to leak memory. The bug occurred for me when I was processing many DICOMs and manipulating some tags contained in sequences and each leaked a bit of memory, ultimately crashing the process.\r\n\r\n**Expected behavior**\r\nMemory should not leak. It works correctly when you replace the `__getattr__` call with `__getitem__` (by manually constructing the necessary tag beforehand).\r\n\r\nWithout being an expert in the codebase, one difference I think that could explain it is that `__getattr__` sets `value.parent = self` for sequences while `__getitem__` doesn't seem to do that. Maybe this loop of references somehow confuses Python's garbage collection?\r\n\r\n**Steps To Reproduce**\r\nThis increases the memory consumption of the Python process by about 700 MB on my machine. The DICOM file I've tested it with is 27MB and has one item in `SourceImageSequence`. Note that the memory leak plateaus after a while in this example, maybe because it's the same file. In my actual workflow when iterating over many different files, the process filled all memory and crashed.\r\n\r\n```python\r\nimport pydicom\r\nfor i in range(100):\r\n dcm = pydicom.dcmread(\"my_dicom.dcm\")\r\n test = dcm.SourceImageSequence\r\n```\r\n\r\nFor comparison, this keeps the memory constant. `(0x0008, 0x2112)` is `SourceImageSequence`: \r\n\r\n```python\r\nimport pydicom\r\nimport pydicom.tag\r\nfor i in range(100):\r\n dcm = pydicom.dcmread(\"my_dicom.dcm\")\r\n test = dcm[pydicom.tag.TupleTag((0x0008, 0x2112))]\r\n```\r\n\r\n**Your environment**\r\n\r\n```bash\r\nLinux-4.15.0-72-generic-x86_64-with-Ubuntu-18.04-bionic\r\nPython 3.6.8 (default, Jan 14 2019, 11:02:34)\r\npydicom 1.3.0\r\n```\r\n\n", "hints_text": "I could reproduce this with a smaller sequence (2MB) under Windows. The memory usage got up until it was about twice the initial value (after a few hundred iterations), after that got back down to the initial value and started to rise again.\r\nIf removing the code that sets the parent, this does not happen - the memory remains at the initial value.\r\nSo, your assessment about the garbage collection delayed due to cyclic references seems to be correct.\r\nI will have a look how to resolve this - probably later this week.\nI'm not seeing any memory leakage using [memory-profiler](https://pypi.org/project/memory-profiler/). What are you using to profile?\r\n\r\nI get similar results (~38 MB, no sign of gradual increase) for each of the following branches and Python 3.6.5, current `master`:\r\n```python\r\nimport time\r\nfrom pydicom import dcmread\r\nfrom pydicom.data import get_testdata_file\r\n\r\nfname = get_testdata_file(\"rtplan.dcm\")\r\nbranch = 'A'\r\n\r\nif branch == 'A':\r\n for ii in range(1):\r\n ds = dcmread(fname)\r\nelif branch == 'B':\r\n for ii in range(1):\r\n ds = dcmread(fname)\r\n seq = ds.BeamSequence\r\nelif branch == 'C':\r\n for ii in range(10000):\r\n ds = dcmread(fname)\r\nelif branch == 'D':\r\n for ii in range(10000):\r\n ds = dcmread(fname)\r\n seq = ds.BeamSequence\r\nelif branch == 'E':\r\n for ii in range(10000):\r\n ds = dcmread(fname)\r\n seq = ds[0x300a, 0x00b0].value\r\n\r\ntime.sleep(1)\r\n```\r\nIt looks like there's a bit of overhead for ds.BeamSequence but not a lot?\n@scaramallion - I didn't use a profiler, just watched the private memory consumption. I can add a screenshot if I get to it tonight. A couple of remarks:\r\n- there is no real leak here, as the memory is freed eventually, just not immediately as with the scenario without setting a parent\r\n- the test data you used is quite small - I used a real rtstruct file for the test with a sequence of about 2MB size, so that is more visible in this case\r\n- not setting the parent didn't fail any test, so while I'm sure there was a scenario where this was not needed, there is no tests for it; I have to check if and when this is really needed\r\n- the solution is not complete anyway, as with the access via `__getitem__` the parent is not set", "created_at": "2019-12-18T20:51:14Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1241", "base_commit": "9d69811e539774f296c2f289839147e741251716", "patch": "diff --git a/pydicom/encaps.py b/pydicom/encaps.py\n--- a/pydicom/encaps.py\n+++ b/pydicom/encaps.py\n@@ -77,13 +77,15 @@ def get_frame_offsets(fp: DicomFileLike) -> Tuple[bool, List[int]]:\n tag = Tag(fp.read_tag())\n \n if tag != 0xfffee000:\n- raise ValueError(\"Unexpected tag '{}' when parsing the Basic Table \"\n- \"Offset item.\".format(tag))\n+ raise ValueError(\n+ f\"Unexpected tag '{tag}' when parsing the Basic Table Offset item\"\n+ )\n \n length = fp.read_UL()\n if length % 4:\n- raise ValueError(\"The length of the Basic Offset Table item is not \"\n- \"a multiple of 4.\")\n+ raise ValueError(\n+ \"The length of the Basic Offset Table item is not a multiple of 4\"\n+ )\n \n offsets = []\n # Always return at least a 0 offset\n@@ -116,18 +118,20 @@ def get_nr_fragments(fp: DicomFileLike) -> int:\n # Item\n length = fp.read_UL()\n if length == 0xFFFFFFFF:\n- raise ValueError(\"Undefined item length at offset {} when \"\n- \"parsing the encapsulated pixel data \"\n- \"fragments.\".format(fp.tell() - 4))\n+ raise ValueError(\n+ f\"Undefined item length at offset {fp.tell() - 4} when \"\n+ \"parsing the encapsulated pixel data fragments\"\n+ )\n fp.seek(length, 1)\n nr_fragments += 1\n elif tag == 0xFFFEE0DD:\n # Sequence Delimiter\n break\n else:\n- raise ValueError(\"Unexpected tag '{}' at offset {} when parsing \"\n- \"the encapsulated pixel data fragment items.\"\n- .format(tag, fp.tell() - 4))\n+ raise ValueError(\n+ f\"Unexpected tag '{tag}' at offset {fp.tell() - 4} when \"\n+ \"parsing the encapsulated pixel data fragment items\"\n+ )\n \n fp.seek(start)\n return nr_fragments\n@@ -206,9 +210,10 @@ def generate_pixel_data_fragment(\n # Item\n length = fp.read_UL()\n if length == 0xFFFFFFFF:\n- raise ValueError(\"Undefined item length at offset {} when \"\n- \"parsing the encapsulated pixel data \"\n- \"fragments.\".format(fp.tell() - 4))\n+ raise ValueError(\n+ f\"Undefined item length at offset {fp.tell() - 4} when \"\n+ \"parsing the encapsulated pixel data fragments\"\n+ )\n yield fp.read(length)\n elif tag == 0xFFFEE0DD:\n # Sequence Delimiter\n@@ -216,9 +221,10 @@ def generate_pixel_data_fragment(\n fp.seek(-4, 1)\n break\n else:\n- raise ValueError(\"Unexpected tag '{0}' at offset {1} when parsing \"\n- \"the encapsulated pixel data fragment items.\"\n- .format(tag, fp.tell() - 4))\n+ raise ValueError(\n+ f\"Unexpected tag '{tag}' at offset {fp.tell() - 4} when \"\n+ \"parsing the encapsulated pixel data fragment items\"\n+ )\n \n \n def generate_pixel_data_frame(\n@@ -549,8 +555,10 @@ def fragment_frame(\n frame_length = len(frame)\n # Add 1 to fix odd length frames not being caught\n if nr_fragments > (frame_length + 1) / 2.0:\n- raise ValueError('Too many fragments requested (the minimum fragment '\n- 'size is 2 bytes)')\n+ raise ValueError(\n+ \"Too many fragments requested (the minimum fragment size is \"\n+ \"2 bytes)\"\n+ )\n \n length = int(frame_length / nr_fragments)\n \n@@ -596,7 +604,7 @@ def itemize_fragment(fragment: bytes) -> bytes:\n a 4 byte length.\n \"\"\"\n # item tag (fffe,e000)\n- item = bytes(b'\\xFE\\xFF\\x00\\xE0')\n+ item = b'\\xFE\\xFF\\x00\\xE0'\n # fragment length '<I' little endian, 4 byte unsigned int\n item += pack('<I', len(fragment))\n # fragment data\n@@ -640,7 +648,7 @@ def itemize_frame(\n :dcm:`Annex A.4 <part05/sect_A.4.html>`\n \"\"\"\n for fragment in fragment_frame(frame, nr_fragments):\n- yield itemise_fragment(fragment)\n+ yield itemize_fragment(fragment)\n \n \n itemise_frame = itemize_frame\n@@ -664,6 +672,16 @@ def encapsulate(\n For multi-frame data each frame must be encoded separately and then all\n encoded frames encapsulated together.\n \n+ When many large frames are to be encapsulated, the total length of\n+ encapsulated data may exceed the maximum length available with the\n+ :dcm:`Basic Offset Table<part05/sect_A.4.html>` (2**31 - 1 bytes). Under\n+ these circumstances you can:\n+\n+ * Pass ``has_bot=False`` to :func:`~pydicom.encaps.encapsulate`\n+ * Use :func:`~pydicom.encaps.encapsulate_extended` and add the\n+ :dcm:`Extended Offset Table<part03/sect_C.7.6.3.html>` elements to your\n+ dataset (recommended)\n+\n Data will be encapsulated with a Basic Offset Table Item at the beginning,\n then one or more fragment items. Each item will be of even length and the\n final fragment of each frame may be padded with ``0x00`` if required.\n@@ -688,18 +706,33 @@ def encapsulate(\n ----------\n DICOM Standard, Part 5, :dcm:`Section 7.5 <part05/sect_7.5.html>` and\n :dcm:`Annex A.4 <part05/sect_A.4.html>`\n+\n+ See Also\n+ --------\n+ :func:`~pydicom.encaps.encapsulate_extended`\n \"\"\"\n- no_frames = len(frames)\n+ nr_frames = len(frames)\n output = bytearray()\n \n # Add the Basic Offset Table Item\n # Add the tag\n output.extend(b'\\xFE\\xFF\\x00\\xE0')\n if has_bot:\n+ # Check that the 2**32 - 1 limit in BOT item lengths won't be exceeded\n+ total = (nr_frames - 1) * 8 + sum([len(f) for f in frames[:-1]])\n+ if total > 2**32 - 1:\n+ raise ValueError(\n+ f\"The total length of the encapsulated frame data ({total} \"\n+ \"bytes) will be greater than the maximum allowed by the Basic \"\n+ f\"Offset Table ({2**32 - 1} bytes), it's recommended that you \"\n+ \"use the Extended Offset Table instead (see the \"\n+ \"'encapsulate_extended' function for more information)\"\n+ )\n+\n # Add the length\n- output.extend(pack('<I', 4 * no_frames))\n+ output.extend(pack('<I', 4 * nr_frames))\n # Reserve 4 x len(frames) bytes for the offsets\n- output.extend(b'\\xFF\\xFF\\xFF\\xFF' * no_frames)\n+ output.extend(b'\\xFF\\xFF\\xFF\\xFF' * nr_frames)\n else:\n # Add the length\n output.extend(pack('<I', 0))\n@@ -708,7 +741,7 @@ def encapsulate(\n for ii, frame in enumerate(frames):\n # `itemised_length` is the total length of each itemised frame\n itemised_length = 0\n- for item in itemise_frame(frame, fragments_per_frame):\n+ for item in itemize_frame(frame, fragments_per_frame):\n itemised_length += len(item)\n output.extend(item)\n \n@@ -717,7 +750,67 @@ def encapsulate(\n \n if has_bot:\n # Go back and write the frame offsets - don't need the last offset\n- output[8:8 + 4 * no_frames] = pack('<{}I'.format(no_frames),\n- *bot_offsets[:-1])\n+ output[8:8 + 4 * nr_frames] = pack(f\"<{nr_frames}I\", *bot_offsets[:-1])\n \n return bytes(output)\n+\n+\n+def encapsulate_extended(frames: List[bytes]) -> Tuple[bytes, bytes, bytes]:\n+ \"\"\"Return encapsulated image data and values for the Extended Offset Table\n+ elements.\n+\n+ When using a compressed transfer syntax (such as RLE Lossless or one of\n+ JPEG formats) then any *Pixel Data* must be :dcm:`encapsulated\n+ <part05/sect_A.4.html>`. When many large frames are to be encapsulated, the\n+ total length of encapsulated data may exceed the maximum length available\n+ with the :dcm:`Basic Offset Table<part05/sect_A.4.html>` (2**32 - 1 bytes).\n+ Under these circumstances you can:\n+\n+ * Pass ``has_bot=False`` to :func:`~pydicom.encaps.encapsulate`\n+ * Use :func:`~pydicom.encaps.encapsulate_extended` and add the\n+ :dcm:`Extended Offset Table<part03/sect_C.7.6.3.html>` elements to your\n+ dataset (recommended)\n+\n+ Examples\n+ --------\n+\n+ .. code-block:: python\n+\n+ from pydicom.encaps import encapsulate_extended\n+\n+ # 'frames' is a list of image frames that have been each been encoded\n+ # separately using the compression method corresponding to the Transfer\n+ # Syntax UID\n+ frames: List[bytes] = [...]\n+ out: Tuple[bytes, bytes, bytes] = encapsulate_extended(frames)\n+\n+ ds.PixelData = out[0]\n+ ds.ExtendedOffsetTable = out[1]\n+ ds.ExtendedOffsetTableLengths = out[2]\n+\n+ Parameters\n+ ----------\n+ frames : list of bytes\n+ The compressed frame data to encapsulate, one frame per item.\n+\n+ Returns\n+ -------\n+ bytes, bytes, bytes\n+ The (encapsulated frames, extended offset table, extended offset\n+ table lengths).\n+\n+ See Also\n+ --------\n+ :func:`~pydicom.encaps.encapsulate`\n+ \"\"\"\n+ nr_frames = len(frames)\n+ frame_lengths = [len(frame) for frame in frames]\n+ frame_offsets = [0]\n+ for ii, length in enumerate(frame_lengths[:-1]):\n+ # Extra 8 bytes for the Item tag and length\n+ frame_offsets.append(frame_offsets[ii] + length + 8)\n+\n+ offsets = pack(f\"<{nr_frames}Q\", *frame_offsets)\n+ lengths = pack(f\"<{nr_frames}Q\", *frame_lengths)\n+\n+ return encapsulate(frames, has_bot=False), offsets, lengths\n", "test_patch": "diff --git a/pydicom/tests/test_encaps.py b/pydicom/tests/test_encaps.py\n--- a/pydicom/tests/test_encaps.py\n+++ b/pydicom/tests/test_encaps.py\n@@ -1,6 +1,8 @@\n-# Copyright 2008-2018 pydicom authors. See LICENSE file for details.\n+# Copyright 2008-2020 pydicom authors. See LICENSE file for details.\n \"\"\"Test for encaps.py\"\"\"\n \n+from struct import unpack\n+\n import pytest\n \n from pydicom import dcmread\n@@ -16,7 +18,8 @@\n read_item,\n fragment_frame,\n itemise_frame,\n- encapsulate\n+ encapsulate,\n+ encapsulate_extended\n )\n from pydicom.filebase import DicomBytesIO\n \n@@ -36,7 +39,7 @@ def test_bad_tag(self):\n fp.is_little_endian = True\n with pytest.raises(ValueError,\n match=r\"Unexpected tag '\\(fffe, e100\\)' when \"\n- r\"parsing the Basic Table Offset item.\"):\n+ r\"parsing the Basic Table Offset item\"):\n get_frame_offsets(fp)\n \n def test_bad_length_multiple(self):\n@@ -49,7 +52,7 @@ def test_bad_length_multiple(self):\n fp.is_little_endian = True\n with pytest.raises(ValueError,\n match=\"The length of the Basic Offset Table item\"\n- \" is not a multiple of 4.\"):\n+ \" is not a multiple of 4\"):\n get_frame_offsets(fp)\n \n def test_zero_length(self):\n@@ -138,7 +141,7 @@ def test_item_bad_tag(self):\n fp.is_little_endian = True\n msg = (\n r\"Unexpected tag '\\(0010, 0010\\)' at offset 12 when parsing the \"\n- r\"encapsulated pixel data fragment items.\"\n+ r\"encapsulated pixel data fragment items\"\n )\n with pytest.raises(ValueError, match=msg):\n get_nr_fragments(fp)\n@@ -212,7 +215,7 @@ def test_item_undefined_length(self):\n with pytest.raises(ValueError,\n match=\"Undefined item length at offset 4 when \"\n \"parsing the encapsulated pixel data \"\n- \"fragments.\"):\n+ \"fragments\"):\n next(fragments)\n pytest.raises(StopIteration, next, fragments)\n \n@@ -249,8 +252,7 @@ def test_item_bad_tag(self):\n with pytest.raises(ValueError,\n match=r\"Unexpected tag '\\(0010, 0010\\)' at offset \"\n r\"12 when parsing the encapsulated pixel \"\n- r\"data \"\n- r\"fragment items.\"):\n+ r\"data fragment items\"):\n next(fragments)\n pytest.raises(StopIteration, next, fragments)\n \n@@ -1199,3 +1201,63 @@ def test_encapsulate_bot(self):\n b'\\xfe\\xff\\x00\\xe0' # Next item tag\n b'\\xe6\\x0e\\x00\\x00' # Next item length\n )\n+\n+ def test_encapsulate_bot_large_raises(self):\n+ \"\"\"Test exception raised if too much pixel data for BOT.\"\"\"\n+\n+ class FakeBytes(bytes):\n+ length = -1\n+\n+ def __len__(self):\n+ return self.length\n+\n+ def __getitem__(self, s):\n+ return b'\\x00' * 5\n+\n+ frame_a = FakeBytes()\n+ frame_a.length = 2**32 - 1 - 8 # 8 for first BOT item tag/length\n+ frame_b = FakeBytes()\n+ frame_b.length = 10\n+ data = encapsulate([frame_a, frame_b], has_bot=True)\n+\n+ frame_a.length = 2**32 - 1 - 7\n+ msg = (\n+ r\"The total length of the encapsulated frame data \\(4294967296 \"\n+ r\"bytes\\) will be greater than the maximum allowed by the Basic \"\n+ )\n+ with pytest.raises(ValueError, match=msg):\n+ encapsulate([frame_a, frame_b], has_bot=True)\n+\n+\n+class TestEncapsulateExtended:\n+ \"\"\"Tests for encaps.encapsulate_extended.\"\"\"\n+ def test_encapsulate(self):\n+ ds = dcmread(JP2K_10FRAME_NOBOT)\n+ frames = decode_data_sequence(ds.PixelData)\n+ assert len(frames) == 10\n+\n+ out = encapsulate_extended(frames)\n+ # Pixel Data encapsulated OK\n+ assert isinstance(out[0], bytes)\n+ test_frames = decode_data_sequence(out[0])\n+ for a, b in zip(test_frames, frames):\n+ assert a == b\n+\n+ # Extended Offset Table is OK\n+ assert isinstance(out[1], bytes)\n+ assert [\n+ 0x0000, # 0\n+ 0x0eee, # 3822\n+ 0x1df6, # 7670\n+ 0x2cf8, # 11512\n+ 0x3bfc, # 15356\n+ 0x4ade, # 19166\n+ 0x59a2, # 22946\n+ 0x6834, # 26676\n+ 0x76e2, # 30434\n+ 0x8594 # 34196\n+ ] == list(unpack('<10Q', out[1]))\n+\n+ # Extended Offset Table Lengths are OK\n+ assert isinstance(out[2], bytes)\n+ assert [len(f) for f in frames] == list(unpack('<10Q', out[2]))\n", "problem_statement": "Add support for Extended Offset Table to encaps module\n[CP1818](http://webcache.googleusercontent.com/search?q=cache:xeWXtrAs9G4J:ftp://medical.nema.org/medical/dicom/final/cp1818_ft_whenoffsettabletoosmall.pdf) added the use of an Extended Offset Table for encapsulated pixel data when the Basic Offset Table isn't suitable.\n", "hints_text": "Some notes for myself:\r\n\r\n* The EOT is optional and intended to support users where there are multiple compressed frames and the total length of all the frames exceeds the `2**32 - 1` limit available in the BOT item lengths. \r\n* Only 1 fragment per frame is allowed with an EOT\r\n* The *Extended Table Offset Lengths* is the length (in bytes) of each compressed frame\r\n* It's not usable where each compressed frame is larger than `2**32 - 1` due to the limit in the 4-byte (FFFE,E000) Item Tag length (who has 4 GB compressed images anyway?)\r\n\r\nRelevant links: [google groups issue](https://groups.google.com/forum/?nomobile=true#!searchin/comp.protocols.dicom/extended$20offset|sort:date/comp.protocols.dicom/piMk2TmcyEg/daCk33zDBwAJ), [Image Pixel module](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html), [BOT](http://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_A.4.html)\r\n\r\nImplementation shouldn't be difficult, something along the lines of:\r\n```python\r\nfrom struct import pack\r\nfrom pydicom.encaps import encapsulate\r\n\r\nframe_data: List[bytes] = [...]\r\nds.PixelData = encapsulate(frame_data, has_bot=False, fragments_per_frame=1)\r\n\r\nframe_lengths = [len(f) for f in frame_data]\r\nframe_offsets = [0]\r\nfor ii, length in enumerate(frame_lengths[:-1]):\r\n frame_offsets .append(frame_offsets [ii] + length + 8)\r\nds.ExtendedOffsetTable = pack(\"<{len(frame_offsets )}Q\", *frame_offsets )\r\nds.ExtendedOffsetTableLengths = pack(\"<{len(frame_lengths)}Q\", *frame_lengths)\r\n```\r\n\r\nMaybe just add a helper function to ensure conformance? And add a check to `encapsulate()` for data that's too long.\r\n```python\r\nfrom pydicom.encaps import encapsulate_extended\r\n\r\nout: Tuple[bytes, bytes, bytes] = encapsulate_extended(frame_data)\r\nds.PixelData = out[0]\r\nds.ExtendedOffsetTable = out[1]\r\nds.ExtendedOffsetTableLengths = out[2]\r\n```\r\n\r\nParsing should already be handled correctly by `generate_pixel_data()` since it's 1 frame per fragment.", "created_at": "2020-10-30T01:59:32Z", "version": "2.0", "FAIL_TO_PASS": ["pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_bad_tag", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_bad_length_multiple", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_zero_length", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_multi_frame", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_single_frame", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_not_little_endian", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_item_undefined_length", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_item_sequence_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_item_bad_tag", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_single_fragment_no_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_multi_fragments_no_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_single_fragment_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_multi_fragments_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_not_little_endian", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_item_undefined_length", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_item_sequence_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_item_bad_tag", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_single_fragment_no_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_multi_fragments_no_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_single_fragment_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_multi_fragments_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_not_little_endian", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_empty_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_empty_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_multi_frame_one_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_multi_frame_three_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_multi_frame_varied_ratio", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_empty_bot_multi_fragments_per_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_no_nr_frames_raises", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_too_few_fragments", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_multi_fragments_per_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_no_marker", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_missing_marker", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_multi_frame_one_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_multi_frame_three_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_multi_frame_varied_ratio", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_empty_bot_single_fragment", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_empty_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_bot_single_fragment", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_multi_frame_one_to_one", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_multi_frame_three_to_one", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_multi_frame_varied_ratio", "pydicom/tests/test_encaps.py::TestDefragmentData::test_defragment", "pydicom/tests/test_encaps.py::TestReadItem::test_item_undefined_length", "pydicom/tests/test_encaps.py::TestReadItem::test_item_sequence_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_item_sequence_delimiter_zero_length", "pydicom/tests/test_encaps.py::TestReadItem::test_item_bad_tag", "pydicom/tests/test_encaps.py::TestReadItem::test_single_fragment_no_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_multi_fragments_no_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_single_fragment_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_multi_fragments_delimiter", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_single_fragment_even_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_single_fragment_odd_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_even_fragment_even_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_even_fragment_odd_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_odd_fragments_even_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_odd_fragments_odd_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_too_many_fragments_raises", "pydicom/tests/test_encaps.py::TestEncapsulateFrame::test_single_item", "pydicom/tests/test_encaps.py::TestEncapsulateFrame::test_two_items", "pydicom/tests/test_encaps.py::TestEncapsulate::test_encapsulate_single_fragment_per_frame_no_bot", "pydicom/tests/test_encaps.py::TestEncapsulate::test_encapsulate_single_fragment_per_frame_bot", "pydicom/tests/test_encaps.py::TestEncapsulate::test_encapsulate_bot", "pydicom/tests/test_encaps.py::TestEncapsulate::test_encapsulate_bot_large_raises", "pydicom/tests/test_encaps.py::TestEncapsulateExtended::test_encapsulate"], "PASS_TO_PASS": [], "environment_setup_commit": "9d69811e539774f296c2f289839147e741251716"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-866", "base_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9", "patch": "diff --git a/pydicom/pixel_data_handlers/numpy_handler.py b/pydicom/pixel_data_handlers/numpy_handler.py\n--- a/pydicom/pixel_data_handlers/numpy_handler.py\n+++ b/pydicom/pixel_data_handlers/numpy_handler.py\n@@ -242,14 +242,20 @@ def get_pixeldata(ds, read_only=False):\n # Check that the actual length of the pixel data is as expected\n actual_length = len(ds.PixelData)\n # Correct for the trailing NULL byte padding for odd length data\n+\n padded_expected_len = expected_len + expected_len % 2\n if actual_length < padded_expected_len:\n- raise ValueError(\n- \"The length of the pixel data in the dataset doesn't match the \"\n- \"expected amount ({0} vs. {1} bytes). The dataset may be \"\n- \"corrupted or there may be an issue with the pixel data handler.\"\n- .format(actual_length, padded_expected_len)\n- )\n+ if actual_length == expected_len:\n+ warnings.warn(\n+ \"The pixel data length is odd and misses a padding byte.\")\n+ else:\n+ raise ValueError(\n+ \"The length of the pixel data in the dataset ({} bytes) \"\n+ \"doesn't match the expected length ({} bytes). \"\n+ \"The dataset may be corrupted or there may be an issue \"\n+ \"with the pixel data handler.\"\n+ .format(actual_length, padded_expected_len)\n+ )\n elif actual_length > padded_expected_len:\n # PS 3.5, Section 8.1.1\n msg = (\n", "test_patch": "diff --git a/pydicom/tests/test_numpy_pixel_data.py b/pydicom/tests/test_numpy_pixel_data.py\n--- a/pydicom/tests/test_numpy_pixel_data.py\n+++ b/pydicom/tests/test_numpy_pixel_data.py\n@@ -986,13 +986,23 @@ def test_bad_length_raises(self):\n # Too short\n ds.PixelData = ds.PixelData[:-1]\n msg = (\n- r\"The length of the pixel data in the dataset doesn't match the \"\n- r\"expected amount \\(479999 vs. 480000 bytes\\). The dataset may be \"\n- r\"corrupted or there may be an issue with the pixel data handler.\"\n+ r\"The length of the pixel data in the dataset \\(479999 bytes\\) \"\n+ r\"doesn't match the expected length \\(480000 bytes\\). \"\n+ r\"The dataset may be corrupted or there may be an issue \"\n+ r\"with the pixel data handler.\"\n )\n with pytest.raises(ValueError, match=msg):\n get_pixeldata(ds)\n \n+ def test_missing_padding_warns(self):\n+ \"\"\"A warning shall be issued if the padding for odd data is missing.\"\"\"\n+ ds = dcmread(EXPL_8_3_1F_ODD)\n+ # remove the padding byte\n+ ds.PixelData = ds.PixelData[:-1]\n+ msg = \"The pixel data length is odd and misses a padding byte.\"\n+ with pytest.warns(UserWarning, match=msg):\n+ get_pixeldata(ds)\n+\n def test_change_photometric_interpretation(self):\n \"\"\"Test get_pixeldata changes PhotometricInterpretation if required.\"\"\"\n def to_rgb(ds):\n", "problem_statement": "Handle odd-sized dicoms with warning\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\n<!-- Example: Attribute Error thrown when printing (0x0010, 0x0020) patient Id> 0-->\r\n\r\nWe have some uncompressed dicoms with an odd number of pixel bytes (saved by older versions of pydicom actually). \r\n\r\nWhen we re-open with pydicom 1.2.2, we're now unable to extract the image, due to the change made by https://github.com/pydicom/pydicom/pull/601\r\n\r\nWould it be possible to emit a warning instead of rejecting the dicom for such cases?\r\n\r\n#### Version\r\n1.2.2\n", "hints_text": "I agree that this would be sensible. Checking the mentioned PR, I also found that we had [discussed this briefly](https://github.com/pydicom/pydicom/pull/601#issuecomment-374710953) (with no result, obviously).\r\n@darcymason - I think this is another case of \"try to handle broken DICOM, only raise in 'strict' mode\", especially as these images have been written by pydicom itself...\nunsponsored plug: I like reviewable.io to keep track of what comments are resolved/unresolved/just-a-nit before merging. Looks like its free for open source repos.\n> @darcymason - I think this is another case of \"try to handle broken DICOM, only raise in 'strict' mode\", especially as these images have been written by pydicom itself...\r\n\r\nYes, I agree, for sure. Even without it being written by pydicom, it is better to be tolerant on reading.", "created_at": "2019-06-21T12:02:05Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_bad_length_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_padding_warns"], "PASS_TO_PASS": ["pydicom/tests/test_numpy_pixel_data.py::test_unsupported_syntaxes", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_supported_dataset", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_pixel_array_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_unsupported_syntax_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_dataset_pixel_array_handler_needs_convert", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_8bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_16bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_32bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame_odd_size", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/liver_1frame.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/liver.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/OBXXXX1A.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_small_odd.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/OBXXXX1A_2frame.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_2frame.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/MR_small.dcm-data7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/emri_small.dcm-data8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_16bit.dcm-data9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_16bit_2frame.dcm-data10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/rtdose_1frame.dcm-data11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/rtdose.dcm-data12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_32bit.dcm-data13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_32bit_2frame.dcm-data14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_3frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame_padded", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_10frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/liver_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/liver_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/liver.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/liver_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/OBXXXX1A.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/OBXXXX1A_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/OBXXXX1A_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/OBXXXX1A_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/MR_small.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/MR_small_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/emri_small.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/emri_small_big_endian.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_16bit.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_expb_16bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_16bit_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_expb_16bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/rtdose_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/rtdose_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/rtdose.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/rtdose_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_32bit.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_expb_32bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_32bit_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.2/pydicom/data/test_files/SC_rgb_expb_32bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_endianness_not_set", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_no_pixel_data_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unknown_pixel_representation_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unsupported_syntaxes_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_change_photometric_interpretation", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only_bit_packed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[-output0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00-output1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01-output2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x02-output3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x04-output4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x08-output5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x10-output6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[@-output8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80-output9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xaa-output10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xf0-output11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x0f-output12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff-output13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x00-output14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x01-output15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x80-output16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\xff-output17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01\\x80-output18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80\\x80-output19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff\\x80-output20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00-input1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x02-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x08-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x10-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80-input9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xaa-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xf0-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x0f-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x00-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x01-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x80-input16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\xff-input17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01\\x80-input18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80\\x80-input19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff\\x80-input20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_non_binary_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_non_array_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00@-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x10-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x08-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x02-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x01-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x80-input7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x10-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x08-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x04-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x02-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x01-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_functional"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1050", "base_commit": "00c248441ffb8b7d46c6d855b723e696a8f5aada", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -741,9 +741,13 @@ def DataElement_from_raw(raw_data_element, encoding=None):\n except NotImplementedError as e:\n raise NotImplementedError(\"{0:s} in tag {1!r}\".format(str(e), raw.tag))\n \n- if raw.tag in _LUT_DESCRIPTOR_TAGS and value[0] < 0:\n+ if raw.tag in _LUT_DESCRIPTOR_TAGS and value:\n # We only fix the first value as the third value is 8 or 16\n- value[0] += 65536\n+ try:\n+ if value[0] < 0:\n+ value[0] += 65536\n+ except TypeError:\n+ pass\n \n return DataElement(raw.tag, VR, value, raw.value_tell,\n raw.length == 0xFFFFFFFF, already_converted=True)\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -674,6 +674,27 @@ def test_lut_descriptor(self):\n assert elem.VR == 'SS'\n assert elem.value == [62720, -2048, 16]\n \n+ def test_lut_descriptor_empty(self):\n+ \"\"\"Regression test for #1049: LUT empty raises.\"\"\"\n+ bs = DicomBytesIO(b'\\x28\\x00\\x01\\x11\\x53\\x53\\x00\\x00')\n+ bs.is_little_endian = True\n+ bs.is_implicit_VR = False\n+ ds = dcmread(bs, force=True)\n+ elem = ds[0x00281101]\n+ assert elem.value is None\n+ assert elem.VR == 'SS'\n+\n+ def test_lut_descriptor_singleton(self):\n+ \"\"\"Test LUT Descriptor with VM = 1\"\"\"\n+ bs = DicomBytesIO(b'\\x28\\x00\\x01\\x11\\x53\\x53\\x02\\x00\\x00\\xf5')\n+ bs.is_little_endian = True\n+ bs.is_implicit_VR = False\n+ ds = dcmread(bs, force=True)\n+ elem = ds[0x00281101]\n+ # No conversion to US if not a triplet\n+ assert elem.value == -2816\n+ assert elem.VR == 'SS'\n+\n \n class TestIncorrectVR(object):\n def setup(self):\n", "problem_statement": "LUT Descriptor tag with no value yields TypeError\n**Describe the bug**\r\nI have a DICOM image with the following tag (copied from ImageJ)\r\n\r\n```\r\n0028,1101 Red Palette Color Lookup Table Descriptor: \r\n```\r\n\r\nwhich corresponds to the raw data element, produced by [`DataElement_from_raw`](https://github.com/pydicom/pydicom/blob/v1.4.1/pydicom/dataelem.py#L699):\r\n```\r\nRawDataElement(tag=(0028, 1101), VR='US', length=0, value=None, value_tell=1850, is_implicit_VR=False, is_little_endian=True)\r\n```\r\n\r\nBecause this tag is matched by the [LUT Descriptor tags](https://github.com/pydicom/pydicom/blob/v1.4.1/pydicom/dataelem.py#L696) and the value is empty (`None`), the [following line](https://github.com/pydicom/pydicom/blob/v1.4.1/pydicom/dataelem.py#L761):\r\n```\r\nif raw.tag in _LUT_DESCRIPTOR_TAGS and value[0] < 0:\r\n```\r\nresults in \r\n```\r\nTypeError: 'NoneType' object is not subscriptable\r\n```\r\n\r\n**Expected behavior**\r\n\r\nGiven that I discovered this by parsing what seems to be a set of faulty DICOMs (mangled pixel data), I'm not sure if an error should be raised if the colour attribute value is not provided.\r\n\r\nHowever, given that `value` can be `None` for other tags, the simple fix is\r\n\r\n```python\r\ntry:\r\n if raw.tag in _LUT_DESCRIPTOR_TAGS and value[0] < 0:\r\n # We only fix the first value as the third value is 8 or 16\r\n value[0] += 65536\r\nexcept TypeError:\r\n pass\r\n```\r\n\r\n(or test if `value` is iterable).\r\n\r\n**Your environment**\r\n```\r\nDarwin-19.3.0-x86_64-i386-64bit\r\nPython 3.7.6 | packaged by conda-forge | (default, Jan 7 2020, 22:05:27)\r\n[Clang 9.0.1 ]\r\npydicom 1.4.1\r\n```\r\n\r\nMany thanks!\n", "hints_text": "", "created_at": "2020-02-10T10:54:28Z", "version": "1.4", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor_empty", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor_singleton"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_empty_numbers_tag", "pydicom/tests/test_filereader.py::TestReader::test_UTF8_filename", "pydicom/tests/test_filereader.py::TestReader::test_RTPlan", "pydicom/tests/test_filereader.py::TestReader::test_RTDose", "pydicom/tests/test_filereader.py::TestReader::test_CT", "pydicom/tests/test_filereader.py::TestReader::test_CT_PixelData", "pydicom/tests/test_filereader.py::TestReader::test_no_force", "pydicom/tests/test_filereader.py::TestReader::test_RTStruct", "pydicom/tests/test_filereader.py::TestReader::test_dir", "pydicom/tests/test_filereader.py::TestReader::test_MR", "pydicom/tests/test_filereader.py::TestReader::test_deflate", "pydicom/tests/test_filereader.py::TestReader::test_no_pixels_read", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_SQ", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_tag", "pydicom/tests/test_filereader.py::TestReader::test_tag_with_unknown_length_tag_too_short", "pydicom/tests/test_filereader.py::TestReader::test_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_nested_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_no_meta_group_length", "pydicom/tests/test_filereader.py::TestReader::test_no_transfer_syntax_in_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_little_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_big_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_planar_config", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::TestReader::test_long_specific_char_set", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::TestReader::test_group_length_wrong", "pydicom/tests/test_filereader.py::TestReader::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_empty_file", "pydicom/tests/test_filereader.py::TestReader::test_empty_specific_character_set", "pydicom/tests/test_filereader.py::TestReader::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_seq_item_looks_like_explicit_VR", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_AE", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_SV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_explicit_little", "pydicom/tests/test_filereader.py::TestDeferredRead::test_time_check", "pydicom/tests/test_filereader.py::TestDeferredRead::test_file_exists", "pydicom/tests/test_filereader.py::TestDeferredRead::test_values_identical", "pydicom/tests/test_filereader.py::TestDeferredRead::test_zipped_deferred", "pydicom/tests/test_filereader.py::TestDeferredRead::test_filelike_deferred", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelDataArray", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_object", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_like_object", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit"], "environment_setup_commit": "5098c9147fadcb3e5918487036867931435adeb8"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-944", "base_commit": "a0300a69a1da1626caef0d9738cff29b17ce79cc", "patch": "diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -545,7 +545,7 @@ def MultiString(val, valtype=str):\n # 2005.05.25: also check for trailing 0, error made\n # in PET files we are converting\n \n- if val and (val.endswith(' ') or val.endswith('\\x00')):\n+ while val and (val.endswith(' ') or val.endswith('\\x00')):\n val = val[:-1]\n splitup = val.split(\"\\\\\")\n \ndiff --git a/pydicom/values.py b/pydicom/values.py\n--- a/pydicom/values.py\n+++ b/pydicom/values.py\n@@ -407,7 +407,7 @@ def convert_single_string(byte_string, encodings=None):\n \"\"\"\n encodings = encodings or [default_encoding]\n value = decode_string(byte_string, encodings, TEXT_VR_DELIMS)\n- if value and value.endswith(' '):\n+ while value and (value.endswith(' ') or value.endswith('\\0')):\n value = value[:-1]\n return value\n \n", "test_patch": "diff --git a/pydicom/tests/test_values.py b/pydicom/tests/test_values.py\n--- a/pydicom/tests/test_values.py\n+++ b/pydicom/tests/test_values.py\n@@ -86,6 +86,21 @@ def test_single_value_with_delimiters(self):\n expected = u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2\\r\\nJ\u00e9r\u00f4me/\u041b\u044e\u043ace\u043c\u0431yp\u0433\\tJ\u00e9r\u00f4me'\n assert expected == convert_single_string(bytestring, encodings)\n \n+ def test_value_ending_with_padding(self):\n+ bytestring = b'Value ending with spaces '\n+ assert 'Value ending with spaces' == convert_single_string(bytestring)\n+ assert 'Value ending with spaces' == convert_text(bytestring)\n+\n+ bytestring = b'Values \\\\with spaces '\n+ assert ['Values', 'with spaces'] == convert_text(bytestring)\n+\n+ bytestring = b'Value ending with zeros\\0\\0\\0'\n+ assert 'Value ending with zeros' == convert_single_string(bytestring)\n+ assert 'Value ending with zeros' == convert_text(bytestring)\n+\n+ bytestring = b'Values\\0\\0\\\\with zeros\\0'\n+ assert ['Values', 'with zeros'] == convert_text(bytestring)\n+\n \n class TestConvertAT(object):\n def test_big_endian(self):\n", "problem_statement": "Embedded Null character\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\n<!-- Example: Attribute Error thrown when printing (0x0010, 0x0020) patient Id> 0-->\r\n---------------------------------------------------------------------------\r\nKeyError Traceback (most recent call last)\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/charset.py in convert_encodings(encodings)\r\n 624 try:\r\n--> 625 py_encodings.append(python_encoding[encoding])\r\n 626 except KeyError:\r\n\r\nKeyError: 'ISO_IR 100\\x00'\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nValueError Traceback (most recent call last)\r\n<ipython-input-12-605c3c3edcf4> in <module>\r\n 4 print(filename)\r\n 5 dcm = pydicom.dcmread(filename,force=True)\r\n----> 6 dcm = pydicom.dcmread('/home/zhuzhemin/XrayKeyPoints/data/10-31-13_11H18M20_3674972_FACE_0_SC.dcm',force=True)\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py in dcmread(fp, defer_size, stop_before_pixels, force, specific_tags)\r\n 848 try:\r\n 849 dataset = read_partial(fp, stop_when, defer_size=defer_size,\r\n--> 850 force=force, specific_tags=specific_tags)\r\n 851 finally:\r\n 852 if not caller_owns_file:\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py in read_partial(fileobj, stop_when, defer_size, force, specific_tags)\r\n 726 dataset = read_dataset(fileobj, is_implicit_VR, is_little_endian,\r\n 727 stop_when=stop_when, defer_size=defer_size,\r\n--> 728 specific_tags=specific_tags)\r\n 729 except EOFError:\r\n 730 pass # error already logged in read_dataset\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py in read_dataset(fp, is_implicit_VR, is_little_endian, bytelength, stop_when, defer_size, parent_encoding, specific_tags)\r\n 361 try:\r\n 362 while (bytelength is None) or (fp.tell() - fp_start < bytelength):\r\n--> 363 raw_data_element = next(de_gen)\r\n 364 # Read data elements. Stop on some errors, but return what was read\r\n 365 tag = raw_data_element.tag\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py in data_element_generator(fp, is_implicit_VR, is_little_endian, stop_when, defer_size, encoding, specific_tags)\r\n 203 # Store the encoding value in the generator\r\n 204 # for use with future elements (SQs)\r\n--> 205 encoding = convert_encodings(encoding)\r\n 206 \r\n 207 yield RawDataElement(tag, VR, length, value, value_tell,\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/charset.py in convert_encodings(encodings)\r\n 626 except KeyError:\r\n 627 py_encodings.append(\r\n--> 628 _python_encoding_for_corrected_encoding(encoding))\r\n 629 \r\n 630 if len(encodings) > 1:\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/charset.py in _python_encoding_for_corrected_encoding(encoding)\r\n 664 # fallback: assume that it is already a python encoding\r\n 665 try:\r\n--> 666 codecs.lookup(encoding)\r\n 667 return encoding\r\n 668 except LookupError:\r\n\r\nValueError: embedded null character\r\n#### Steps/Code to Reproduce\r\n<!--\r\nExample:\r\n```py\r\nfrom io import BytesIO\r\nfrom pydicom import dcmread\r\n\r\nbytestream = b'\\x02\\x00\\x02\\x00\\x55\\x49\\x16\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31' \\\r\n b'\\x30\\x30\\x30\\x38\\x2e\\x35\\x2e\\x31\\x2e\\x31\\x2e\\x39\\x00\\x02\\x00\\x10\\x00' \\\r\n b'\\x55\\x49\\x12\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31\\x30\\x30\\x30\\x38' \\\r\n b'\\x2e\\x31\\x2e\\x32\\x00\\x20\\x20\\x10\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x20\\x20' \\\r\n b'\\x20\\x00\\x06\\x00\\x00\\x00\\x4e\\x4f\\x52\\x4d\\x41\\x4c'\r\n\r\nfp = BytesIO(bytestream)\r\nds = dcmread(fp, force=True)\r\n\r\nprint(ds.PatientID)\r\n```\r\nIf the code is too long, feel free to put it in a public gist and link\r\nit in the issue: https://gist.github.com\r\n\r\nWhen possible use pydicom testing examples to reproduce the errors. Otherwise, provide\r\nan anonymous version of the data in order to replicate the errors.\r\n-->\r\nimport pydicom\r\ndcm = pydicom.dcmread('/home/zhuzhemin/XrayKeyPoints/data/10-31-13_11H18M20_3674972_FACE_0_SC.dcm')\r\n\r\n#### Expected Results\r\n<!-- Please paste or describe the expected results.\r\nExample: No error is thrown and the name of the patient is printed.-->\r\nNo error\r\nI used dcmread function in matlab to read the same file and it was ok. So it should not be the problem of the file.\r\n#### Actual Results\r\n<!-- Please paste or specifically describe the actual output or traceback.\r\n(Use %xmode to deactivate ipython's trace beautifier)\r\nExample: ```AttributeError: 'FileDataset' object has no attribute 'PatientID'```\r\n-->\r\nError: Embedded Null character\r\n#### Versions\r\n<!--\r\nPlease run the following snippet and paste the output below.\r\nimport platform; print(platform.platform())\r\nimport sys; print(\"Python\", sys.version)\r\nimport pydicom; print(\"pydicom\", pydicom.__version__)\r\n-->\r\n1.3.0\r\n\r\n<!-- Thanks for contributing! -->\r\n\n", "hints_text": "Well, this is invalid DICOM, so strictly speaking this is not a bug, but we can probably just ignore the null character and change the error into a warning (if `config.enforce_valid_values` is not set).\n> Well, this is invalid DICOM, so strictly speaking this is not a bug, but we can probably just ignore the null character and change the error into a warning (if `config.enforce_valid_values` is not set).\r\n\r\nWe could do that, but given that this is the first time seeing an error like this, I don't think it is worth the effort. Instead, I think using [data_element_callback](https://pydicom.github.io/pydicom/stable/api_ref.html#pydicom.config.data_element_callback) is better suited - example of how to use in my comment [here](https://github.com/pydicom/pydicom/issues/820#issuecomment-473500989). Not quite the same situation, but could be adapted to replace the bad value.\nI'm in favour of ignoring it with a warning/exception, its not really any different from all the other non-conformant fixes we have.\nI guess a terminating null is probably common enough carry-over from C that we could be tolerant to reading that. I'm worried about chasing invalid DICOM endlessly, though, when there is an existing facility for people to filter any kind of invalid values out, and every extra check hits performance, if only a small amount. Perhaps we just need to make that `util.fixer` code easier to use, maybe a `pydicom.config` setting to set characters to strip as a one-liner before reading a file.\nYeah, I see your point... the code gets messier each time we add a workaround for another incarnation of invalid DICOM. \r\nThis concrete exception happens during Python encoding lookup (as a fallback to check if the encoding is already a Python encoding), where we only expect a `LookupError`. The actual fix, if we would add one, would have to happen earlier (like stripping any trailing zero byte from string values), but I'm not sure if that's worth it.\r\nIt may be interesting to understand where this comes from, as I doubt any major DICOM library or modality would have written such a value, and if this may happen elsewhere. I would also check if dcmtk handles this - if they do, I would be more inclined to add a fix. \nOk, dcmdump just ignores it (I replaced the last '0' by a a zero):\r\n```(0008,0005) CS [ISO_IR 10 ] # 10, 1 SpecificCharacterSet```\r\n\n> I'm worried about chasing invalid DICOM endlessly, though, when there is an existing facility for people to filter any kind of invalid values out, and every extra check hits performance, if only a small amount.\r\n\r\nFair enough. Perhaps we could update fixer (if needed) and have a 'library' of available fixes instead and make sure its all documented. That way in the future we can just add to the library instead of adding a workaround to the codebase.\nI read your answers but cannot adapt the callback to my own situation. I really do not understand how dicom is organized and parsed. All I want is to grab the pixel array and do something. Would Appreciate if you could update the version and fix it.\nAs @mrbean-bremen said, this can't currently be fixed using `config.data_element_callback` because that gets called after reading while the exception is raised during reading (because character set is special). We'd need an earlier hook if we want to go the fixer route.\nLet's try this again... quick workaround.\r\n```python\r\nimport codecs\r\nimport re\r\n\r\nfrom pydicom import charset\r\nfrom pydicom import dcmread\r\n\r\ndef _python_encoding_for_corrected_encoding(encoding):\r\n encoding = encoding.strip(' \\r\\t\\n\\0')\r\n\r\n # standard encodings\r\n patched = None\r\n if re.match('^ISO[^_]IR', encoding) is not None:\r\n patched = 'ISO_IR' + encoding[6:]\r\n # encodings with code extensions\r\n elif re.match('^(?=ISO.2022.IR.)(?!ISO 2022 IR )',\r\n encoding) is not None:\r\n patched = 'ISO 2022 IR ' + encoding[12:]\r\n\r\n if patched:\r\n # handle encoding patched for common spelling errors\r\n try:\r\n py_encoding = python_encoding[patched]\r\n charset._warn_about_invalid_encoding(encoding, patched)\r\n return py_encoding\r\n except KeyError:\r\n charset._warn_about_invalid_encoding(encoding)\r\n return default_encoding\r\n\r\n # fallback: assume that it is already a python encoding\r\n try:\r\n codecs.lookup(encoding)\r\n return encoding\r\n except LookupError:\r\n charset._warn_about_invalid_encoding(encoding)\r\n return default_encoding\r\n\r\ncharset._python_encoding_for_corrected_encoding = _python_encoding_for_corrected_encoding\r\n\r\nds = dcmread(...)\r\n```\nInterestingly we actually do handle charset values that have trailing padding `\\x00`, through `valuerep.MultiString`, what we don't do is handle values that end in more than one null (i.e. `\\x00\\x00`) which is the case here.\r\n\r\nWe could change [this line](https://github.com/pydicom/pydicom/blob/a0300a69a1da1626caef0d9738cff29b17ce79cc/pydicom/valuerep.py#L548)\r\n```python\r\nwhile val.endswith(' ') or val.endswith('\\x00'):\r\n val = val[:-1]\r\n```\nHm, that looks like an easy fix without impact - I wasn't aware of this. The only question is - should we warn in this case?\r\nThat being said, I still think that your proposal to add a repository of available fixes is a good one, even if not applicable to this issue.", "created_at": "2019-09-05T18:25:50Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_values.py::TestConvertText::test_value_ending_with_padding"], "PASS_TO_PASS": ["pydicom/tests/test_values.py::TestConvertTag::test_big_endian", "pydicom/tests/test_values.py::TestConvertTag::test_little_endian", "pydicom/tests/test_values.py::TestConvertTag::test_offset", "pydicom/tests/test_values.py::TestConvertAE::test_strip_blanks", "pydicom/tests/test_values.py::TestConvertText::test_single_value", "pydicom/tests/test_values.py::TestConvertText::test_multi_value", "pydicom/tests/test_values.py::TestConvertText::test_single_value_with_backslash", "pydicom/tests/test_values.py::TestConvertText::test_single_value_with_delimiters", "pydicom/tests/test_values.py::TestConvertAT::test_big_endian", "pydicom/tests/test_values.py::TestConvertAT::test_little_endian", "pydicom/tests/test_values.py::TestConvertAT::test_empty_bytestring", "pydicom/tests/test_values.py::TestConvertDA::test_big_endian", "pydicom/tests/test_values.py::TestConvertDA::test_little_endian", "pydicom/tests/test_values.py::TestConvertDA::test_empty_bytestring", "pydicom/tests/test_values.py::TestConvertValue::test_convert_value_raises"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1255", "base_commit": "59be4993000cc8af2cd9a4176f15398b6a7875d7", "patch": "diff --git a/pydicom/_version.py b/pydicom/_version.py\n--- a/pydicom/_version.py\n+++ b/pydicom/_version.py\n@@ -3,7 +3,7 @@\n from typing import Tuple\n \n \n-__version__: str = '2.1.0'\n+__version__: str = '2.1.1'\n __version_info__: Tuple[str, str, str] = tuple(\n re.match(r'(\\d+\\.\\d+\\.\\d+).*', __version__).group(1).split('.')\n )\ndiff --git a/pydicom/filebase.py b/pydicom/filebase.py\n--- a/pydicom/filebase.py\n+++ b/pydicom/filebase.py\n@@ -5,7 +5,7 @@\n from struct import unpack, pack\n from types import TracebackType\n from typing import (\n- Tuple, Optional, NoReturn, BinaryIO, Callable, Type, Union, cast, TextIO,\n+ Tuple, Optional, BinaryIO, Callable, Type, Union, cast, TextIO,\n TYPE_CHECKING, Any\n )\n \n@@ -182,15 +182,15 @@ def __init__(\n self.close = file_like_obj.close\n self.name: str = getattr(file_like_obj, 'name', '<no filename>')\n \n- def no_write(self, bytes_read: bytes) -> NoReturn:\n+ def no_write(self, bytes_read: bytes) -> None:\n \"\"\"Used for file-like objects where no write is available\"\"\"\n raise IOError(\"This DicomFileLike object has no write() method\")\n \n- def no_read(self, bytes_read: Optional[int] = None) -> NoReturn:\n+ def no_read(self, bytes_read: Optional[int] = None) -> None:\n \"\"\"Used for file-like objects where no read is available\"\"\"\n raise IOError(\"This DicomFileLike object has no read() method\")\n \n- def no_seek(self, offset: int, from_what: int = 0) -> NoReturn:\n+ def no_seek(self, offset: int, from_what: int = 0) -> None:\n \"\"\"Used for file-like objects where no seek is available\"\"\"\n raise IOError(\"This DicomFileLike object has no seek() method\")\n \ndiff --git a/pydicom/jsonrep.py b/pydicom/jsonrep.py\n--- a/pydicom/jsonrep.py\n+++ b/pydicom/jsonrep.py\n@@ -226,7 +226,8 @@ def get_sequence_item(self, value):\n value_key = unique_value_keys[0]\n elem = DataElement.from_json(\n self.dataset_class, key, vr,\n- val[value_key], value_key\n+ val[value_key], value_key,\n+ self.bulk_data_element_handler\n )\n ds.add(elem)\n return ds\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -38,6 +38,7 @@\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n+ \"Programming Language :: Python :: 3.9\",\n \"Operating System :: OS Independent\",\n \"Topic :: Scientific/Engineering :: Medical Science Apps.\",\n \"Topic :: Scientific/Engineering :: Physics\",\n@@ -80,7 +81,7 @@ def data_files_inventory():\n \n \n PACKAGE_DATA = {\n- 'pydicom': data_files_inventory() + ['py.typed']\n+ 'pydicom': data_files_inventory()\n }\n \n opts = dict(\n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -354,3 +354,25 @@ def bulk_data_reader(tag, vr, value):\n ds = Dataset().from_json(json.dumps(json_data), bulk_data_reader)\n \n assert b'xyzzy' == ds[0x00091002].value\n+\n+ def test_bulk_data_reader_is_called_within_SQ(self):\n+ def bulk_data_reader(_):\n+ return b'xyzzy'\n+\n+ json_data = {\n+ \"003a0200\": {\n+ \"vr\": \"SQ\",\n+ \"Value\": [\n+ {\n+ \"54001010\": {\n+ \"vr\": \"OW\",\n+ \"BulkDataURI\": \"https://a.dummy.url\"\n+ }\n+ }\n+ ]\n+ }\n+ }\n+\n+ ds = Dataset().from_json(json.dumps(json_data), bulk_data_reader)\n+\n+ assert b'xyzzy' == ds[0x003a0200].value[0][0x54001010].value\n", "problem_statement": "Mypy errors\n**Describe the bug**\r\nSeveral of the type hints are problematic and result in mypy errors.\r\n\r\nOne example:\r\n\r\n```none\r\ncat << EOF > /tmp/test.py\r\nfrom pydicom import Dataset, dcmread\r\n\r\ndataset = Dataset()\r\ndataset.Rows = 10\r\ndataset.Columns = 20\r\ndataset.NumberOfFrames = \"5\"\r\n\r\nassert int(dataset.NumberOfFrames) == 5\r\n\r\nfilename = '/tmp/test.dcm'\r\ndataset.save_as(str(filename))\r\n\r\ndataset = dcmread(filename)\r\n\r\nassert int(dataset.NumberOfFrames) == 5\r\nEOF\r\n```\r\n\r\n```none\r\nmypy /tmp/test.py\r\n/tmp/test.py:15: error: No overload variant of \"int\" matches argument type \"object\"\r\n/tmp/test.py:15: note: Possible overload variant:\r\n/tmp/test.py:15: note: def int(self, x: Union[str, bytes, SupportsInt, _SupportsIndex] = ...) -> int\r\n/tmp/test.py:15: note: <1 more non-matching overload not shown>\r\nFound 1 error in 1 file (checked 1 source file)\r\n```\r\n\r\n**Expected behavior**\r\nMypy should not report any errors.\r\n\r\n**Steps To Reproduce**\r\nSee above\r\n\r\n**Your environment**\r\n```none\r\npython -m pydicom.env_info\r\nmodule | version\r\n------ | -------\r\nplatform | macOS-10.15.6-x86_64-i386-64bit\r\nPython | 3.8.6 (default, Oct 8 2020, 14:06:32) [Clang 12.0.0 (clang-1200.0.32.2)]\r\npydicom | 2.1.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.19.3\r\nPIL | 8.0.1\r\n```\nImportError: cannot import name 'NoReturn'\n**Describe the bug**\r\nthrow following excetion when import pydicom package:\r\n```\r\nxxx/python3.6/site-packages/pydicom/filebase.py in <module>\r\n5 from struct import unpack, pack\r\n 6 from types import TracebackType\r\n----> 7 from typing import (\r\n 8 Tuple, Optional, NoReturn, BinaryIO, Callable, Type, Union, cast, TextIO,\r\n 9 TYPE_CHECKING, Any\r\n\r\nImportError: cannot import name 'NoReturn'\r\n```\r\n\r\n**Expected behavior**\r\nimort pydicom sucessfully\r\n\r\n**Steps To Reproduce**\r\nHow to reproduce the issue. Please include a minimum working code sample, the\r\ntraceback (if any) and the anonymized DICOM dataset (if relevant).\r\n\r\n**Your environment**\r\npython:3.6.0\r\npydicom:2.1\r\n\n", "hints_text": "I ran into multiple other errors and would suggest removing `py.typed` until the type annotations have been properly tested. \n@hackermd, just for my education, since I have only dabbled in 'typing' so far - does this break your workflow somehow? Is it not possible to exclude pydicom from forcing errors? (other than removing `py.typed`)\r\n\nHmm, maybe we should just use `Any` for the element values rather than `object`. The problem is the element value type will be/is so broad users are pretty much going to have to `cast` everything no matter what we do.\n@darcymason \r\n\r\n> does this break your workflow somehow\r\n\r\nWe are running mypy on all our Pyhon code and our unit test pipelines are failing. I have fixed the pydicom version to `2.0.0`, but I would like to avoid doing that moving forward.\r\n\r\n> Is it not possible to exclude pydicom from forcing errors? (other than removing py.typed)\r\n\r\nOne can add `#type: ingore` to exclude individual lines from type checks, but at the moment we are getting hundreds of errors.\r\n\r\nInstead of removing `py.typed`, one could also remove the type hints from problematic functions. `object` or `Any` are not that useful and seem to cause more trouble than benefit.\n@scaramallion \r\n\r\n> The problem is the element value type will be/is so broad users are pretty much going to have to cast everything no matter what we do\r\n\r\nAgreed. The return value of these \"magic\" methods will be difficult to type. It's basically a Union of all Python types corresponding to any of the DICOM Value Representations.\n@hackermd, thanks for the explanations.\r\n\r\nI suggest doing a patch release for this if @scaramallion is in agreement. We could just remove the `py.typed`, as suggested, and do it quickly (and push 'typing' to v2.2), or perhaps within a few days/couple of weeks if removal of `object` can be a better solution. @scaramallion, your thoughts? \r\n\r\n@hackermd, would you be able to test on master if we try the correction route?\r\n\n> would you be able to test on master if we try the correction route\r\n\r\nYes, happy to help with that. \nYeah, lets do it. Fix #1253 and #1254 while we're at it. Pushing typing back to at least v2.2 is probably the way to go, too. \nNew in 3.6.2, well that's annoying", "created_at": "2020-11-04T20:55:23Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_within_SQ"], "PASS_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_2"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1017", "base_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3", "patch": "diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -955,35 +955,40 @@ def dcmwrite(filename, dataset, write_like_original=True):\n # for write_numbers, the Writer maps to a tuple (function, struct_format)\n # (struct_format is python's struct module format)\n writers = {\n- 'UL': (write_numbers, 'L'),\n- 'SL': (write_numbers, 'l'),\n- 'US': (write_numbers, 'H'),\n- 'SS': (write_numbers, 'h'),\n- 'FL': (write_numbers, 'f'),\n+ 'AE': (write_string, None),\n+ 'AS': (write_string, None),\n+ 'AT': (write_ATvalue, None),\n+ 'CS': (write_string, None),\n+ 'DA': (write_DA, None),\n+ 'DS': (write_number_string, None),\n+ 'DT': (write_DT, None),\n 'FD': (write_numbers, 'd'),\n- 'OF': (write_numbers, 'f'),\n+ 'FL': (write_numbers, 'f'),\n+ 'IS': (write_number_string, None),\n+ 'LO': (write_text, None),\n+ 'LT': (write_text, None),\n 'OB': (write_OBvalue, None),\n 'OD': (write_OWvalue, None),\n+ 'OF': (write_numbers, 'f'),\n 'OL': (write_OWvalue, None),\n- 'UI': (write_UI, None),\n- 'SH': (write_text, None),\n- 'DA': (write_DA, None),\n- 'TM': (write_TM, None),\n- 'CS': (write_string, None),\n+ 'OW': (write_OWvalue, None),\n+ 'OV': (write_OWvalue, None),\n 'PN': (write_PN, None),\n- 'LO': (write_text, None),\n- 'IS': (write_number_string, None),\n- 'DS': (write_number_string, None),\n- 'AE': (write_string, None),\n- 'AS': (write_string, None),\n- 'LT': (write_text, None),\n+ 'SH': (write_text, None),\n+ 'SL': (write_numbers, 'l'),\n 'SQ': (write_sequence, None),\n+ 'SS': (write_numbers, 'h'),\n+ 'ST': (write_text, None),\n+ 'SV': (write_numbers, 'q'),\n+ 'TM': (write_TM, None),\n 'UC': (write_text, None),\n+ 'UI': (write_UI, None),\n+ 'UL': (write_numbers, 'L'),\n 'UN': (write_UN, None),\n 'UR': (write_string, None),\n- 'AT': (write_ATvalue, None),\n- 'ST': (write_text, None),\n- 'OW': (write_OWvalue, None),\n+ 'US': (write_numbers, 'H'),\n+ 'UT': (write_text, None),\n+ 'UV': (write_numbers, 'Q'),\n 'US or SS': (write_OWvalue, None),\n 'US or OW': (write_OWvalue, None),\n 'US or SS or OW': (write_OWvalue, None),\n@@ -991,6 +996,4 @@ def dcmwrite(filename, dataset, write_like_original=True):\n 'OB/OW': (write_OBvalue, None),\n 'OB or OW': (write_OBvalue, None),\n 'OW or OB': (write_OBvalue, None),\n- 'DT': (write_DT, None),\n- 'UT': (write_text, None),\n } # note OW/OB depends on other items, which we don't know at write time\ndiff --git a/pydicom/values.py b/pydicom/values.py\n--- a/pydicom/values.py\n+++ b/pydicom/values.py\n@@ -300,6 +300,15 @@ def convert_OWvalue(byte_string, is_little_endian, struct_format=None):\n return convert_OBvalue(byte_string, is_little_endian)\n \n \n+def convert_OVvalue(byte_string, is_little_endian, struct_format=None):\n+ \"\"\"Return the encoded 'OV' value as :class:`bytes` or :class:`str`.\n+\n+ No byte swapping will be performed.\n+ \"\"\"\n+ # for now, Maybe later will have own routine\n+ return convert_OBvalue(byte_string, is_little_endian)\n+\n+\n def convert_PN(byte_string, encodings=None):\n \"\"\"Return a decoded 'PN' value.\n \n@@ -635,35 +644,40 @@ def convert_value(VR, raw_data_element, encodings=None):\n # (function, struct_format)\n # (struct_format in python struct module style)\n converters = {\n- 'UL': (convert_numbers, 'L'),\n- 'SL': (convert_numbers, 'l'),\n- 'US': (convert_numbers, 'H'),\n- 'SS': (convert_numbers, 'h'),\n- 'FL': (convert_numbers, 'f'),\n+ 'AE': convert_AE_string,\n+ 'AS': convert_string,\n+ 'AT': convert_ATvalue,\n+ 'CS': convert_string,\n+ 'DA': convert_DA_string,\n+ 'DS': convert_DS_string,\n+ 'DT': convert_DT_string,\n 'FD': (convert_numbers, 'd'),\n- 'OF': (convert_numbers, 'f'),\n+ 'FL': (convert_numbers, 'f'),\n+ 'IS': convert_IS_string,\n+ 'LO': convert_text,\n+ 'LT': convert_single_string,\n 'OB': convert_OBvalue,\n 'OD': convert_OBvalue,\n+ 'OF': (convert_numbers, 'f'),\n 'OL': convert_OBvalue,\n- 'UI': convert_UI,\n- 'SH': convert_text,\n- 'DA': convert_DA_string,\n- 'TM': convert_TM_string,\n- 'CS': convert_string,\n+ 'OW': convert_OWvalue,\n+ 'OV': convert_OVvalue,\n 'PN': convert_PN,\n- 'LO': convert_text,\n- 'IS': convert_IS_string,\n- 'DS': convert_DS_string,\n- 'AE': convert_AE_string,\n- 'AS': convert_string,\n- 'LT': convert_single_string,\n+ 'SH': convert_text,\n+ 'SL': (convert_numbers, 'l'),\n 'SQ': convert_SQ,\n+ 'SS': (convert_numbers, 'h'),\n+ 'ST': convert_single_string,\n+ 'SV': (convert_numbers, 'q'),\n+ 'TM': convert_TM_string,\n 'UC': convert_text,\n+ 'UI': convert_UI,\n+ 'UL': (convert_numbers, 'L'),\n 'UN': convert_UN,\n 'UR': convert_UR_string,\n- 'AT': convert_ATvalue,\n- 'ST': convert_single_string,\n- 'OW': convert_OWvalue,\n+ 'US': (convert_numbers, 'H'),\n+ 'UT': convert_single_string,\n+ 'UV': (convert_numbers, 'Q'),\n 'OW/OB': convert_OBvalue, # note OW/OB depends on other items,\n 'OB/OW': convert_OBvalue, # which we don't know at read time\n 'OW or OB': convert_OBvalue,\n@@ -672,6 +686,4 @@ def convert_value(VR, raw_data_element, encodings=None):\n 'US or OW': convert_OWvalue,\n 'US or SS or OW': convert_OWvalue,\n 'US\\\\US or SS\\\\US': convert_OWvalue,\n- 'DT': convert_DT_string,\n- 'UT': convert_single_string,\n }\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -17,6 +17,7 @@\n from pydicom import config\n from pydicom.dataset import Dataset, FileDataset\n from pydicom.data import get_testdata_files\n+from pydicom.datadict import add_dict_entries\n from pydicom.filereader import dcmread, read_dataset\n from pydicom.dataelem import DataElement, DataElement_from_raw\n from pydicom.errors import InvalidDicomError\n@@ -837,6 +838,31 @@ def setup(self):\n ds.URNCodeValue = 'http://test.com' # VR of UR\n ds.RetrieveURL = 'ftp://test.com ' # Test trailing spaces ignored\n ds.DestinationAE = ' TEST 12 ' # 16 characters max for AE\n+ # 8-byte values\n+ ds.ExtendedOffsetTable = ( # VR of OV\n+ b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n+ b'\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08'\n+ )\n+\n+ # No public elements with VR of SV or UV yet...\n+ add_dict_entries({\n+ 0xFFFE0001: (\n+ 'SV', '1', 'SV Element Minimum', '', 'SVElementMinimum'\n+ ),\n+ 0xFFFE0002: (\n+ 'SV', '1', 'SV Element Maximum', '', 'SVElementMaximum'\n+ ),\n+ 0xFFFE0003: (\n+ 'UV', '1', 'UV Element Minimum', '', 'UVElementMinimum'\n+ ),\n+ 0xFFFE0004: (\n+ 'UV', '1', 'UV Element Maximum', '', 'UVElementMaximum'\n+ ),\n+ })\n+ ds.SVElementMinimum = -2**63\n+ ds.SVElementMaximum = 2**63 - 1\n+ ds.UVElementMinimum = 0\n+ ds.UVElementMaximum = 2**64 - 1\n \n self.fp = BytesIO() # Implicit little\n file_ds = FileDataset(self.fp, ds)\n@@ -939,6 +965,113 @@ def test_read_AE(self):\n ds = dcmread(self.fp, force=True)\n assert 'TEST 12' == ds.DestinationAE\n \n+ def test_read_OV_implicit_little(self):\n+ \"\"\"Check reading element with VR of OV encoded as implicit\"\"\"\n+ ds = dcmread(self.fp, force=True)\n+ val = (\n+ b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n+ b'\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08'\n+ )\n+ elem = ds['ExtendedOffsetTable']\n+ assert 'OV' == elem.VR\n+ assert 0x7FE00001 == elem.tag\n+ assert val == elem.value\n+\n+ new = DataElement(0x7FE00001, 'OV', val)\n+ assert elem == new\n+\n+ def test_read_OV_explicit_little(self):\n+ \"\"\"Check reading element with VR of OV encoded as explicit\"\"\"\n+ ds = dcmread(self.fp_ex, force=True)\n+ val = (\n+ b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n+ b'\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08'\n+ )\n+ elem = ds['ExtendedOffsetTable']\n+ assert 'OV' == elem.VR\n+ assert 0x7FE00001 == elem.tag\n+ assert val == elem.value\n+\n+ new = DataElement(0x7FE00001, 'OV', val)\n+ assert elem == new\n+\n+ def test_read_SV_implicit_little(self):\n+ \"\"\"Check reading element with VR of SV encoded as implicit\"\"\"\n+ ds = dcmread(self.fp, force=True)\n+ elem = ds['SVElementMinimum']\n+ assert 'SV' == elem.VR\n+ assert 0xFFFE0001 == elem.tag\n+ assert -2**63 == elem.value\n+\n+ new = DataElement(0xFFFE0001, 'SV', -2**63)\n+ assert elem == new\n+\n+ elem = ds['SVElementMaximum']\n+ assert 'SV' == elem.VR\n+ assert 0xFFFE0002 == elem.tag\n+ assert 2**63 - 1 == elem.value\n+\n+ new = DataElement(0xFFFE0002, 'SV', 2**63 - 1)\n+ assert elem == new\n+\n+ @pytest.mark.skip(\"No public elements with VR of SV\")\n+ def test_read_SV_explicit_little(self):\n+ \"\"\"Check reading element with VR of SV encoded as explicit\"\"\"\n+ ds = dcmread(self.fp_ex, force=True)\n+ elem = ds['SVElementMinimum']\n+ assert 'SV' == elem.VR\n+ assert 0xFFFE0001 == elem.tag\n+ assert -2**63 == elem.value\n+\n+ new = DataElement(0xFFFE0001, 'SV', -2**63)\n+ assert elem == new\n+\n+ elem = ds['SVElementMaximum']\n+ assert 'SV' == elem.VR\n+ assert 0xFFFE0002 == elem.tag\n+ assert 2**63 - 1 == elem.value\n+\n+ new = DataElement(0xFFFE0002, 'SV', 2**63 - 1)\n+ assert elem == new\n+\n+ def test_read_UV_implicit_little(self):\n+ \"\"\"Check reading element with VR of UV encoded as implicit\"\"\"\n+ ds = dcmread(self.fp, force=True)\n+ elem = ds['UVElementMinimum']\n+ assert 'UV' == elem.VR\n+ assert 0xFFFE0003 == elem.tag\n+ assert 0 == elem.value\n+\n+ new = DataElement(0xFFFE0003, 'UV', 0)\n+ assert elem == new\n+\n+ elem = ds['UVElementMaximum']\n+ assert 'UV' == elem.VR\n+ assert 0xFFFE0004 == elem.tag\n+ assert 2**64 - 1 == elem.value\n+\n+ new = DataElement(0xFFFE0004, 'UV', 2**64 - 1)\n+ assert elem == new\n+\n+ def test_read_UV_explicit_little(self):\n+ \"\"\"Check reading element with VR of UV encoded as explicit\"\"\"\n+ ds = dcmread(self.fp_ex, force=True)\n+ elem = ds['UVElementMinimum']\n+ assert 'UV' == elem.VR\n+ assert 0xFFFE0003 == elem.tag\n+ assert 0 == elem.value\n+\n+ new = DataElement(0xFFFE0003, 'UV', 0)\n+ assert elem == new\n+\n+ elem = ds['UVElementMaximum']\n+ assert 'UV' == elem.VR\n+ assert 0xFFFE0004 == elem.tag\n+ assert 2**64 - 1 == elem.value\n+\n+ new = DataElement(0xFFFE0004, 'UV', 2**64 - 1)\n+ assert elem == new\n+\n \n class TestDeferredRead(object):\n \"\"\"Test that deferred data element reading (for large size)\n", "problem_statement": "Add support for missing VRs\nMissing: OV, SV, UV\r\n\r\n\n", "hints_text": "", "created_at": "2020-01-01T04:52:05Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_AE", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_SV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_explicit_little"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_empty_numbers_tag", "pydicom/tests/test_filereader.py::TestReader::test_UTF8_filename", "pydicom/tests/test_filereader.py::TestReader::test_RTPlan", "pydicom/tests/test_filereader.py::TestReader::test_RTDose", "pydicom/tests/test_filereader.py::TestReader::test_CT", "pydicom/tests/test_filereader.py::TestReader::test_CT_PixelData", "pydicom/tests/test_filereader.py::TestReader::test_no_force", "pydicom/tests/test_filereader.py::TestReader::test_RTStruct", "pydicom/tests/test_filereader.py::TestReader::test_dir", "pydicom/tests/test_filereader.py::TestReader::test_MR", "pydicom/tests/test_filereader.py::TestReader::test_deflate", "pydicom/tests/test_filereader.py::TestReader::test_no_pixels_read", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_SQ", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_tag", "pydicom/tests/test_filereader.py::TestReader::test_tag_with_unknown_length_tag_too_short", "pydicom/tests/test_filereader.py::TestReader::test_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_nested_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_no_meta_group_length", "pydicom/tests/test_filereader.py::TestReader::test_no_transfer_syntax_in_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_little_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_big_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_planar_config", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::TestReader::test_long_specific_char_set", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::TestReader::test_group_length_wrong", "pydicom/tests/test_filereader.py::TestReader::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_empty_file", "pydicom/tests/test_filereader.py::TestReader::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_seq_item_looks_like_explicit_VR", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::TestDeferredRead::test_time_check", "pydicom/tests/test_filereader.py::TestDeferredRead::test_file_exists", "pydicom/tests/test_filereader.py::TestDeferredRead::test_values_identical", "pydicom/tests/test_filereader.py::TestDeferredRead::test_zipped_deferred", "pydicom/tests/test_filereader.py::TestDeferredRead::test_filelike_deferred", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelDataArray", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_object", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_like_object", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1048", "base_commit": "00c248441ffb8b7d46c6d855b723e696a8f5aada", "patch": "diff --git a/pydicom/data/data_manager.py b/pydicom/data/data_manager.py\n--- a/pydicom/data/data_manager.py\n+++ b/pydicom/data/data_manager.py\n@@ -5,6 +5,8 @@\n import os\n from os.path import abspath, dirname, join\n \n+from pydicom.fileutil import path_from_pathlike\n+\n DATA_ROOT = abspath(dirname(__file__))\n \n \n@@ -13,7 +15,7 @@ def get_files(base, pattern):\n \n Parameters\n ----------\n- base : str\n+ base : str or PathLike\n Base directory to recursively search.\n \n pattern : str\n@@ -26,6 +28,7 @@ def get_files(base, pattern):\n The list of filenames matched.\n \"\"\"\n \n+ base = path_from_pathlike(base)\n # if the user forgot to add them\n pattern = \"*\" + pattern + \"*\"\n \ndiff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -35,6 +35,7 @@\n from pydicom.datadict import (tag_for_keyword, keyword_for_tag,\n repeater_has_keyword)\n from pydicom.dataelem import DataElement, DataElement_from_raw, RawDataElement\n+from pydicom.fileutil import path_from_pathlike\n from pydicom.pixel_data_handlers.util import (\n convert_color_space, reshape_pixel_array, get_image_pixel_ids\n )\n@@ -1733,7 +1734,7 @@ def save_as(self, filename, write_like_original=True):\n \n Parameters\n ----------\n- filename : str or file-like\n+ filename : str or PathLike or file-like\n Name of file or the file-like to write the new DICOM file to.\n write_like_original : bool, optional\n If ``True`` (default), preserves the following information from\n@@ -2238,7 +2239,7 @@ def __init__(self,\n \n Parameters\n ----------\n- filename_or_obj : str or BytesIO or None\n+ filename_or_obj : str or PathLike or BytesIO or None\n Full path and filename to the file, memory buffer object, or\n ``None`` if is a :class:`io.BytesIO`.\n dataset : Dataset or dict\n@@ -2263,6 +2264,7 @@ def __init__(self,\n self.is_implicit_VR = is_implicit_VR\n self.is_little_endian = is_little_endian\n filename = None\n+ filename_or_obj = path_from_pathlike(filename_or_obj)\n if isinstance(filename_or_obj, str):\n filename = filename_or_obj\n self.fileobj_type = open\ndiff --git a/pydicom/dicomdir.py b/pydicom/dicomdir.py\n--- a/pydicom/dicomdir.py\n+++ b/pydicom/dicomdir.py\n@@ -28,7 +28,7 @@ def __init__(self,\n \n Parameters\n ----------\n- filename_or_obj : str or None\n+ filename_or_obj : str or PathLike or file-like or None\n Full path and filename to the file of ``None`` if\n :class:`io.BytesIO`.\n dataset : dataset.Dataset\ndiff --git a/pydicom/filereader.py b/pydicom/filereader.py\n--- a/pydicom/filereader.py\n+++ b/pydicom/filereader.py\n@@ -19,7 +19,7 @@\n from pydicom.dicomdir import DicomDir\n from pydicom.errors import InvalidDicomError\n from pydicom.filebase import DicomFile\n-from pydicom.fileutil import read_undefined_length_value\n+from pydicom.fileutil import read_undefined_length_value, path_from_pathlike\n from pydicom.misc import size_in_bytes\n from pydicom.sequence import Sequence\n from pydicom.tag import (ItemTag, SequenceDelimiterTag, TupleTag, Tag, BaseTag)\n@@ -769,7 +769,7 @@ def dcmread(fp, defer_size=None, stop_before_pixels=False,\n \n Parameters\n ----------\n- fp : str or file-like\n+ fp : str or PathLike or file-like\n Either a file-like object, or a string containing the file name. If a\n file-like object, the caller is responsible for closing it.\n defer_size : int or str or None, optional\n@@ -829,6 +829,7 @@ def dcmread(fp, defer_size=None, stop_before_pixels=False,\n \"\"\"\n # Open file if not already a file object\n caller_owns_file = True\n+ fp = path_from_pathlike(fp)\n if isinstance(fp, str):\n # caller provided a file name; we own the file handle\n caller_owns_file = False\ndiff --git a/pydicom/fileutil.py b/pydicom/fileutil.py\n--- a/pydicom/fileutil.py\n+++ b/pydicom/fileutil.py\n@@ -1,6 +1,8 @@\n # Copyright 2008-2018 pydicom authors. See LICENSE file for details.\n \"\"\"Functions for reading to certain bytes, e.g. delimiters.\"\"\"\n-\n+import os\n+import pathlib\n+import sys\n from struct import pack, unpack\n \n from pydicom.misc import size_in_bytes\n@@ -93,7 +95,7 @@ def read_undefined_length_value(fp,\n is_little_endian,\n delimiter_tag,\n defer_size=None,\n- read_size=1024*8):\n+ read_size=1024 * 8):\n \"\"\"Read until `delimiter_tag` and return the value up to that point.\n \n On completion, the file will be set to the first byte after the delimiter\n@@ -260,3 +262,32 @@ def read_delimiter_item(fp, delimiter):\n if length != 0:\n logger.warn(\"Expected delimiter item to have length 0, \"\n \"got %d at file position 0x%x\", length, fp.tell() - 4)\n+\n+\n+def path_from_pathlike(file_object):\n+ \"\"\"Returns the path if `file_object` is a path-like object, otherwise the\n+ original `file_object`.\n+\n+ Parameters\n+ ----------\n+ file_object: str or PathLike or file-like\n+\n+ Returns\n+ -------\n+ str or file-like\n+ the string representation of the given path object, or the object\n+ itself in case of an object not representing a path.\n+\n+ ..note:\n+\n+ ``PathLike`` objects have been introduced in Python 3.6. In Python 3.5,\n+ only objects of type :class:`pathlib.Path` are considered.\n+ \"\"\"\n+ if sys.version_info < (3, 6):\n+ if isinstance(file_object, pathlib.Path):\n+ return str(file_object)\n+ return file_object\n+ try:\n+ return os.fspath(file_object)\n+ except TypeError:\n+ return file_object\ndiff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -11,6 +11,7 @@\n from pydicom.dataelem import DataElement_from_raw\n from pydicom.dataset import Dataset, validate_file_meta\n from pydicom.filebase import DicomFile, DicomFileLike, DicomBytesIO\n+from pydicom.fileutil import path_from_pathlike\n from pydicom.multival import MultiValue\n from pydicom.tag import (Tag, ItemTag, ItemDelimiterTag, SequenceDelimiterTag,\n tag_in_exception)\n@@ -810,7 +811,7 @@ def dcmwrite(filename, dataset, write_like_original=True):\n \n Parameters\n ----------\n- filename : str or file-like\n+ filename : str or PathLike or file-like\n Name of file or the file-like to write the new DICOM file to.\n dataset : pydicom.dataset.FileDataset\n Dataset holding the DICOM information; e.g. an object read with\n@@ -883,6 +884,7 @@ def dcmwrite(filename, dataset, write_like_original=True):\n \n caller_owns_file = True\n # Open file if not already a file object\n+ filename = path_from_pathlike(filename)\n if isinstance(filename, str):\n fp = DicomFile(filename, 'wb')\n # caller provided a file name; we own the file handle\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -7,6 +7,7 @@\n from io import BytesIO\n import os\n import shutil\n+from pathlib import Path\n from struct import unpack\n import sys\n import tempfile\n@@ -114,6 +115,10 @@ def test_UTF8_filename(self):\n os.remove(utf8_filename)\n assert ds is not None\n \n+ def test_pathlib_path_filename(self):\n+ \"\"\"Check that file can be read using pathlib.Path\"\"\"\n+ ds = dcmread(Path(priv_SQ_name))\n+\n def test_RTPlan(self):\n \"\"\"Returns correct values for sample data elements in test\n RT Plan file.\ndiff --git a/pydicom/tests/test_fileutil.py b/pydicom/tests/test_fileutil.py\nnew file mode 100644\n--- /dev/null\n+++ b/pydicom/tests/test_fileutil.py\n@@ -0,0 +1,37 @@\n+# Copyright 2008-2020 pydicom authors. See LICENSE file for details.\n+\"\"\"Test suite for util functions\"\"\"\n+import sys\n+from io import BytesIO\n+from pathlib import Path\n+\n+import pytest\n+\n+from pydicom.fileutil import path_from_pathlike\n+\n+\n+class PathLike:\n+ \"\"\"Minimal example for path-like object\"\"\"\n+ def __init__(self, path: str):\n+ self.path = path\n+\n+ def __fspath__(self):\n+ return self.path\n+\n+\n+class TestPathFromPathLike:\n+ \"\"\"Test the fileutil module\"\"\"\n+\n+ def test_non_pathlike_is_returned_unaltered(self):\n+ assert 'test.dcm' == path_from_pathlike('test.dcm')\n+ assert path_from_pathlike(None) is None\n+ file_like = BytesIO()\n+ assert file_like == path_from_pathlike(file_like)\n+ assert 42 == path_from_pathlike(42)\n+\n+ def test_pathlib_path(self):\n+ assert 'test.dcm' == path_from_pathlike(Path('test.dcm'))\n+\n+ @pytest.mark.skipif(sys.version_info < (3, 6),\n+ reason=\"Path-like objects introduced in Python 3.6\")\n+ def test_path_like(self):\n+ assert 'test.dcm' == path_from_pathlike(PathLike('test.dcm'))\ndiff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -6,6 +6,7 @@\n from datetime import date, datetime, time, timedelta, timezone\n from io import BytesIO\n import os\n+from pathlib import Path\n from platform import python_implementation\n \n from struct import unpack\n@@ -137,6 +138,14 @@ def testJPEG2000(self):\n them identical (JPEG2K file).\"\"\"\n self.compare(jpeg_name)\n \n+ def test_pathlib_path_filename(self):\n+ \"\"\"Check that file can be written using pathlib.Path\"\"\"\n+ ds = dcmread(Path(ct_name))\n+ ds.save_as(self.file_out, write_like_original=True)\n+ self.file_out.seek(0)\n+ ds1 = dcmread(self.file_out)\n+ assert ds.PatientName == ds1.PatientName\n+\n def testListItemWriteBack(self):\n \"\"\"Change item in a list and confirm\n it is written to file\"\"\"\n", "problem_statement": "dcmread cannot handle pathlib.Path objects\n**Describe the bug**\r\nThe `dcmread()` currently fails when passed an instance of `pathlib.Path`. The problem is the following line:\r\nhttps://github.com/pydicom/pydicom/blob/8b0bbaf92d7a8218ceb94dedbee3a0463c5123e3/pydicom/filereader.py#L832\r\n\r\n**Expected behavior**\r\n`dcmread()` should open and read the file to which the `pathlib.Path` object points.\r\n\r\nThe line above should probably be:\r\n```python\r\nif isinstance(fp, (str, Path)):\r\n````\r\n\r\n**Steps To Reproduce**\r\n```python\r\nfrom pathlib import Path\r\nfrom pydicom.filereader import dcmread\r\n\r\ndcm_filepath = Path('path/to/file')\r\ndcmread(dcm_filepath)\r\n```\n", "hints_text": "Good point. We could use `os.fspath`, but that is only available from Python 3.6 onwards, so we probably have to add a respective check...\nThe `save_as()` method of `Dataset` has the same issue.\nYes, I noticed. I'm on it.\nYep. I actually started writing code for it at one point, but got side-tracked with other issues. Basically just wrapping the argument in str() fixes it.\r\n", "created_at": "2020-02-09T18:36:33Z", "version": "1.4", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_empty_numbers_tag", "pydicom/tests/test_filereader.py::TestReader::test_UTF8_filename", "pydicom/tests/test_filereader.py::TestReader::test_pathlib_path_filename", "pydicom/tests/test_filereader.py::TestReader::test_RTPlan", "pydicom/tests/test_filereader.py::TestReader::test_RTDose", "pydicom/tests/test_filereader.py::TestReader::test_CT", "pydicom/tests/test_filereader.py::TestReader::test_CT_PixelData", "pydicom/tests/test_filereader.py::TestReader::test_no_force", "pydicom/tests/test_filereader.py::TestReader::test_RTStruct", "pydicom/tests/test_filereader.py::TestReader::test_dir", "pydicom/tests/test_filereader.py::TestReader::test_MR", "pydicom/tests/test_filereader.py::TestReader::test_deflate", "pydicom/tests/test_filereader.py::TestReader::test_no_pixels_read", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_SQ", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_tag", "pydicom/tests/test_filereader.py::TestReader::test_tag_with_unknown_length_tag_too_short", "pydicom/tests/test_filereader.py::TestReader::test_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_nested_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_no_meta_group_length", "pydicom/tests/test_filereader.py::TestReader::test_no_transfer_syntax_in_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_little_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_big_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_planar_config", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::TestReader::test_long_specific_char_set", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::TestReader::test_group_length_wrong", "pydicom/tests/test_filereader.py::TestReader::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_empty_file", "pydicom/tests/test_filereader.py::TestReader::test_empty_specific_character_set", "pydicom/tests/test_filereader.py::TestReader::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_seq_item_looks_like_explicit_VR", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_AE", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_SV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_explicit_little", "pydicom/tests/test_filereader.py::TestDeferredRead::test_time_check", "pydicom/tests/test_filereader.py::TestDeferredRead::test_file_exists", "pydicom/tests/test_filereader.py::TestDeferredRead::test_values_identical", "pydicom/tests/test_filereader.py::TestDeferredRead::test_zipped_deferred", "pydicom/tests/test_filereader.py::TestDeferredRead::test_filelike_deferred", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelDataArray", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_object", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_like_object", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit", "pydicom/tests/test_fileutil.py::TestPathFromPathLike::test_non_pathlike_is_returned_unaltered", "pydicom/tests/test_fileutil.py::TestPathFromPathLike::test_pathlib_path", "pydicom/tests/test_fileutil.py::TestPathFromPathLike::test_path_like", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "PASS_TO_PASS": [], "environment_setup_commit": "5098c9147fadcb3e5918487036867931435adeb8"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1608", "base_commit": "37dd49e2754a10db22e7cde2ac18aa8afc1f3af6", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -512,9 +512,10 @@ def _convert_value(self, val: Any) -> Any:\n val.append\n except AttributeError: # not a list\n return self._convert(val)\n- else:\n- return MultiValue(self._convert, val,\n- validation_mode=self.validation_mode)\n+ if len(val) == 1:\n+ return self._convert(val[0])\n+ return MultiValue(self._convert, val,\n+ validation_mode=self.validation_mode)\n \n def _convert(self, val: Any) -> Any:\n \"\"\"Convert `val` to an appropriate type for the element's VR.\"\"\"\n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -1,6 +1,7 @@\n # -*- coding: utf-8 -*-\n # Copyright 2008-2019 pydicom authors. See LICENSE file for details.\n import json\n+from unittest import mock\n \n import pytest\n \n@@ -271,13 +272,14 @@ def test_sort_order(self):\n assert ds_json.index('\"00100020\"') < ds_json.index('\"00100030\"')\n assert ds_json.index('\"00100030\"') < ds_json.index('\"00100040\"')\n \n- def test_suppress_invalid_tags(self):\n+ @mock.patch(\"pydicom.DataElement.to_json_dict\", side_effect=ValueError)\n+ def test_suppress_invalid_tags(self, _):\n \"\"\"Test tags that raise exceptions don't if suppress_invalid_tags True.\n \"\"\"\n ds = Dataset()\n- ds.add_new(0x00100010, 'PN', ['Jane^Doe'])\n+ ds.add_new(0x00100010, 'PN', 'Jane^Doe')\n \n- with pytest.raises(Exception):\n+ with pytest.raises(ValueError):\n ds.to_json_dict()\n \n ds_json = ds.to_json_dict(suppress_invalid_tags=True)\ndiff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -1540,20 +1540,27 @@ def test_set_value(vr, pytype, vm0, vmN, keyword, disable_value_validation):\n assert value == elem.value\n \n # Test VM = 1\n+ if vr != 'SQ':\n+ ds = Dataset()\n+ value = vmN[0]\n+ setattr(ds, keyword, value)\n+ elem = ds[keyword]\n+ assert elem.value == value\n+ assert value == elem.value\n+\n+ # Test VM = 1 as list\n ds = Dataset()\n value = vmN[0]\n+ setattr(ds, keyword, [value])\n+ elem = ds[keyword]\n if vr == 'SQ':\n- setattr(ds, keyword, [value])\n- elem = ds[keyword]\n assert elem.value[0] == value\n assert value == elem.value[0]\n else:\n- setattr(ds, keyword, value)\n- elem = ds[keyword]\n assert elem.value == value\n assert value == elem.value\n \n- if vr[0] == 'O':\n+ if vr[0] == 'O' or vr == 'UN':\n return\n \n # Test VM > 1\n", "problem_statement": "Unable to assign single element list to PN field\nI am getting `AttributeError` while trying to assign a list of single element to a `PN` field.\r\nIt's converting `val` to a 2D array [here](https://github.com/pydicom/pydicom/blob/master/pydicom/filewriter.py#L328) when `VM` is 1. \r\n\r\n**Code**\r\n```\r\n>>> from pydicom import dcmread, dcmwrite\r\n>>> ds = dcmread(\"SOP1.dcm\")\r\n>>> a = [\"name1\"]\r\n>>> b = [\"name1\", \"name2\"]\r\n>>> ds.PatientName = a\r\n>>> dcmwrite(\"out.dcm\", ds) # throws the error below\r\n>>> ds.PatientName = b\r\n>>> dcmwrite(\"out.dcm\", ds) # works fine\r\n```\r\n\r\n**Error**\r\n```\r\nTraceback (most recent call last):\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/tag.py\", line 28, in tag_in_exception\r\n yield\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 662, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 562, in write_data_element\r\n fn(buffer, elem, encodings=encodings) # type: ignore[operator]\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 333, in write_PN\r\n enc = b'\\\\'.join([elem.encode(encodings) for elem in val])\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 333, in <listcomp>\r\n enc = b'\\\\'.join([elem.encode(encodings) for elem in val])\r\nAttributeError: 'MultiValue' object has no attribute 'encode'\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 1153, in dcmwrite\r\n _write_dataset(fp, dataset, write_like_original)\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 889, in _write_dataset\r\n write_dataset(fp, get_item(dataset, slice(0x00010000, None)))\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 662, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \"/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py\", line 131, in __exit__\r\n self.gen.throw(type, value, traceback)\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/tag.py\", line 32, in tag_in_exception\r\n raise type(exc)(msg) from exc\r\nAttributeError: With tag (0010, 0010) got exception: 'MultiValue' object has no attribute 'encode'\r\nTraceback (most recent call last):\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/tag.py\", line 28, in tag_in_exception\r\n yield\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 662, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 562, in write_data_element\r\n fn(buffer, elem, encodings=encodings) # type: ignore[operator]\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 333, in write_PN\r\n enc = b'\\\\'.join([elem.encode(encodings) for elem in val])\r\n File \"/Users/neonbulb/virtualenv/deid/lib/python3.8/site-packages/pydicom/filewriter.py\", line 333, in <listcomp>\r\n enc = b'\\\\'.join([elem.encode(encodings) for elem in val])\r\nAttributeError: 'MultiValue' object has no attribute 'encode'\r\n```\n", "hints_text": "Not sure if this is a bug, but at least it is unexpected behavior. Shall be easy to fix.", "created_at": "2022-02-24T19:31:55Z", "version": "2.2", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::test_set_value[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_set_value[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_set_value[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_set_value[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_set_value[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_set_value[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_set_value[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_set_value[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_set_value[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_set_value[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_set_value[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_set_value[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_set_value[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_set_value[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[OV-bytes-vm020-vmN20-SelectorOVValue]", "pydicom/tests/test_valuerep.py::test_set_value[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_set_value[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_set_value[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_set_value[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_set_value[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_set_value[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_set_value[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_set_value[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_set_value[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_set_value[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_set_value[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_set_value[UV-int-vm037-vmN37-SelectorUVValue]"], "PASS_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestDataSetToJson::test_suppress_invalid_tags", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_2", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_within_SQ", "pydicom/tests/test_json.py::TestNumeric::test_numeric_values", "pydicom/tests/test_json.py::TestNumeric::test_numeric_types", "pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestTM::test_pickling_tm_from_time", "pydicom/tests/test_valuerep.py::TestTM::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestTM::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_comparison", "pydicom/tests/test_valuerep.py::TestTM::test_time_behavior", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDT::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDT::test_comparison", "pydicom/tests/test_valuerep.py::TestDT::test_datetime_behavior", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDA::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDA::test_comparison", "pydicom/tests/test_valuerep.py::TestDA::test_date_behavior", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[3.14159265358979]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[-1234.456e78]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E-5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E+5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[+1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[42", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[nan]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[3.141592653589793]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1,000]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[127.0.0.1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1.e]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.0-1.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.0-0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.0--0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.123-0.123]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.321--0.321]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1e-05-1e-05]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[3.141592653589793-3.14159265358979]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-3.141592653589793--3.1415926535898]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[5.385940192876374e-07-5.3859401929e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-5.385940192876374e-07--5.385940193e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[12342534378.125532-12342534378.1255]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[64070869985876.78-64070869985876.8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.7976931348623157e+308-1.797693135e+308]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_wrong_type", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_new_empty[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_new_empty[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str_value[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str_value[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_length", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat_auto_format", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-nan]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan2]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSfloat::test_hash", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_new_empty", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_str_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_repr", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_string_too_long", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_string_too_long_raises", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val4]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val5]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val6]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val7]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal_auto_format", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_hash", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_str_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestIS::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestIS::test_hash", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains", "pydicom/tests/test_valuerep.py::TestPersonName::test_length", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_veterinary", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator_from_bytes", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time", "pydicom/tests/test_valuerep.py::test_person_name_unicode_warns", "pydicom/tests/test_valuerep.py::test_set_value[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OV-bytes-vm020-vmN20-SelectorOVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UV-int-vm037-vmN37-SelectorUVValue]", "pydicom/tests/test_valuerep.py::TestVR::test_behavior", "pydicom/tests/test_valuerep.py::TestVR::test_all_present"], "environment_setup_commit": "0fa18d2a2179c92efc22200ed6b3689e66cecf92"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-839", "base_commit": "da9e0df8da28a35596f830379341a379de8ac439", "patch": "diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -72,7 +72,10 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):\n # PixelRepresentation is usually set in the root dataset\n while 'PixelRepresentation' not in ds and ds.parent:\n ds = ds.parent\n- if ds.PixelRepresentation == 0:\n+ # if no pixel data is present, none if these tags is used,\n+ # so we can just ignore a missing PixelRepresentation in this case\n+ if ('PixelRepresentation' not in ds and 'PixelData' not in ds or\n+ ds.PixelRepresentation == 0):\n elem.VR = 'US'\n byte_type = 'H'\n else:\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -671,9 +671,15 @@ def test_pixel_representation_vm_one(self):\n assert 1 == ds.SmallestValidPixelValue\n assert 'SS' == ds[0x00280104].VR\n \n- # If no PixelRepresentation AttributeError shall be raised\n+ # If no PixelRepresentation and no PixelData is present 'US' is set\n ref_ds = Dataset()\n ref_ds.SmallestValidPixelValue = b'\\x00\\x01' # Big endian 1\n+ ds = correct_ambiguous_vr(deepcopy(ref_ds), True)\n+ assert 'US' == ds[0x00280104].VR\n+\n+ # If no PixelRepresentation but PixelData is present\n+ # AttributeError shall be raised\n+ ref_ds.PixelData = b'123'\n with pytest.raises(AttributeError,\n match=r\"Failed to resolve ambiguous VR for tag \"\n r\"\\(0028, 0104\\):.* 'PixelRepresentation'\"):\n@@ -697,9 +703,14 @@ def test_pixel_representation_vm_three(self):\n assert [256, 1, 16] == ds.LUTDescriptor\n assert 'SS' == ds[0x00283002].VR\n \n- # If no PixelRepresentation AttributeError shall be raised\n+ # If no PixelRepresentation and no PixelData is present 'US' is set\n ref_ds = Dataset()\n ref_ds.LUTDescriptor = b'\\x01\\x00\\x00\\x01\\x00\\x10'\n+ ds = correct_ambiguous_vr(deepcopy(ref_ds), True)\n+ assert 'US' == ds[0x00283002].VR\n+\n+ # If no PixelRepresentation AttributeError shall be raised\n+ ref_ds.PixelData = b'123'\n with pytest.raises(AttributeError,\n match=r\"Failed to resolve ambiguous VR for tag \"\n r\"\\(0028, 3002\\):.* 'PixelRepresentation'\"):\n@@ -928,6 +939,13 @@ def test_correct_ambiguous_data_element(self):\n \"\"\"Test correct ambiguous US/SS element\"\"\"\n ds = Dataset()\n ds.PixelPaddingValue = b'\\xfe\\xff'\n+ out = correct_ambiguous_vr_element(ds[0x00280120], ds, True)\n+ # assume US if PixelData is not set\n+ assert 'US' == out.VR\n+\n+ ds = Dataset()\n+ ds.PixelPaddingValue = b'\\xfe\\xff'\n+ ds.PixelData = b'3456'\n with pytest.raises(AttributeError,\n match=r\"Failed to resolve ambiguous VR for tag \"\n r\"\\(0028, 0120\\):.* 'PixelRepresentation'\"):\n", "problem_statement": "Ambiguous VR element could be read in <=1.1.0 but is broken in >=1.2.0\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\nAttribute Error thrown when printing (0x0028, 0x0120) PixelPaddingValue\r\n\r\n#### Steps/Code to Reproduce\r\nUsing pydicom 1.2.2 and above (including master branch as of issue creation date):\r\n```\r\nfrom pydicom import dcmread\r\n\r\nds = dcmread('rtss.dcm')\r\nds\r\n\r\nException in thread Thread-1:\r\nTraceback (most recent call last):\r\n File \"/Users/apanchal/Projects/venvs/dicom/lib/python3.7/site-packages/pydicom/filewriter.py\", line 157, in correct_ambiguous_vr_element\r\n _correct_ambiguous_vr_element(elem, ds, is_little_endian)\r\n File \"/Users/apanchal/Projects/venvs/dicom/lib/python3.7/site-packages/pydicom/filewriter.py\", line 75, in _correct_ambiguous_vr_element\r\n if ds.PixelRepresentation == 0:\r\n File \"/Users/apanchal/Projects/venvs/dicom/lib/python3.7/site-packages/pydicom/dataset.py\", line 711, in __getattr__\r\n return super(Dataset, self).__getattribute__(name)\r\nAttributeError: 'FileDataset' object has no attribute 'PixelRepresentation'\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py\", line 917, in _bootstrap_inner\r\n self.run()\r\n File \"/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py\", line 865, in run\r\n self._target(*self._args, **self._kwargs)\r\n File \"/Users/apanchal/Projects/test.py\", line 107, in processing_thread\r\n dp.ds, name, patientid, patientdob)\r\n File \"/Users/apanchal/Projects/test.py\", line 144, in UpdateElements\r\n for item in data:\r\n File \"/Users/apanchal/Projects/venvs/dicom/lib/python3.7/site-packages/pydicom/dataset.py\", line 1045, in __iter__\r\n yield self[tag]\r\n File \"/Users/apanchal/Projects/venvs/dicom/lib/python3.7/site-packages/pydicom/dataset.py\", line 805, in __getitem__\r\n self[tag], self, data_elem[6])\r\n File \"/Users/apanchal/Projects/venvs/dicom/lib/python3.7/site-packages/pydicom/filewriter.py\", line 161, in correct_ambiguous_vr_element\r\n raise AttributeError(reason)\r\nAttributeError: Failed to resolve ambiguous VR for tag (0028, 0120): 'FileDataset' object has no attribute 'PixelRepresentation'\r\n```\r\n\r\nAnonymized RTSTRUCT file is attached: [RTSTRUCT.zip](https://github.com/pydicom/pydicom/files/3124625/RTSTRUCT.zip)\r\n\r\n#### Expected Results\r\nThe dataset is printed. This worked in pydicom 1.1.0 and below.\r\n\r\nSince `PixelRepresentation` is not defined in the dataset, this attribute cannot be printed anymore.\r\n\r\nWhat's strange is that according to the standard PixelPaddingValue (0028, 0120) is 1C for RTSTRUCT, but in this file it has no other tags referencing PixelData. So it probably should not have been included by the vendor.\r\n\r\nI am wondering if there should be another path like in #809 that can handle the missing PixelRepresentation attribute.\r\n\r\n#### Actual Results\r\n```AttributeError: Failed to resolve ambiguous VR for tag (0028, 0120): 'FileDataset' object has no attribute 'PixelRepresentation'```\r\n\r\n#### Versions\r\n```\r\nDarwin-17.7.0-x86_64-i386-64bit\r\nPython 3.7.0 (default, Jul 23 2018, 20:22:55) \r\n[Clang 9.1.0 (clang-902.0.39.2)]\r\npydicom 1.2.2\r\n```\n", "hints_text": "Hm, in this case `PixelPadding` doesn't make sense, as there is no `PixelData` present, so we could just ignore it (e.g. use some default VR). With `PixelData` present, a missing `PixelRepresentation` would be a real DICOM violation, that would justify an exception as with the current behavior in my opinion. \r\nThe same is true for all tags with ambiguous VR dependent on `PixelRepresentation`.\r\nIf this is sufficient, I can put together a respective PR. ", "created_at": "2019-04-28T18:27:57Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-995", "base_commit": "29be72498a4f4131808a45843b15692234ae7652", "patch": "diff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -34,8 +34,9 @@\n from pydicom.datadict import (tag_for_keyword, keyword_for_tag,\n repeater_has_keyword)\n from pydicom.dataelem import DataElement, DataElement_from_raw, RawDataElement\n-from pydicom.pixel_data_handlers.util import (convert_color_space,\n- reshape_pixel_array)\n+from pydicom.pixel_data_handlers.util import (\n+ convert_color_space, reshape_pixel_array, get_image_pixel_ids\n+)\n from pydicom.tag import Tag, BaseTag, tag_in_exception\n from pydicom.uid import (ExplicitVRLittleEndian, ImplicitVRLittleEndian,\n ExplicitVRBigEndian, PYDICOM_IMPLEMENTATION_UID)\n@@ -1302,20 +1303,11 @@ def convert_pixel_data(self, handler_name=''):\n decompressed and any related data elements are changed accordingly.\n \"\"\"\n # Check if already have converted to a NumPy array\n- # Also check if self.PixelData has changed. If so, get new NumPy array\n- keywords = ['PixelData', 'FloatPixelData', 'DoubleFloatPixelData']\n- px_keyword = [kw for kw in keywords if kw in self]\n- if len(px_keyword) != 1:\n- raise AttributeError(\n- \"Unable to convert the pixel data: one of Pixel Data, Float \"\n- \"Pixel Data or Double Float Pixel Data must be present in \"\n- \"the dataset\"\n- )\n-\n+ # Also check if pixel data has changed. If so, get new NumPy array\n already_have = True\n if not hasattr(self, \"_pixel_array\"):\n already_have = False\n- elif self._pixel_id != id(getattr(self, px_keyword[0])):\n+ elif self._pixel_id != get_image_pixel_ids(self):\n already_have = False\n \n if already_have:\n@@ -1451,9 +1443,7 @@ def _do_pixel_data_conversion(self, handler):\n self._pixel_array, 'YBR_FULL', 'RGB'\n )\n \n- keywords = ['PixelData', 'FloatPixelData', 'DoubleFloatPixelData']\n- px_keyword = [kw for kw in keywords if kw in self]\n- self._pixel_id = id(getattr(self, px_keyword[0]))\n+ self._pixel_id = get_image_pixel_ids(self)\n \n def decompress(self, handler_name=''):\n \"\"\"Decompresses *Pixel Data* and modifies the :class:`Dataset`\ndiff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py\n--- a/pydicom/pixel_data_handlers/util.py\n+++ b/pydicom/pixel_data_handlers/util.py\n@@ -750,6 +750,59 @@ def get_expected_length(ds, unit='bytes'):\n return length\n \n \n+def get_image_pixel_ids(ds):\n+ \"\"\"Return a dict of the pixel data affecting element's :func:`id` values.\n+\n+ +------------------------------------------------+\n+ | Element |\n+ +-------------+---------------------------+------+\n+ | Tag | Keyword | Type |\n+ +=============+===========================+======+\n+ | (0028,0002) | SamplesPerPixel | 1 |\n+ +-------------+---------------------------+------+\n+ | (0028,0004) | PhotometricInterpretation | 1 |\n+ +-------------+---------------------------+------+\n+ | (0028,0006) | PlanarConfiguration | 1C |\n+ +-------------+---------------------------+------+\n+ | (0028,0008) | NumberOfFrames | 1C |\n+ +-------------+---------------------------+------+\n+ | (0028,0010) | Rows | 1 |\n+ +-------------+---------------------------+------+\n+ | (0028,0011) | Columns | 1 |\n+ +-------------+---------------------------+------+\n+ | (0028,0100) | BitsAllocated | 1 |\n+ +-------------+---------------------------+------+\n+ | (0028,0103) | PixelRepresentation | 1 |\n+ +-------------+---------------------------+------+\n+ | (7FE0,0008) | FloatPixelData | 1C |\n+ +-------------+---------------------------+------+\n+ | (7FE0,0009) | DoubleFloatPixelData | 1C |\n+ +-------------+---------------------------+------+\n+ | (7FE0,0010) | PixelData | 1C |\n+ +-------------+---------------------------+------+\n+\n+ Parameters\n+ ----------\n+ ds : Dataset\n+ The :class:`~pydicom.dataset.Dataset` containing the pixel data.\n+\n+ Returns\n+ -------\n+ dict\n+ A dict containing the :func:`id` values for the elements that affect\n+ the pixel data.\n+\n+ \"\"\"\n+ keywords = [\n+ 'SamplesPerPixel', 'PhotometricInterpretation', 'PlanarConfiguration',\n+ 'NumberOfFrames', 'Rows', 'Columns', 'BitsAllocated',\n+ 'PixelRepresentation', 'FloatPixelData', 'DoubleFloatPixelData',\n+ 'PixelData'\n+ ]\n+\n+ return {kw: id(getattr(ds, kw, None)) for kw in keywords}\n+\n+\n def pixel_dtype(ds, as_float=False):\n \"\"\"Return a :class:`numpy.dtype` for the pixel data in `ds`.\n \n", "test_patch": "diff --git a/pydicom/tests/test_dataset.py b/pydicom/tests/test_dataset.py\n--- a/pydicom/tests/test_dataset.py\n+++ b/pydicom/tests/test_dataset.py\n@@ -11,6 +11,7 @@\n from pydicom import dcmread\n from pydicom.filebase import DicomBytesIO\n from pydicom.overlay_data_handlers import numpy_handler as NP_HANDLER\n+from pydicom.pixel_data_handlers.util import get_image_pixel_ids\n from pydicom.sequence import Sequence\n from pydicom.tag import Tag\n from pydicom.uid import (\n@@ -1142,10 +1143,10 @@ def test_pixel_array_already_have(self):\n # Test that _pixel_array is returned unchanged unless required\n fpath = get_testdata_files(\"CT_small.dcm\")[0]\n ds = dcmread(fpath)\n- ds._pixel_id = id(ds.PixelData)\n+ ds._pixel_id = get_image_pixel_ids(ds)\n ds._pixel_array = 'Test Value'\n ds.convert_pixel_data()\n- assert id(ds.PixelData) == ds._pixel_id\n+ assert get_image_pixel_ids(ds) == ds._pixel_id\n assert 'Test Value' == ds._pixel_array\n \n def test_pixel_array_id_changed(self):\n@@ -1277,17 +1278,6 @@ def test_update_with_dataset(self):\n ds2.update(ds)\n assert 'TestC' == ds2.PatientName\n \n- def test_convert_pixel_data_no_px(self):\n- \"\"\"Test convert_pixel_data() with no pixel data elements.\"\"\"\n- ds = Dataset()\n- msg = (\n- r\"Unable to convert the pixel data: one of Pixel Data, Float \"\n- r\"Pixel Data or Double Float Pixel Data must be present in \"\n- r\"the dataset\"\n- )\n- with pytest.raises(AttributeError, match=msg):\n- ds.convert_pixel_data()\n-\n \n class TestDatasetElements(object):\n \"\"\"Test valid assignments of data elements\"\"\"\ndiff --git a/pydicom/tests/test_numpy_pixel_data.py b/pydicom/tests/test_numpy_pixel_data.py\n--- a/pydicom/tests/test_numpy_pixel_data.py\n+++ b/pydicom/tests/test_numpy_pixel_data.py\n@@ -146,6 +146,9 @@\n JPEG_2K = get_testdata_files(\"JPEG2000.dcm\")[0]\n # RLE Lossless\n RLE = get_testdata_files(\"MR_small_RLE.dcm\")[0]\n+# No Image Pixel module\n+NO_PIXEL = get_testdata_files(\"rtplan.dcm\")[0]\n+\n \n # Transfer Syntaxes (non-retired + Explicit VR Big Endian)\n SUPPORTED_SYNTAXES = [\n@@ -471,6 +474,17 @@ def needs_convert(ds):\n # Reset\n NP_HANDLER.needs_to_convert_to_RGB = orig_fn\n \n+ def test_dataset_pixel_array_no_pixels(self):\n+ \"\"\"Test good exception message if no pixel data in dataset.\"\"\"\n+ ds = dcmread(NO_PIXEL)\n+ msg = (\n+ r\"Unable to convert the pixel data: one of Pixel Data, Float \"\n+ r\"Pixel Data or Double Float Pixel Data must be present in the \"\n+ r\"dataset\"\n+ )\n+ with pytest.raises(AttributeError, match=msg):\n+ ds.pixel_array\n+\n @pytest.mark.parametrize(\"fpath, data\", REFERENCE_DATA_UNSUPPORTED)\n def test_can_access_unsupported_dataset(self, fpath, data):\n \"\"\"Test can read and access elements in unsupported datasets.\"\"\"\n", "problem_statement": "Dataset.pixel_array doesn't change unless PixelData does\n#### Description\r\nCurrently `ds.pixel_array` produces a numpy array that depends on element values for Rows, Columns, Samples Per Pixel, etc, however the code for `ds.pixel_array` only changes the returned array if the value for `ds.PixelData` changes. This may lead to confusion/undesirable behaviour if the values for related elements are changed after `ds.pixel_array` is called but not the underlying pixel data.\r\n\r\nI can't think of any real use cases except maybe in an interactive session when debugging a non-conformant dataset, but I suggest we change the way `Dataset._pixel_id` is calculated so that it takes into account changes in related elements as well.\r\n\n", "hints_text": "", "created_at": "2019-12-17T23:21:50Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_dataset.py::TestDataset::test_attribute_error_in_property", "pydicom/tests/test_dataset.py::TestDataset::test_for_stray_raw_data_element", "pydicom/tests/test_dataset.py::TestDataset::test_attribute_error_in_property_correct_debug", "pydicom/tests/test_dataset.py::TestDataset::test_tag_exception_print", "pydicom/tests/test_dataset.py::TestDataset::test_tag_exception_walk", "pydicom/tests/test_dataset.py::TestDataset::test_set_new_data_element_by_name", "pydicom/tests/test_dataset.py::TestDataset::test_set_existing_data_element_by_name", "pydicom/tests/test_dataset.py::TestDataset::test_set_non_dicom", "pydicom/tests/test_dataset.py::TestDataset::test_membership", "pydicom/tests/test_dataset.py::TestDataset::test_contains", "pydicom/tests/test_dataset.py::TestDataset::test_clear", "pydicom/tests/test_dataset.py::TestDataset::test_pop", "pydicom/tests/test_dataset.py::TestDataset::test_pop_using_tuple", "pydicom/tests/test_dataset.py::TestDataset::test_pop_using_keyword", "pydicom/tests/test_dataset.py::TestDataset::test_popitem", "pydicom/tests/test_dataset.py::TestDataset::test_setdefault", "pydicom/tests/test_dataset.py::TestDataset::test_setdefault_tuple", "pydicom/tests/test_dataset.py::TestDataset::test_setdefault_use_value", "pydicom/tests/test_dataset.py::TestDataset::test_setdefault_keyword", "pydicom/tests/test_dataset.py::TestDataset::test_get_exists1", "pydicom/tests/test_dataset.py::TestDataset::test_get_exists2", "pydicom/tests/test_dataset.py::TestDataset::test_get_exists3", "pydicom/tests/test_dataset.py::TestDataset::test_get_exists4", "pydicom/tests/test_dataset.py::TestDataset::test_get_default1", "pydicom/tests/test_dataset.py::TestDataset::test_get_default2", "pydicom/tests/test_dataset.py::TestDataset::test_get_default3", "pydicom/tests/test_dataset.py::TestDataset::test_get_default4", "pydicom/tests/test_dataset.py::TestDataset::test_get_raises", "pydicom/tests/test_dataset.py::TestDataset::test_get_from_raw", "pydicom/tests/test_dataset.py::TestDataset::test__setitem__", "pydicom/tests/test_dataset.py::TestDataset::test_matching_tags", "pydicom/tests/test_dataset.py::TestDataset::test_named_member_updated", "pydicom/tests/test_dataset.py::TestDataset::test_update", "pydicom/tests/test_dataset.py::TestDataset::test_dir_subclass", "pydicom/tests/test_dataset.py::TestDataset::test_dir", "pydicom/tests/test_dataset.py::TestDataset::test_dir_filter", "pydicom/tests/test_dataset.py::TestDataset::test_delete_dicom_attr", "pydicom/tests/test_dataset.py::TestDataset::test_delete_dicom_command_group_length", "pydicom/tests/test_dataset.py::TestDataset::test_delete_other_attr", "pydicom/tests/test_dataset.py::TestDataset::test_delete_dicom_attr_we_dont_have", "pydicom/tests/test_dataset.py::TestDataset::test_delete_item_long", "pydicom/tests/test_dataset.py::TestDataset::test_delete_item_tuple", "pydicom/tests/test_dataset.py::TestDataset::test_delete_non_existing_item", "pydicom/tests/test_dataset.py::TestDataset::test_equality_no_sequence", "pydicom/tests/test_dataset.py::TestDataset::test_equality_private", "pydicom/tests/test_dataset.py::TestDataset::test_equality_sequence", "pydicom/tests/test_dataset.py::TestDataset::test_equality_not_dataset", "pydicom/tests/test_dataset.py::TestDataset::test_equality_unknown", "pydicom/tests/test_dataset.py::TestDataset::test_equality_inheritance", "pydicom/tests/test_dataset.py::TestDataset::test_equality_elements", "pydicom/tests/test_dataset.py::TestDataset::test_inequality", "pydicom/tests/test_dataset.py::TestDataset::test_hash", "pydicom/tests/test_dataset.py::TestDataset::test_property", "pydicom/tests/test_dataset.py::TestDataset::test_add_repeater_elem_by_keyword", "pydicom/tests/test_dataset.py::TestDataset::test_setitem_slice_raises", "pydicom/tests/test_dataset.py::TestDataset::test_getitem_slice_raises", "pydicom/tests/test_dataset.py::TestDataset::test_empty_slice", "pydicom/tests/test_dataset.py::TestDataset::test_getitem_slice", "pydicom/tests/test_dataset.py::TestDataset::test_getitem_slice_ffff", "pydicom/tests/test_dataset.py::TestDataset::test_delitem_slice", "pydicom/tests/test_dataset.py::TestDataset::test_group_dataset", "pydicom/tests/test_dataset.py::TestDataset::test_get_item", "pydicom/tests/test_dataset.py::TestDataset::test_get_item_slice", "pydicom/tests/test_dataset.py::TestDataset::test_get_private_item", "pydicom/tests/test_dataset.py::TestDataset::test_private_block", "pydicom/tests/test_dataset.py::TestDataset::test_add_new_private_tag", "pydicom/tests/test_dataset.py::TestDataset::test_delete_private_tag", "pydicom/tests/test_dataset.py::TestDataset::test_private_creators", "pydicom/tests/test_dataset.py::TestDataset::test_is_original_encoding", "pydicom/tests/test_dataset.py::TestDataset::test_remove_private_tags", "pydicom/tests/test_dataset.py::TestDataset::test_data_element", "pydicom/tests/test_dataset.py::TestDataset::test_iterall", "pydicom/tests/test_dataset.py::TestDataset::test_save_as", "pydicom/tests/test_dataset.py::TestDataset::test_with", "pydicom/tests/test_dataset.py::TestDataset::test_exit_exception", "pydicom/tests/test_dataset.py::TestDataset::test_pixel_array_already_have", "pydicom/tests/test_dataset.py::TestDataset::test_pixel_array_id_changed", "pydicom/tests/test_dataset.py::TestDataset::test_pixel_array_unknown_syntax", "pydicom/tests/test_dataset.py::TestDataset::test_formatted_lines", "pydicom/tests/test_dataset.py::TestDataset::test_formatted_lines_known_uid", "pydicom/tests/test_dataset.py::TestDataset::test_set_convert_private_elem_from_raw", "pydicom/tests/test_dataset.py::TestDataset::test_top", "pydicom/tests/test_dataset.py::TestDataset::test_trait_names", "pydicom/tests/test_dataset.py::TestDataset::test_walk", "pydicom/tests/test_dataset.py::TestDataset::test_update_with_dataset", "pydicom/tests/test_dataset.py::TestDatasetElements::test_sequence_assignment", "pydicom/tests/test_dataset.py::TestDatasetElements::test_ensure_file_meta", "pydicom/tests/test_dataset.py::TestDatasetElements::test_fix_meta_info", "pydicom/tests/test_dataset.py::TestDatasetElements::test_validate_and_correct_file_meta", "pydicom/tests/test_dataset.py::TestFileDataset::test_pickle", "pydicom/tests/test_dataset.py::TestFileDataset::test_pickle_modified", "pydicom/tests/test_dataset.py::TestFileDataset::test_equality_file_meta", "pydicom/tests/test_dataset.py::TestFileDataset::test_creation_with_container", "pydicom/tests/test_dataset.py::TestFileDataset::test_works_as_expected_within_numpy_array", "pydicom/tests/test_dataset.py::TestFileDataset::test_dataset_overrides_all_dict_attributes", "pydicom/tests/test_dataset.py::TestDatasetOverlayArray::test_no_possible", "pydicom/tests/test_dataset.py::TestDatasetOverlayArray::test_possible_not_available", "pydicom/tests/test_dataset.py::TestDatasetOverlayArray::test_possible_available", "pydicom/tests/test_dataset.py::TestDatasetOverlayArray::test_handler_raises", "pydicom/tests/test_numpy_pixel_data.py::test_unsupported_syntaxes", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_supported_dataset", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_pixel_array_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_unsupported_syntax_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_dataset_pixel_array_handler_needs_convert", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_dataset_pixel_array_no_pixels", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_8bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[numpy]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[NumPy]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[np]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[np_handler]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[numpy_handler]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_16bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_32bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame_odd_size", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame_ybr422", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/liver_1frame.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/liver.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/OBXXXX1A.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_small_odd.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_ybr_full_422_uncompressed.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/OBXXXX1A_2frame.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_2frame.dcm-data7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/MR_small.dcm-data8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/emri_small.dcm-data9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_16bit.dcm-data10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_16bit_2frame.dcm-data11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/rtdose_1frame.dcm-data12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/rtdose.dcm-data13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_32bit.dcm-data14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_32bit_2frame.dcm-data15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_3frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame_padded", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_10frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_float_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_float_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_64bit_float_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_64bit_float_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/liver_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/liver_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/liver.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/liver_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/OBXXXX1A.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/OBXXXX1A_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/OBXXXX1A_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/OBXXXX1A_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/MR_small.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/MR_small_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/emri_small.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/emri_small_big_endian.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_16bit.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_expb_16bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_16bit_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_expb_16bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/rtdose_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/rtdose_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/rtdose.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/rtdose_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_32bit.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_expb_32bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_32bit_2frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__1.3/pydicom/data/test_files/SC_rgb_expb_32bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_endianness_not_set", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_no_pixel_data_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_required_elem", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unknown_pixel_representation_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unsupported_syntaxes_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_bad_length_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_padding_warns", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_change_photometric_interpretation", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only_bit_packed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_ybr422_excess_padding", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_ybr422_wrong_interpretation", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_float_pixel_data", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_double_float_pixel_data", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[-output0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00-output1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01-output2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x02-output3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x04-output4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x08-output5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x10-output6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[@-output8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80-output9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xaa-output10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xf0-output11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x0f-output12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff-output13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x00-output14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x01-output15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x80-output16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\xff-output17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01\\x80-output18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80\\x80-output19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff\\x80-output20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00-input1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x02-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x08-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x10-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80-input9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xaa-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xf0-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x0f-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x00-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x01-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x80-input16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\xff-input17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01\\x80-input18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80\\x80-input19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff\\x80-input20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_non_binary_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_non_array_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00@-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x10-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x08-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x02-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x01-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x80-input7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x10-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x08-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x04-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x02-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x01-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_functional"], "PASS_TO_PASS": [], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1416", "base_commit": "699c9f0a8e190d463dd828822106250523d38154", "patch": "diff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py\n--- a/pydicom/pixel_data_handlers/util.py\n+++ b/pydicom/pixel_data_handlers/util.py\n@@ -873,7 +873,7 @@ def _expand_segmented_lut(\n lut.extend([y1] * length)\n else:\n step = (y1 - y0) / length\n- vals = np.around(np.arange(y0 + step, y1 + step, step))\n+ vals = np.around(np.linspace(y0 + step, y1, length))\n lut.extend([int(vv) for vv in vals])\n elif opcode == 2:\n # C.7.9.2.3: Indirect segment\n", "test_patch": "diff --git a/pydicom/tests/test_handler_util.py b/pydicom/tests/test_handler_util.py\n--- a/pydicom/tests/test_handler_util.py\n+++ b/pydicom/tests/test_handler_util.py\n@@ -1252,6 +1252,11 @@ def test_linear(self):\n out = _expand_segmented_lut(data, 'H')\n assert [-400, -320, -240, -160, -80, 0] == out\n \n+ # Positive slope, floating point steps\n+ data = (0, 1, 163, 1, 48, 255)\n+ out = _expand_segmented_lut(data, 'H')\n+ assert (1 + 48) == len(out)\n+\n # No slope\n data = (0, 2, 0, 28672, 1, 5, 28672)\n out = _expand_segmented_lut(data, 'H')\n", "problem_statement": "Segmented LUTs are incorrectly expanded\n**Describe the bug**\r\n`pydicom.pixel_data_handlers.util._expand_segmented_lut()` expands segmented LUTs to an incorrect length.\r\n\r\n**Expected behavior**\r\nA correct length LUT to be produced.\r\n\r\n**Steps To Reproduce**\r\nInitialize the following variables.\r\n```\r\nimport numpy as np\r\nlength = 48\r\ny0 = 163\r\ny1 = 255\r\n```\r\n\r\nRun the following two lines from [`pydicom.pixel_data_handlers.util._expand_segmented_lut()`](https://github.com/pydicom/pydicom/blob/699c9f0a8e190d463dd828822106250523d38154/pydicom/pixel_data_handlers/util.py#L875\r\n)\r\n```\r\nstep = (y1 - y0) / length\r\nvals = np.around(np.arange(y0 + step, y1 + step, step))\r\n```\r\n\r\nConfirm that variable `vals` if of incorrect length\r\n```\r\nprint(len(vals) == length)\r\n> False\r\n```\r\n\r\nAlternatively, the code below produces similarly false results\r\n\r\n```\r\nfrom pydicom.pixel_data_handlers.util import _expand_segmented_lut \r\nlut = _expand_segmented_lut(([0, 1, 163, 1, 48, 255]), \"B\")\r\nprint(len(lut) == (1+48))\r\n> False\r\n```\r\n\r\n`np.arange` [explicitly states](https://numpy.org/doc/stable/reference/generated/numpy.arange.html) that it's \"results will often not be consistent\" when using \"non-integer step\", which is a very possible scenario in this function. The following alternative code does function correctly:\r\n\r\n```\r\nvals = np.around(np.linspace(y0 + step, y1, length))\r\n```\r\n\r\n**Your environment**\r\n```bash\r\n$ python -m pydicom.env_info\r\nmodule | version\r\n------ | -------\r\nplatform | Darwin-20.5.0-x86_64-i386-64bit\r\nPython | 3.7.10 (default, Feb 26 2021, 10:16:00) [Clang 10.0.0 ]\r\npydicom | 2.1.2\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.20.3\r\nPIL | 8.2.0\r\n```\n", "hints_text": "PRs welcome!\r\n\r\nMore test data, too", "created_at": "2021-06-18T13:14:02Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_linear"], "PASS_TO_PASS": ["pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_pixel_representation_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_bits_allocated_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unsupported_dtypes", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-1-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-1-False-int8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-0-False-uint16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-1-False-int16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-False-uint32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-1-False-int32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-True-float32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[64-0-True-float64]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_uncompressed_syntaxes", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_nr_frames_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_samples_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_planar_conf_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_current_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_desired_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[RGB-RGB]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_single_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_frame_by_frame", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_no_endian_raises", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_slope_intercept", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lutdata_ow", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_neither_ds_nor_palette_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unknown_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unavailable_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_supplemental_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_lut_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unequal_lut_length_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_no_palette_color", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16_2frame", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_litle", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_big", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_16_allocated_8_entries", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_alpha", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_well_known_palette", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_positive", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_negative", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_discrete", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_08", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_16", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_spring", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_summer", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_fall", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_winter", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_linear_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_indirect_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_unknown_opcode_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint32", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int32", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_rescale", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_modality_lut", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_photometric_interp", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_parameters", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_index", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_rescale_empty", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_int8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_int16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_bad_depth", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint16_array_float", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_lutdata_ow", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_only_windowing", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_only_voi", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_voi_windowing", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_voi_windowing_empty", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_precision", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_not_j2k", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_no_siz", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_short_bytestream", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_none", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_missing", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_existing"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1000", "base_commit": "14acdd4d767ee55e8e84daeb6f80f81ef4748fee", "patch": "diff --git a/pydicom/filereader.py b/pydicom/filereader.py\n--- a/pydicom/filereader.py\n+++ b/pydicom/filereader.py\n@@ -322,7 +322,8 @@ def _is_implicit_vr(fp, implicit_vr_is_assumed, is_little_endian, stop_when):\n \n def read_dataset(fp, is_implicit_VR, is_little_endian, bytelength=None,\n stop_when=None, defer_size=None,\n- parent_encoding=default_encoding, specific_tags=None):\n+ parent_encoding=default_encoding, specific_tags=None,\n+ at_top_level=True):\n \"\"\"Return a :class:`~pydicom.dataset.Dataset` instance containing the next\n dataset in the file.\n \n@@ -348,6 +349,9 @@ def read_dataset(fp, is_implicit_VR, is_little_endian, bytelength=None,\n Character Set* isn't specified.\n specific_tags : list or None\n See :func:`dcmread` for parameter info.\n+ at_top_level: bool\n+ If dataset is top level (not within a sequence).\n+ Used to turn off explicit VR heuristic within sequences\n \n Returns\n -------\n@@ -361,8 +365,9 @@ def read_dataset(fp, is_implicit_VR, is_little_endian, bytelength=None,\n \"\"\"\n raw_data_elements = dict()\n fp_start = fp.tell()\n- is_implicit_VR = _is_implicit_vr(\n- fp, is_implicit_VR, is_little_endian, stop_when)\n+ if at_top_level:\n+ is_implicit_VR = _is_implicit_vr(\n+ fp, is_implicit_VR, is_little_endian, stop_when)\n fp.seek(fp_start)\n de_gen = data_element_generator(fp, is_implicit_VR, is_little_endian,\n stop_when, defer_size, parent_encoding,\n@@ -456,11 +461,13 @@ def read_sequence_item(fp, is_implicit_VR, is_little_endian, encoding,\n fp.tell() - 4 + offset, bytes2hex(bytes_read)))\n if length == 0xFFFFFFFF:\n ds = read_dataset(fp, is_implicit_VR, is_little_endian,\n- bytelength=None, parent_encoding=encoding)\n+ bytelength=None, parent_encoding=encoding,\n+ at_top_level=False)\n ds.is_undefined_length_sequence_item = True\n else:\n ds = read_dataset(fp, is_implicit_VR, is_little_endian, length,\n- parent_encoding=encoding)\n+ parent_encoding=encoding,\n+ at_top_level=False)\n ds.is_undefined_length_sequence_item = False\n logger.debug(\"%08x: Finished sequence item\" % (fp.tell() + offset,))\n ds.seq_item_tell = seq_item_tell\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -22,6 +22,7 @@\n from pydicom.errors import InvalidDicomError\n from pydicom.filebase import DicomBytesIO\n from pydicom.filereader import data_element_generator\n+from pydicom.sequence import Sequence\n from pydicom.tag import Tag, TupleTag\n from pydicom.uid import ImplicitVRLittleEndian\n import pydicom.valuerep\n@@ -729,6 +730,35 @@ def test_explicit_vr_expected_implicit_used_strict(self):\n self.ds_implicit, is_implicit_VR=False, is_little_endian=True\n )\n \n+ def test_seq_item_looks_like_explicit_VR(self):\n+ # For issue 999.\n+\n+ # Set up an implicit VR dataset with a \"normal\" group 8 tag,\n+ # followed by a sequence with an item (dataset) having\n+ # a data element length that looks like a potential valid VR\n+ ds = Dataset()\n+ ds.file_meta = Dataset()\n+ ds.file_meta.MediaStorageSOPClassUID = \"1.1.1\"\n+ ds.file_meta.MediaStorageSOPInstanceUID = \"2.2.2\"\n+ ds.is_implicit_VR = True\n+ ds.is_little_endian = True\n+ ds.SOPClassUID = '9.9.9' # First item group 8 in top-level dataset\n+ seq = Sequence()\n+ seq_ds = Dataset()\n+ seq_ds.BadPixelImage = b\"\\3\" * 0x5244 # length looks like \"DR\"\n+ seq.append(seq_ds)\n+ ds.ReferencedImageSequence = seq\n+\n+ dbio = DicomBytesIO()\n+ ds.save_as(dbio, write_like_original=False)\n+\n+ # Now read the constructed dataset back in\n+ # In original issue, shows warning that has detected what appears\n+ # to be Explicit VR, then throws NotImplemented for the unknown VR\n+ dbio.seek(0)\n+ ds = dcmread(dbio)\n+ ds.remove_private_tags() # forces it to actually parse SQ\n+\n \n class TestUnknownVR(object):\n @pytest.mark.parametrize(\n", "problem_statement": "Heuristic for Explicit VR acting in sequence datasets\n**Describe the bug**\r\nThere is a check to confirm implicit VR by looking for two ascii characters and switching to explicit with a warning (#823). It was thought this was safe because length in first data elements would not be that large. However, in sequence item datasets this may not be true.\r\n\r\nNoted in google group conversation at https://groups.google.com/forum/#!topic/pydicom/VUmvUYmQxc0 (note that the title of that thread is not correct. that was not the problem).\r\n\r\nTest demonstrating it and fix already done - PR to follow shortly.\r\n\n", "hints_text": "", "created_at": "2019-12-21T19:31:51Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestIncorrectVR::test_seq_item_looks_like_explicit_VR"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_empty_numbers_tag", "pydicom/tests/test_filereader.py::TestReader::test_UTF8_filename", "pydicom/tests/test_filereader.py::TestReader::test_RTPlan", "pydicom/tests/test_filereader.py::TestReader::test_RTDose", "pydicom/tests/test_filereader.py::TestReader::test_CT", "pydicom/tests/test_filereader.py::TestReader::test_CT_PixelData", "pydicom/tests/test_filereader.py::TestReader::test_no_force", "pydicom/tests/test_filereader.py::TestReader::test_RTStruct", "pydicom/tests/test_filereader.py::TestReader::test_dir", "pydicom/tests/test_filereader.py::TestReader::test_MR", "pydicom/tests/test_filereader.py::TestReader::test_deflate", "pydicom/tests/test_filereader.py::TestReader::test_no_pixels_read", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_SQ", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_tag", "pydicom/tests/test_filereader.py::TestReader::test_tag_with_unknown_length_tag_too_short", "pydicom/tests/test_filereader.py::TestReader::test_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_nested_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_no_meta_group_length", "pydicom/tests/test_filereader.py::TestReader::test_no_transfer_syntax_in_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_little_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_big_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_planar_config", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::TestReader::test_long_specific_char_set", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::TestReader::test_group_length_wrong", "pydicom/tests/test_filereader.py::TestReader::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_empty_file", "pydicom/tests/test_filereader.py::TestReader::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used_strict", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_AE", "pydicom/tests/test_filereader.py::TestDeferredRead::test_time_check", "pydicom/tests/test_filereader.py::TestDeferredRead::test_file_exists", "pydicom/tests/test_filereader.py::TestDeferredRead::test_values_identical", "pydicom/tests/test_filereader.py::TestDeferredRead::test_zipped_deferred", "pydicom/tests/test_filereader.py::TestDeferredRead::test_filelike_deferred", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelDataArray", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_object", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_like_object", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1069", "base_commit": "30ac743bcaedbc06f0e0d5cef590cb173756eb2d", "patch": "diff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py\n--- a/pydicom/pixel_data_handlers/util.py\n+++ b/pydicom/pixel_data_handlers/util.py\n@@ -112,6 +112,9 @@ def apply_color_lut(arr, ds=None, palette=None):\n \"Table Module is not currently supported\"\n )\n \n+ if 'RedPaletteColorLookupTableDescriptor' not in ds:\n+ raise ValueError(\"No suitable Palette Color Lookup Table Module found\")\n+\n # All channels are supposed to be identical\n lut_desc = ds.RedPaletteColorLookupTableDescriptor\n # A value of 0 = 2^16 entries\n", "test_patch": "diff --git a/pydicom/tests/test_handler_util.py b/pydicom/tests/test_handler_util.py\n--- a/pydicom/tests/test_handler_util.py\n+++ b/pydicom/tests/test_handler_util.py\n@@ -1150,6 +1150,15 @@ def test_first_map_negative(self):\n assert [60160, 25600, 37376] == list(rgb[arr == 130][0])\n assert ([60160, 25600, 37376] == rgb[arr == 130]).all()\n \n+ def test_unchanged(self):\n+ \"\"\"Test dataset with no LUT is unchanged.\"\"\"\n+ # Regression test for #1068\n+ ds = dcmread(MOD_16, force=True)\n+ assert 'RedPaletteColorLookupTableDescriptor' not in ds\n+ msg = r\"No suitable Palette Color Lookup Table Module found\"\n+ with pytest.raises(ValueError, match=msg):\n+ apply_color_lut(ds.pixel_array, ds)\n+\n \n @pytest.mark.skipif(not HAVE_NP, reason=\"Numpy is not available\")\n class TestNumpy_ExpandSegmentedLUT(object):\n", "problem_statement": "apply_color_lut() incorrect exception when missing RedPaletteColorLUTDescriptor\n**Describe the bug**\r\n`AttributeError` when used on a dataset without `RedPaletteColorLookupTableDescriptor `\r\n\r\n**Expected behavior**\r\nShould raise `ValueError` for consistency with later exceptions\r\n\r\n**Steps To Reproduce**\r\n```python\r\nfrom pydicom.pixel_data_handlers.util import apply_color_lut\r\nds = dcmread(\"CT_small.dcm\")\r\narr = ds.apply_color_lut(arr, ds)\r\n```\r\n```\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \".../pydicom/pixel_data_handlers/util.py\", line 116, in apply_color_lut\r\n lut_desc = ds.RedPaletteColorLookupTableDescriptor\r\n File \".../pydicom/dataset.py\", line 768, in __getattr__\r\n return object.__getattribute__(self, name)\r\nAttributeError: 'FileDataset' object has no attribute 'RedPaletteColorLookupTableDescriptor'\r\n```\n", "hints_text": "", "created_at": "2020-03-14T00:02:52Z", "version": "1.4", "FAIL_TO_PASS": ["pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unchanged"], "PASS_TO_PASS": ["pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_pixel_representation_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_bits_allocated_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unsupported_dtypes", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-1-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-1-False-int8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-0-False-uint16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-1-False-int16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-False-uint32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-1-False-int32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-True-float32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[64-0-True-float64]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_uncompressed_syntaxes", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_nr_frames_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_samples_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_planar_conf_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_current_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_desired_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[RGB-RGB]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_single_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_no_endian_raises", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_slope_intercept", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_neither_ds_nor_palette_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unknown_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unavailable_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_supplemental_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_lut_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unequal_lut_length_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_no_palette_color", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16_2frame", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_litle", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_big", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_16_allocated_8_entries", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_alpha", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_well_known_palette", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_positive", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_negative", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_discrete", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_linear", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_08", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_16", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_spring", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_summer", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_fall", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_winter", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_linear_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_indirect_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_unknown_opcode_raises", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_int8", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_int16", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_voi_bad_depth", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_uint32", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_int8", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_int16", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_int32", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_rescale", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_modality_lut", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_bad_photometric_interp", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_bad_parameters", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_window_bad_index", "pydicom/tests/test_handler_util.py::TestNumpy_VOILUT::test_unchanged"], "environment_setup_commit": "5098c9147fadcb3e5918487036867931435adeb8"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1439", "base_commit": "506ecea8f378dc687d5c504788fc78810a190b7a", "patch": "diff --git a/pydicom/pixel_data_handlers/rle_handler.py b/pydicom/pixel_data_handlers/rle_handler.py\n--- a/pydicom/pixel_data_handlers/rle_handler.py\n+++ b/pydicom/pixel_data_handlers/rle_handler.py\n@@ -38,6 +38,7 @@\n from struct import unpack\n import sys\n from typing import List, TYPE_CHECKING, cast\n+import warnings\n \n try:\n import numpy as np\n@@ -332,13 +333,20 @@ def _rle_decode_frame(\n # ii is 1, 0, 3, 2, 5, 4 for the example above\n # This is where the segment order correction occurs\n segment = _rle_decode_segment(data[offsets[ii]:offsets[ii + 1]])\n- # Check that the number of decoded pixels is correct\n- if len(segment) != rows * columns:\n+\n+ # Check that the number of decoded bytes is correct\n+ actual_length = len(segment)\n+ if actual_length < rows * columns:\n raise ValueError(\n \"The amount of decoded RLE segment data doesn't match the \"\n- f\"expected amount ({len(segment)} vs. \"\n+ f\"expected amount ({actual_length} vs. \"\n f\"{rows * columns} bytes)\"\n )\n+ elif actual_length != rows * columns:\n+ warnings.warn(\n+ \"The decoded RLE segment contains non-conformant padding \"\n+ f\"- {actual_length} vs. {rows * columns} bytes expected\"\n+ )\n \n if segment_order == '>':\n byte_offset = bytes_per_sample - byte_offset - 1\n@@ -346,7 +354,9 @@ def _rle_decode_frame(\n # For 100 pixel/plane, 32-bit, 3 sample data, `start` will be\n # 0, 1, 2, 3, 400, 401, 402, 403, 800, 801, 802, 803\n start = byte_offset + (sample_number * stride)\n- decoded[start:start + stride:bytes_per_sample] = segment\n+ decoded[start:start + stride:bytes_per_sample] = (\n+ segment[:rows * columns]\n+ )\n \n return decoded\n \n", "test_patch": "diff --git a/pydicom/tests/test_rle_pixel_data.py b/pydicom/tests/test_rle_pixel_data.py\n--- a/pydicom/tests/test_rle_pixel_data.py\n+++ b/pydicom/tests/test_rle_pixel_data.py\n@@ -881,11 +881,10 @@ def test_invalid_nr_segments_raises(self, header, samples, bits):\n header, rows=1, columns=1, nr_samples=samples, nr_bits=bits\n )\n \n- def test_invalid_frame_data_raises(self):\n- \"\"\"Test that invalid segment data raises exception.\"\"\"\n+ def test_invalid_segment_data_raises(self):\n+ \"\"\"Test invalid segment data raises exception\"\"\"\n ds = dcmread(RLE_16_1_1F)\n pixel_data = defragment_data(ds.PixelData)\n- # Missing byte\n msg = r\"amount \\(4095 vs. 4096 bytes\\)\"\n with pytest.raises(ValueError, match=msg):\n _rle_decode_frame(\n@@ -896,13 +895,19 @@ def test_invalid_frame_data_raises(self):\n ds.BitsAllocated\n )\n \n- # Extra byte\n- msg = r'amount \\(4097 vs. 4096 bytes\\)'\n- with pytest.raises(ValueError, match=msg):\n- _rle_decode_frame(\n+ def test_nonconf_segment_padding_warns(self):\n+ \"\"\"Test non-conformant segment padding warns\"\"\"\n+ ds = dcmread(RLE_16_1_1F)\n+ pixel_data = defragment_data(ds.PixelData)\n+ msg = (\n+ r\"The decoded RLE segment contains non-conformant padding - 4097 \"\n+ r\"vs. 4096 bytes expected\"\n+ )\n+ with pytest.warns(UserWarning, match=msg):\n+ frame = _rle_decode_frame(\n pixel_data + b'\\x00\\x01',\n- ds.Rows,\n- ds.Columns,\n+ 4096,\n+ 1,\n ds.SamplesPerPixel,\n ds.BitsAllocated\n )\n", "problem_statement": "Exception decompressing RLE encoded data with non-conformant padding\nGetting Following error \r\n\"Could not convert: The amount of decoded RLE segment data doesn't match the expected amount (786433 vs. 786432 bytes)\"\r\nFor following code\r\nplt.imsave(os.path.join(output_folder,file)+'.png', convert_color_space(ds.pixel_array, ds[0x28,0x04].value, 'RGB'))\r\nAlso attaching DICOM file \r\n[US.1.2.156.112536.1.2127.130145051254127131.13912524190.144.txt](https://github.com/pydicom/pydicom/files/6799721/US.1.2.156.112536.1.2127.130145051254127131.13912524190.144.txt)\r\n\r\nPlease remove .txt extension to use DICOM file\r\n\r\n\r\n\n", "hints_text": "It looks like the RLE segment has been padded out to 786433 bytes even though:\r\n\r\n> Each RLE segment must be an even number of bytes or padded at its end with zero to make it even.\r\n\r\nThe solution would be to only raise an exception if the segment is shorter than expected and trim excess padding.\r\n\r\nThere's no simple workaround, but you should be able to do:\r\n```python\r\nfrom pydicom import dcmread\r\nfrom pydicom.pixel_data_handlers import rle_handler\r\nfrom pydicom.pixel_data_handlers.rle_handler import _parse_rle_header, _rle_decode_segment\r\n\r\ndef frame_decoder(data, rows, columns, nr_samples, nr_bits, segment_order = '>'):\r\n if nr_bits % 8:\r\n raise NotImplementedError(\r\n \"Unable to decode RLE encoded pixel data with a (0028,0100) \"\r\n f\"'Bits Allocated' value of {nr_bits}\"\r\n )\r\n\r\n offsets = _parse_rle_header(data[:64])\r\n nr_segments = len(offsets)\r\n\r\n bytes_per_sample = nr_bits // 8\r\n if nr_segments != nr_samples * bytes_per_sample:\r\n raise ValueError(\r\n \"The number of RLE segments in the pixel data doesn't match the \"\r\n f\"expected amount ({nr_segments} vs. \"\r\n f\"{nr_samples * bytes_per_sample} segments)\"\r\n )\r\n\r\n offsets.append(len(data))\r\n\r\n decoded = bytearray(rows * columns * nr_samples * bytes_per_sample)\r\n\r\n stride = bytes_per_sample * rows * columns\r\n for sample_number in range(nr_samples):\r\n le_gen = range(bytes_per_sample)\r\n byte_offsets = le_gen if segment_order == '<' else reversed(le_gen)\r\n for byte_offset in byte_offsets:\r\n ii = sample_number * bytes_per_sample + byte_offset\r\n segment = _rle_decode_segment(data[offsets[ii]:offsets[ii + 1]])\r\n if len(segment) < rows * columns:\r\n raise ValueError(\r\n \"The amount of decoded RLE segment data doesn't match the \"\r\n f\"expected amount ({len(segment)} vs. \"\r\n f\"{rows * columns} bytes)\"\r\n )\r\n\r\n if segment_order == '>':\r\n byte_offset = bytes_per_sample - byte_offset - 1\r\n\r\n start = byte_offset + (sample_number * stride)\r\n decoded[start:start + stride:bytes_per_sample] = segment[:rows * columns]\r\n\r\n return decoded\r\n\r\nrle_handler._rle_decode_frame = frame_decoder\r\n\r\nds = dcmread('path/to/file.dcm')\r\nds.decompress('rle')\r\narr = ds.pixel_array\r\n```\r\n", "created_at": "2021-07-13T00:43:22Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_nonconf_segment_padding_warns"], "PASS_TO_PASS": ["pydicom/tests/test_rle_pixel_data.py::test_unsupported_syntaxes", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_environment", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_supported_dataset", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/rtdose_1frame.dcm-data0]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/SC_rgb.dcm-data1]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/image_dfl.dcm-data2]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_2frame.dcm-data3]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data4]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/JPEG-lossy.dcm-data5]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data6]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data7]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/emri_small_jpeg_2k_lossless.dcm-data8]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/JPEG2000.dcm-data9]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_NoRLEHandler::test_pixel_array_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_environment", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_unsupported_syntax_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/rtdose_1frame.dcm-data0]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/SC_rgb.dcm-data1]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/image_dfl.dcm-data2]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_2frame.dcm-data3]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data4]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/JPEG-lossy.dcm-data5]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data6]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data7]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/emri_small_jpeg_2k_lossless.dcm-data8]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.1/pydicom/data/test_files/JPEG2000.dcm-data9]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_signed", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_1bit_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_8bit_1sample_1f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_decompress_with_handler", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_8bit_1sample_2f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_8bit_3sample_1f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_8bit_3sample_2f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_16bit_1sample_1f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_16bit_1sample_10f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_16bit_3sample_1f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_16bit_3sample_2f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_32bit_1sample_1f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_32bit_1sample_15f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_32bit_3sample_1f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEHandler::test_pixel_array_32bit_3sample_2f", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_GetPixelData::test_no_pixel_data_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_GetPixelData::test_unknown_pixel_representation_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_GetPixelData::test_unsupported_syntaxes_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_GetPixelData::test_change_photometric_interpretation", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_GetPixelData::test_little_endian_segment_order", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_invalid_header_length", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_invalid_nr_segments_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_parse_header[0-offsets0]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_parse_header[1-offsets1]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_parse_header[2-offsets2]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_parse_header[8-offsets3]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_parse_header[14-offsets4]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEParseHeader::test_parse_header[15-offsets5]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_unsupported_bits_allocated_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x00\\x00\\x00\\x00-1-8]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x02\\x00\\x00\\x00-1-8]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x02\\x00\\x00\\x00-3-8]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x04\\x00\\x00\\x00-3-8]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x01\\x00\\x00\\x00-1-16]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x03\\x00\\x00\\x00-1-16]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x05\\x00\\x00\\x00-3-16]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x07\\x00\\x00\\x00-3-16]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x03\\x00\\x00\\x00-1-32]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x05\\x00\\x00\\x00-1-32]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x0b\\x00\\x00\\x00-3-32]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\r\\x00\\x00\\x00-3-32]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\x07\\x00\\x00\\x00-1-64]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_nr_segments_raises[\\t\\x00\\x00\\x00-1-64]", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_invalid_segment_data_raises", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_8bit_1sample", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_8bit_3sample", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_16bit_1sample", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_16bit_3sample", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_32bit_1sample", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeFrame::test_32bit_3sample", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeSegment::test_noop", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeSegment::test_literal", "pydicom/tests/test_rle_pixel_data.py::TestNumpy_RLEDecodeSegment::test_copy"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-900", "base_commit": "3746878d8edf1cbda6fbcf35eec69f9ba79301ca", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -165,6 +165,17 @@ def __init__(self,\n if not isinstance(tag, BaseTag):\n tag = Tag(tag)\n self.tag = tag\n+\n+ # a known tag shall only have the VR 'UN' if it has a length that\n+ # exceeds the size that can be encoded in 16 bit - all other cases\n+ # can be seen as an encoding error and can be corrected\n+ if VR == 'UN' and (is_undefined_length or value is None or\n+ len(value) < 0xffff):\n+ try:\n+ VR = dictionary_VR(tag)\n+ except KeyError:\n+ pass\n+\n self.VR = VR # Note!: you must set VR before setting value\n if already_converted:\n self._value = value\n", "test_patch": "diff --git a/pydicom/tests/test_dataelem.py b/pydicom/tests/test_dataelem.py\n--- a/pydicom/tests/test_dataelem.py\n+++ b/pydicom/tests/test_dataelem.py\n@@ -1,3 +1,4 @@\n+# -*- coding: utf-8 -*-\n # Copyright 2008-2018 pydicom authors. See LICENSE file for details.\n \"\"\"Unit tests for the pydicom.dataelem module.\"\"\"\n \n@@ -351,6 +352,51 @@ def test_private_repeater_tag(self):\n assert '[Overlay ID]' == private_data_elem.name\n assert 'UN' == private_data_elem.VR\n \n+ def test_known_tags_with_UN_VR(self):\n+ \"\"\"Known tags with VR UN are correctly decoded.\"\"\"\n+ ds = Dataset()\n+ ds[0x00080005] = DataElement(0x00080005, 'UN', b'ISO_IR 126')\n+ ds[0x00100010] = DataElement(0x00100010, 'UN',\n+ u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2'.encode('iso_ir_126'))\n+ ds.decode()\n+ assert 'CS' == ds[0x00080005].VR\n+ assert 'PN' == ds[0x00100010].VR\n+ assert u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2' == ds[0x00100010].value\n+\n+ ds = Dataset()\n+ ds[0x00080005] = DataElement(0x00080005, 'UN',\n+ b'ISO 2022 IR 100\\\\ISO 2022 IR 126')\n+ ds[0x00100010] = DataElement(0x00100010, 'UN',\n+ b'Dionysios=\\x1b\\x2d\\x46'\n+ + u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2'.encode('iso_ir_126'))\n+ ds.decode()\n+ assert 'CS' == ds[0x00080005].VR\n+ assert 'PN' == ds[0x00100010].VR\n+ assert u'Dionysios=\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2' == ds[0x00100010].value\n+\n+ def test_unknown_tags_with_UN_VR(self):\n+ \"\"\"Unknown tags with VR UN are not decoded.\"\"\"\n+ ds = Dataset()\n+ ds[0x00080005] = DataElement(0x00080005, 'CS', b'ISO_IR 126')\n+ ds[0x00111010] = DataElement(0x00111010, 'UN',\n+ u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2'.encode('iso_ir_126'))\n+ ds.decode()\n+ assert 'UN' == ds[0x00111010].VR\n+ assert u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2'.encode('iso_ir_126') == ds[0x00111010].value\n+\n+ def test_tag_with_long_value_UN_VR(self):\n+ \"\"\"Tag with length > 64kb with VR UN is not changed.\"\"\"\n+ ds = Dataset()\n+ ds[0x00080005] = DataElement(0x00080005, 'CS', b'ISO_IR 126')\n+\n+ single_value = b'123456.789012345'\n+ large_value = b'\\\\'.join([single_value] * 4500)\n+ ds[0x30040058] = DataElement(0x30040058, 'UN',\n+ large_value,\n+ is_undefined_length=False)\n+ ds.decode()\n+ assert 'UN' == ds[0x30040058].VR\n+\n def test_empty_text_values(self):\n \"\"\"Test that assigning an empty value behaves as expected.\"\"\"\n def check_empty_text_element(value):\n", "problem_statement": "can open my dicom, error in re.match('^ISO[^_]IR', encoding)\n```\r\n(test) root@DESKTOP-COPUCVT:/mnt/e/test# python3 mydicom.py\r\nTraceback (most recent call last):\r\n File \"/root/.local/share/virtualenvs/test-LINKoilU/lib/python3.6/site-packages/pydicom/charset.py\", line 625, in convert_encodings\r\n py_encodings.append(python_encoding[encoding])\r\nKeyError: 73\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"mydicom.py\", line 12, in <module>\r\n pydicom.dcmread(\"DX.X.1.2.276.0.7230010.3.1.4.313262848.25.1563878256.444385.dcm\")\r\n File \"/root/.local/share/virtualenvs/test-LINKoilU/lib/python3.6/site-packages/pydicom/filereader.py\", line 850, in dcmread\r\n force=force, specific_tags=specific_tags)\r\n File \"/root/.local/share/virtualenvs/test-LINKoilU/lib/python3.6/site-packages/pydicom/filereader.py\", line 728, in read_partial\r\n specific_tags=specific_tags)\r\n File \"/root/.local/share/virtualenvs/test-LINKoilU/lib/python3.6/site-packages/pydicom/filereader.py\", line 382, in read_dataset\r\n encoding = convert_encodings(char_set)\r\n File \"/root/.local/share/virtualenvs/test-LINKoilU/lib/python3.6/site-packages/pydicom/charset.py\", line 628, in convert_encodings\r\n _python_encoding_for_corrected_encoding(encoding))\r\n File \"/root/.local/share/virtualenvs/test-LINKoilU/lib/python3.6/site-packages/pydicom/charset.py\", line 647, in _python_encoding_for_corrected_encoding\r\n if re.match('^ISO[^_]IR', encoding) is not None:\r\n File \"/root/.local/share/virtualenvs/test-LINKoilU/lib/python3.6/re.py\", line 172, in match\r\n return _compile(pattern, flags).match(string)\r\nTypeError: expected string or bytes-like object\r\n```\r\n\r\n#### Description\r\n I dont know why pydicom cant open my pictures, but other python library can read the picture and read some meta data correctly. I suspect \" if re.match('^ISO[^_]IR', encoding) is not None:\" the encoding here is not string for my dicom picture. I am new to pydicom, \r\nHas anyone encountered a similar problem? how to solve it? need help,thanks!\r\n\r\nhere is some dicom tags:\r\n\r\n\r\n\r\n\r\n\r\n\r\n#### Steps/Code to Reproduce\r\n```py\r\n\r\nimport pydicom\r\nimport os\r\nimport numpy\r\nchild_path = \"DX.X.1.2.276.0.7230010.3.1.4.313262848.25.1563878256.444385.dcm\"\r\npydicom.dcmread(\"DX.X.1.2.276.0.7230010.3.1.4.313262848.25.1563878256.444385.dcm\"\uff09\r\n\r\n```\r\n\r\n#### Expected Results\r\nExample: read the file without error\r\n\r\n#### Actual Results\r\ncant read the file\r\n\r\n#### Versions\r\nv1.3.0\r\n\r\npython v3.6\r\n\r\n<!-- Thanks for contributing! -->\r\n\n", "hints_text": "The traceback is not really conclusive - apparently there is a syntax error somewhere in `mydicom.py`.\r\nCan you show the contents that code please? The traceback seems not to match the lines you gave below. \r\n\r\nIn the DICOM file I cannot see anything out of the order, apart from ProtocolName being in the wrong encoding (the encoding is latin1, the ProtocolName in some other, possibly Chinese encoding).\nThe most recent traceback is the one that's important I think. Can you compress the anonymised DICOM file as a zip and attach it as well?", "created_at": "2019-07-26T20:06:47Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_dataelem.py::TestDataElement::test_known_tags_with_UN_VR"], "PASS_TO_PASS": ["pydicom/tests/test_dataelem.py::TestDataElement::test_VM_1", "pydicom/tests/test_dataelem.py::TestDataElement::test_VM_2", "pydicom/tests/test_dataelem.py::TestDataElement::test_DSFloat_conversion", "pydicom/tests/test_dataelem.py::TestDataElement::test_backslash", "pydicom/tests/test_dataelem.py::TestDataElement::test_UID", "pydicom/tests/test_dataelem.py::TestDataElement::test_keyword", "pydicom/tests/test_dataelem.py::TestDataElement::test_retired", "pydicom/tests/test_dataelem.py::TestDataElement::test_description_group_length", "pydicom/tests/test_dataelem.py::TestDataElement::test_description_unknown_private", "pydicom/tests/test_dataelem.py::TestDataElement::test_description_unknown", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_standard_element", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_private_element", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_sequence_element", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_not_rlement", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_inheritance", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_class_members", "pydicom/tests/test_dataelem.py::TestDataElement::test_inequality_standard", "pydicom/tests/test_dataelem.py::TestDataElement::test_inequality_sequence", "pydicom/tests/test_dataelem.py::TestDataElement::test_hash", "pydicom/tests/test_dataelem.py::TestDataElement::test_repeater_str", "pydicom/tests/test_dataelem.py::TestDataElement::test_str_no_vr", "pydicom/tests/test_dataelem.py::TestDataElement::test_repr_seq", "pydicom/tests/test_dataelem.py::TestDataElement::test_getitem_raises", "pydicom/tests/test_dataelem.py::TestDataElement::test_repval_large_elem", "pydicom/tests/test_dataelem.py::TestDataElement::test_repval_large_vm", "pydicom/tests/test_dataelem.py::TestDataElement::test_repval_strange_type", "pydicom/tests/test_dataelem.py::TestDataElement::test_private_tag_in_repeater_range", "pydicom/tests/test_dataelem.py::TestDataElement::test_private_repeater_tag", "pydicom/tests/test_dataelem.py::TestDataElement::test_unknown_tags_with_UN_VR", "pydicom/tests/test_dataelem.py::TestDataElement::test_tag_with_long_value_UN_VR", "pydicom/tests/test_dataelem.py::TestDataElement::test_empty_text_values", "pydicom/tests/test_dataelem.py::TestDataElement::test_empty_binary_values", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_key_error", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_valid_tag", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_data_element_without_encoding", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_unknown_vr"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-897", "base_commit": "b682e1dc71eda183786ad724da25f2fb30b5a621", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -378,7 +378,7 @@ def _convert(self, val):\n elif self.VR == 'TM' and config.datetime_conversion:\n return pydicom.valuerep.TM(val)\n elif self.VR == \"UI\":\n- return UID(val)\n+ return UID(val if val else '')\n elif not in_py2 and self.VR == \"PN\":\n return PersonName(val)\n # Later may need this for PersonName as for UI,\ndiff --git a/pydicom/multival.py b/pydicom/multival.py\n--- a/pydicom/multival.py\n+++ b/pydicom/multival.py\n@@ -2,6 +2,7 @@\n \"\"\"Code for multi-value data elements values,\n or any list of items that must all be the same type.\n \"\"\"\n+from pydicom import compat\n \n try:\n from collections.abc import MutableSequence\n@@ -30,7 +31,7 @@ def __init__(self, type_constructor, iterable):\n :param type_constructor: a constructor for the required\n type for all list items. Could be the\n class, or a factory function. For DICOM\n- mult-value data elements, this will be the\n+ multi-value data elements, this will be the\n class or type corresponding to the VR.\n :param iterable: an iterable (e.g. list, tuple) of items\n to initialize the MultiValue list\n@@ -59,8 +60,11 @@ def __setitem__(self, i, val):\n self._list.__setitem__(i, self.type_constructor(val))\n \n def __str__(self):\n- lines = [str(x) for x in self]\n- return \"['\" + \"', '\".join(lines) + \"']\"\n+ if not self:\n+ return ''\n+ lines = [\"'{}'\".format(x) if isinstance(x, compat.char_types)\n+ else str(x) for x in self]\n+ return \"[\" + \", \".join(lines) + \"]\"\n \n __repr__ = __str__\n \ndiff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -603,8 +603,6 @@ def _encode_personname(components, encodings):\n \n class PersonName3(object):\n def __init__(self, val, encodings=None, original_string=None):\n- # handle None `val` as empty string\n- val = val or ''\n if isinstance(val, PersonName3):\n encodings = val.encodings\n self.original_string = val.original_string\n@@ -614,6 +612,9 @@ def __init__(self, val, encodings=None, original_string=None):\n self.original_string = val\n self._components = None\n else:\n+ # handle None `val` as empty string\n+ val = val or ''\n+\n # this is the decoded string - save the original string if\n # available for easier writing back\n self.original_string = original_string\n@@ -774,6 +775,12 @@ def formatted(self, format_str):\n self._create_dict()\n return format_str % self._dict\n \n+ def __bool__(self):\n+ if self.original_string is None:\n+ return (self._components is not None and\n+ (len(self._components) > 1 or bool(self._components[0])))\n+ return bool(self.original_string)\n+\n \n class PersonNameBase(object):\n \"\"\"Base class for Person Name classes\"\"\"\n", "test_patch": "diff --git a/pydicom/tests/test_dataelem.py b/pydicom/tests/test_dataelem.py\n--- a/pydicom/tests/test_dataelem.py\n+++ b/pydicom/tests/test_dataelem.py\n@@ -15,6 +15,7 @@\n DataElement_from_raw,\n )\n from pydicom.dataset import Dataset\n+from pydicom.multival import MultiValue\n from pydicom.tag import Tag\n from pydicom.uid import UID\n from pydicom.valuerep import DSfloat\n@@ -368,6 +369,92 @@ def test_private_repeater_tag(self):\n assert '[Overlay ID]' == private_data_elem.name\n assert 'UN' == private_data_elem.VR\n \n+ def test_empty_text_values(self):\n+ \"\"\"Test that assigning an empty value behaves as expected.\"\"\"\n+ def check_empty_text_element(value):\n+ setattr(ds, tag_name, value)\n+ elem = ds[tag_name]\n+ assert bool(elem.value) is False\n+\n+ text_vrs = {\n+ 'AE': 'Receiver',\n+ 'AS': 'PatientAge',\n+ 'AT': 'OffendingElement',\n+ 'CS': 'QualityControlSubject',\n+ 'DA': 'PatientBirthDate',\n+ 'DS': 'PatientWeight',\n+ 'DT': 'AcquisitionDateTime',\n+ 'IS': 'BeamNumber',\n+ 'LO': 'DataSetSubtype',\n+ 'LT': 'ExtendedCodeMeaning',\n+ 'PN': 'PatientName',\n+ 'SH': 'CodeValue',\n+ 'ST': 'InstitutionAddress',\n+ 'TM': 'StudyTime',\n+ 'UC': 'LongCodeValue',\n+ 'UI': 'SOPClassUID',\n+ 'UR': 'CodingSchemeURL',\n+ 'UT': 'StrainAdditionalInformation',\n+ }\n+ ds = Dataset()\n+ # set value to new element\n+ for tag_name in text_vrs.values():\n+ check_empty_text_element(None)\n+ del ds[tag_name]\n+ check_empty_text_element(b'')\n+ del ds[tag_name]\n+ check_empty_text_element(u'')\n+ del ds[tag_name]\n+ check_empty_text_element([])\n+ del ds[tag_name]\n+\n+ # set value to existing element\n+ for tag_name in text_vrs.values():\n+ check_empty_text_element(None)\n+ check_empty_text_element(b'')\n+ check_empty_text_element(u'')\n+ check_empty_text_element([])\n+ check_empty_text_element(None)\n+\n+ def test_empty_binary_values(self):\n+ \"\"\"Test that assigning an empty value behaves as expected for\n+ non-text VRs.\"\"\"\n+ def check_empty_binary_element(value):\n+ setattr(ds, tag_name, value)\n+ elem = ds[tag_name]\n+ assert bool(elem.value) is False\n+\n+ non_text_vrs = {\n+ 'SL': 'RationalNumeratorValue',\n+ 'SS': 'SelectorSSValue',\n+ 'UL': 'SimpleFrameList',\n+ 'US': 'SourceAcquisitionBeamNumber',\n+ 'FD': 'RealWorldValueLUTData',\n+ 'FL': 'VectorAccuracy',\n+ 'OB': 'FillPattern',\n+ 'OD': 'DoubleFloatPixelData',\n+ 'OF': 'UValueData',\n+ 'OL': 'TrackPointIndexList',\n+ 'OW': 'TrianglePointIndexList',\n+ 'UN': 'SelectorUNValue',\n+ }\n+ ds = Dataset()\n+ # set value to new element\n+ for tag_name in non_text_vrs.values():\n+ check_empty_binary_element(None)\n+ del ds[tag_name]\n+ check_empty_binary_element([])\n+ del ds[tag_name]\n+ check_empty_binary_element(MultiValue(int, []))\n+ del ds[tag_name]\n+\n+ # set value to existing element\n+ for tag_name in non_text_vrs.values():\n+ check_empty_binary_element(None)\n+ check_empty_binary_element([])\n+ check_empty_binary_element(MultiValue(int, []))\n+ check_empty_binary_element(None)\n+\n \n class RawDataElementTests(unittest.TestCase):\n def testKeyError(self):\ndiff --git a/pydicom/tests/test_multival.py b/pydicom/tests/test_multival.py\n--- a/pydicom/tests/test_multival.py\n+++ b/pydicom/tests/test_multival.py\n@@ -1,43 +1,46 @@\n # Copyright 2008-2018 pydicom authors. See LICENSE file for details.\n \"\"\"Test suite for MultiValue class\"\"\"\n \n-import unittest\n+import pytest\n+\n from pydicom.multival import MultiValue\n from pydicom.valuerep import DS, DSfloat, DSdecimal, IS\n-from pydicom import config\n+from pydicom import config, compat\n from copy import deepcopy\n \n import sys\n+\n python_version = sys.version_info\n \n \n-class MultiValuetests(unittest.TestCase):\n+class TestMultiValue(object):\n def testMultiDS(self):\n \"\"\"MultiValue: Multi-valued data elements can be created........\"\"\"\n multival = MultiValue(DS, ['11.1', '22.2', '33.3'])\n for val in multival:\n- self.assertTrue(isinstance(val, (DSfloat, DSdecimal)),\n- \"Multi-value DS item not converted to DS\")\n+ assert isinstance(val, (DSfloat, DSdecimal))\n \n def testEmptyElements(self):\n \"\"\"MultiValue: Empty number string elements are not converted...\"\"\"\n multival = MultiValue(DSfloat, ['1.0', ''])\n- self.assertEqual(1.0, multival[0])\n- self.assertEqual('', multival[1])\n+ assert 1.0 == multival[0]\n+ assert '' == multival[1]\n multival = MultiValue(IS, ['1', ''])\n- self.assertEqual(1, multival[0])\n- self.assertEqual('', multival[1])\n+ assert 1 == multival[0]\n+ assert '' == multival[1]\n multival = MultiValue(DSdecimal, ['1', ''])\n- self.assertEqual(1, multival[0])\n- self.assertEqual('', multival[1])\n+ assert 1 == multival[0]\n+ assert '' == multival[1]\n+ multival = MultiValue(IS, [])\n+ assert not multival\n+ assert 0 == len(multival)\n \n def testLimits(self):\n \"\"\"MultiValue: Raise error if any item outside DICOM limits....\"\"\"\n original_flag = config.enforce_valid_values\n config.enforce_valid_values = True\n- self.assertRaises(OverflowError,\n- MultiValue,\n- IS, [1, -2 ** 31 - 1])\n+ with pytest.raises(OverflowError):\n+ MultiValue(IS, [1, -2 ** 31 - 1])\n # Overflow error not raised for IS out of DICOM valid range\n config.enforce_valid_values = original_flag\n \n@@ -45,44 +48,39 @@ def testAppend(self):\n \"\"\"MultiValue: Append of item converts it to required type...\"\"\"\n multival = MultiValue(IS, [1, 5, 10])\n multival.append('5')\n- self.assertTrue(isinstance(multival[-1], IS))\n- self.assertEqual(multival[-1], 5,\n- \"Item set by append is not correct value\")\n+ assert isinstance(multival[-1], IS)\n+ assert multival[-1] == 5\n \n def testSetIndex(self):\n \"\"\"MultiValue: Setting list item converts it to required type\"\"\"\n multival = MultiValue(IS, [1, 5, 10])\n multival[1] = '7'\n- self.assertTrue(isinstance(multival[1], IS))\n- self.assertEqual(multival[1], 7,\n- \"Item set by index is not correct value\")\n+ assert isinstance(multival[1], IS)\n+ assert multival[1] == 7\n \n def testDeleteIndex(self):\n \"\"\"MultiValue: Deleting item at index behaves as expected...\"\"\"\n multival = MultiValue(IS, [1, 5, 10])\n del multival[1]\n- self.assertEqual(2, len(multival))\n- self.assertEqual(multival[0], 1)\n- self.assertEqual(multival[1], 10)\n+ assert 2 == len(multival)\n+ assert multival[0] == 1\n+ assert multival[1] == 10\n \n def testExtend(self):\n \"\"\"MultiValue: Extending a list converts all to required type\"\"\"\n multival = MultiValue(IS, [1, 5, 10])\n multival.extend(['7', 42])\n- self.assertTrue(isinstance(multival[-2], IS))\n- self.assertTrue(isinstance(multival[-1], IS))\n- self.assertEqual(multival[-2], 7,\n- \"Item set by extend not correct value\")\n+ assert isinstance(multival[-2], IS)\n+ assert isinstance(multival[-1], IS)\n+ assert multival[-2], 7\n \n def testSlice(self):\n \"\"\"MultiValue: Setting slice converts items to required type.\"\"\"\n multival = MultiValue(IS, range(7))\n multival[2:7:2] = [4, 16, 36]\n for val in multival:\n- self.assertTrue(isinstance(val, IS),\n- \"Slice IS value not correct type\")\n- self.assertEqual(multival[4], 16,\n- \"Set by slice failed for item 4 of list\")\n+ assert isinstance(val, IS)\n+ assert multival[4] == 16\n \n def testIssue236DeepCopy(self):\n \"\"\"MultiValue: deepcopy of MultiValue does not generate an error\"\"\"\n@@ -97,38 +95,45 @@ def testSorting(self):\n \"\"\"MultiValue: allow inline sort.\"\"\"\n multival = MultiValue(DS, [12, 33, 5, 7, 1])\n multival.sort()\n- self.assertEqual([1, 5, 7, 12, 33], multival)\n+ assert [1, 5, 7, 12, 33] == multival\n multival.sort(reverse=True)\n- self.assertEqual([33, 12, 7, 5, 1], multival)\n+ assert [33, 12, 7, 5, 1] == multival\n multival.sort(key=str)\n- self.assertEqual([1, 12, 33, 5, 7], multival)\n+ assert [1, 12, 33, 5, 7] == multival\n \n def test_equal(self):\n \"\"\"MultiValue: test equality operator\"\"\"\n multival = MultiValue(DS, [12, 33, 5, 7, 1])\n multival2 = MultiValue(DS, [12, 33, 5, 7, 1])\n multival3 = MultiValue(DS, [33, 12, 5, 7, 1])\n- self.assertTrue(multival == multival2)\n- self.assertFalse(multival == multival3)\n+ assert multival == multival2\n+ assert not (multival == multival3)\n multival = MultiValue(str, ['a', 'b', 'c'])\n multival2 = MultiValue(str, ['a', 'b', 'c'])\n multival3 = MultiValue(str, ['b', 'c', 'a'])\n- self.assertTrue(multival == multival2)\n- self.assertFalse(multival == multival3)\n+ assert multival == multival2\n+ assert not (multival == multival3)\n \n def test_not_equal(self):\n \"\"\"MultiValue: test equality operator\"\"\"\n multival = MultiValue(DS, [12, 33, 5, 7, 1])\n multival2 = MultiValue(DS, [12, 33, 5, 7, 1])\n multival3 = MultiValue(DS, [33, 12, 5, 7, 1])\n- self.assertFalse(multival != multival2)\n- self.assertTrue(multival != multival3)\n+ assert not multival != multival2\n+ assert multival != multival3\n multival = MultiValue(str, ['a', 'b', 'c'])\n multival2 = MultiValue(str, ['a', 'b', 'c'])\n multival3 = MultiValue(str, ['b', 'c', 'a'])\n- self.assertFalse(multival != multival2)\n- self.assertTrue(multival != multival3)\n-\n-\n-if __name__ == \"__main__\":\n- unittest.main()\n+ assert not (multival != multival2)\n+ assert multival != multival3\n+\n+ def test_str_rep(self):\n+ \"\"\"MultiValue: test print output\"\"\"\n+ multival = MultiValue(IS, [])\n+ assert '' == str(multival)\n+ multival = MultiValue(compat.text_type, [1, 2, 3])\n+ assert \"['1', '2', '3']\" == str(multival)\n+ multival = MultiValue(int, [1, 2, 3])\n+ assert '[1, 2, 3]' == str(multival)\n+ multival = MultiValue(float, [1.1, 2.2, 3.3])\n+ assert '[1.1, 2.2, 3.3]' == str(multival)\n", "problem_statement": "Inconsistencies in value testing for PersonName3\n```python\r\nfrom pydicom.dataset import Dataset\r\n\r\nds = Dataset()\r\nds.PatientName = None # or ''\r\nif ds.PatientName:\r\n print('Has a value')\r\nelse:\r\n print('Has no value')\r\n\r\nif None: # or ''\r\n print('Evaluates as True')\r\nelse:\r\n print('Evaluates as False')\r\n```\r\nPrints `Has a value` then `Evaluates as False`. Should print `Has no value` instead (encoded dataset will have a zero-length element).\r\n\r\nCurrent master, python 3.6.\n", "hints_text": "Should that `if None` read `if ds.PatientName is None`?\r\n\r\nI can see the inconsistency if assigning `None` - which results in an empty value instead of `None`. Assigning an empty string works as expected (has an empty string afterwards).\r\nFor other string tags `None` or `''` can be assigned, though I now wonder if this is the correct behavior, as there is no difference between an empty value and no value in DICOM for string VRs. IMHO, the correct behavior should be to assign no value, e.g. the following should be equivalent:\r\n```python\r\nds.PatientName = ''\r\nds.PatientName = None\r\nds.PatientName = []\r\n```\r\nCurrently, the first 2 result in VM=1, the last in VM=0 (which is correct).\r\n@darcymason, @scaramallion - what do you think?\nThe `if None` was just to demonstrate how python behaves and hence how I naively expect an empty pydicom element value to behave.\r\n\r\nI just want a simple consistent \"does this element have a value\" test, which means an element with `None` and `''` should both fail the test. Essentially if the element will end up encoded with zero-length it should fail. It works as I expect for simple text element values, but `PersonName3` and maybe some of the other VR classes might need `__bool__()` or `__len__()`?\r\n\r\n```python\r\n# I'd like this to work cleanly\r\nfor elem in ds:\r\n if elem.value:\r\n print(elem.value)\r\n else:\r\n print('(no value available)')\r\n```\r\n\r\nI've been playing around with printing out pretty datasets for pynetdicom and have run into a some problems with consistency in how element values are evaluated and printed.\r\n\r\nI think you're right, they should be VM = 0. I think the last case gives you a `MultiValue` rather than a `PersonName3` which is probably why.\n```python\r\n#!/usr/bin/env python\r\n\r\nfrom pydicom.dataset import Dataset\r\nfrom pydicom.datadict import tag_for_keyword\r\n\r\nVRs = {\r\n 'AE' : 'Receiver',\r\n 'AS' : 'PatientAge',\r\n 'AT' : 'OffendingElement',\r\n 'CS' : 'QualityControlSubject',\r\n 'DA' : 'PatientBirthDate',\r\n 'DS' : 'PatientWeight',\r\n 'DT' : 'AcquisitionDateTime',\r\n 'IS' : 'BeamNumber',\r\n 'LO' : 'DataSetSubtype',\r\n 'LT' : 'ExtendedCodeMeaning',\r\n 'PN' : 'PatientName',\r\n 'SH' : 'CodeValue',\r\n 'ST' : 'InstitutionAddress',\r\n 'TM' : 'StudyTime',\r\n 'UC' : 'LongCodeValue',\r\n 'UI' : 'SOPClassUID',\r\n 'UR' : 'CodingSchemeURL',\r\n 'UT' : 'StrainAdditionalInformation',\r\n 'SL' : 'RationalNumeratorValue',\r\n 'SS' : 'SelectorSSValue',\r\n 'UL' : 'SimpleFrameList',\r\n 'US' : 'SourceAcquisitionBeamNumber',\r\n 'FD' : 'RealWorldValueLUTData',\r\n 'FL' : 'VectorAccuracy',\r\n 'OB' : 'FillPattern',\r\n 'OD' : 'DoubleFloatPixelData',\r\n 'OF' : 'UValueData',\r\n 'OL' : 'TrackPointIndexList',\r\n 'OW' : 'TrianglePointIndexList',\r\n #'OV' : '',\r\n 'UN' : 'SelectorUNValue',\r\n}\r\n\r\nds = Dataset()\r\nfor vr, kw in VRs.items():\r\n try:\r\n setattr(ds, kw, None)\r\n except:\r\n print('Failed assigning None', vr)\r\n continue\r\n\r\n elem = ds[tag_for_keyword(kw)]\r\n\r\n try:\r\n assert bool(elem.value) is False\r\n except:\r\n print('Failed empty value test', vr)\r\n\r\n try:\r\n assert elem.VM == 0\r\n except Exception as exc:\r\n print('Failed VM == 0', vr, elem.VM)\r\n```\r\nUI fails assignment using `None`, they all fail the VM == 0 test, PN fails the value test in Python 3.6, passes in 2.7.\nPN in Python 2 is derived from `unicode`, so this is to be expected. So you agree that VM shall be 0 after assigning `None` or `''`?\n> So you agree that VM shall be 0 after assigning None or ''?\r\n\r\nAs far as I can see the standard doesn't explicitly say so, but I think that's reasonable. DCMTK's `dcmdump` uses that convention.\r\n\r\nWhat do you think @darcymason?\n> I think you're right, they should be VM = 0. I think the last case gives you a MultiValue rather than a PersonName3 which is probably why.\r\n\r\nSorry, I overlooked that post. Yes, and that may be the easiest way to change this - assign an empty `MultiValue` (aka an empty list) in these cases instead of `None` or `''`.\nThere is also the question of how to represent empty values. Currently we get:\r\n```\r\n>>> ds.CodeValue = None\r\n>>> ds.CodeValue\r\n>>> print(ds.CodeValue)\r\nNone\r\n>>> ds['CodeValue'].VM\r\n1\r\n>>> ds.CodeValue = []\r\n>>> ds.CodeValue\r\n['']\r\n>>> ds['CodeValue'].VM\r\n0\r\n```\r\nwhich is quite inconsistent. `None` for an empty value may make sense, or an empty list (other than a list with an empty string), not sure about this. Any ideas?\nI think as long as `bool(value)` would normally evaluate as `False` then it should be considered empty.\r\n```python\r\nvalue = '' # or None or [] or b'' or whatever\r\nif not value:\r\n print('Empty')\r\n```\r\nFor `MultiValue` it should probably be an OR on `[bool(val) for val in MultiValue]`\n> > So you agree that VM shall be 0 after assigning None or ''?\r\n> \r\n> As far as I can see the standard doesn't explicitly say so, but I think that's reasonable. DCMTK's `dcmdump` uses that convention.\r\n> \r\n> What do you think @darcymason?\r\n\r\nHmmm... just read quickly through, so apologies if I've repeated (or missed) something already said. Haven't looked at any code yet.\r\n\r\nOne thought is that DICOM type 2 data elements allow blank values, which to me is a real valid value, different than a None.\r\n\r\nSecond thought is we've normally handled a non-existent value by just not having the attribute set, i.e. just don't set the attribute, or if it already exists, delete it. You check for existence of values by `if keyword in ds`.\r\n\r\nThird thought (the last in this comment I think) is that when we drop support for earlier python versions and can start typing pydicom, do we cause trouble by encouraging use of None? We have not forbidden setting None, or even incorrect types in many cases, but this is in line with python's duck typing philosophy. It may be that at some point more control over this could be automatically introduced via typing. Yes, we could Union everything with None, but I would foresee a whole lot of `if` statements to handle those cases.\r\n\r\n\nI frequently use `None` for type 2 elements that are required to be present but may or may not have a value. It just seems to me that this is the 'obvious' thing to do when I want an element with no value. Does it make sense that you need to set an integer VR to `''` if you want an empty value?\r\n\r\n`if keyword in ds` tests for the presence of the element in the dataset, not that the element has a value. \nWell, thinking this through some more, I may be coming around to your way of thinking...I suppose blank type 2 can be considered a zero-length (no value) data element. Using a null (python None) value for those does have a certain logic to it, similar to Null in databases and so on. And in that case, VM should be zero, although VM is a weak concept to me anyway, since it exists in dictionaries but not in actual DICOM files, so I'm not too invested in that one way or the other.\nThe other thing is that some elements don't encode properly with a value set to `None`, while others work as I expect.\r\n\r\n```python\r\n>>> from pydicom.dataset import Dataset\r\n>>> from pynetdicom.dsutils import encode # wrapper for filewriter.write_dataset\r\n>>> ds = Dataset()\r\n>>> ds.Receiver = None # VR of AE\r\n>>> type(ds.Receiver)\r\nNoneType\r\n>>> encode(ds, True, True) # Works OK\r\nb'\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00'\r\n>>> ds = Dataset()\r\n>>> ds.BitsStored = None # VR of US\r\n>>> type(ds.BitsStored)\r\nNoneType\r\n>>> encode(ds, True, True) # Fails to encode\r\n>>>\r\n```\nSo I think this has elevated to a larger conversation on \"`None` support\" in pydicom, make it consistent across all types, or raise exceptions if there are any types or situations where it should not be allowed.\r\n\r\nI'll sleep on it for now, pick it up again tomorrow...\r\n\nMy current instinct is to:\r\n- handle assigning `None`, `''` or `[]` to an element with a text VR as assigning an empty string (as they are all equivalent, and an empty string is most convienient for the user, and probably expected), return `False` as truth value, and have a VM of 0 (this is as implemented in the PR) \r\n- handle assigning `None` or `[]` to an element with a binary VR as assigning `None` (I think this better meets the expections for an element without a value), return `False` as truth value, and have a VM of 0 (in the PR I use a `MultiValue` object, which I would change)\r\n- in the case of IS and DS (these are kind of in-between), we have to make sure they handle the empty string case by returning `None` instead of 0 if getting the numerical value (haven't checked the current behavior) \r\n\r\nUsing `None` for text values, apart from not being upwards compatible, is a thing I have been burned with before. I used to write DICOM elements into a database and had used database `null` to represent elements without values. This turned out to be a big mistake, as there is actually no use case where you have to differentiate no value from an empty value for text values (and indeed there is no such distinction in DICOM itself for text VRs), and led to a lot of unnecessary checking for null values in the user code (and exceptions if they have been missing).\nI've started a separate issue for the empty values discussion #896", "created_at": "2019-07-24T18:43:18Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_dataelem.py::DataElementTests::test_empty_text_values", "pydicom/tests/test_multival.py::TestMultiValue::test_str_rep"], "PASS_TO_PASS": ["pydicom/tests/test_dataelem.py::DataElementTests::testBackslash", "pydicom/tests/test_dataelem.py::DataElementTests::testDSFloatConversion", "pydicom/tests/test_dataelem.py::DataElementTests::testEqualityInheritance", "pydicom/tests/test_dataelem.py::DataElementTests::testEqualityNotElement", "pydicom/tests/test_dataelem.py::DataElementTests::testEqualityPrivateElement", "pydicom/tests/test_dataelem.py::DataElementTests::testEqualitySequenceElement", "pydicom/tests/test_dataelem.py::DataElementTests::testEqualityStandardElement", "pydicom/tests/test_dataelem.py::DataElementTests::testHash", "pydicom/tests/test_dataelem.py::DataElementTests::testKeyword", "pydicom/tests/test_dataelem.py::DataElementTests::testRetired", "pydicom/tests/test_dataelem.py::DataElementTests::testUID", "pydicom/tests/test_dataelem.py::DataElementTests::testVM1", "pydicom/tests/test_dataelem.py::DataElementTests::testVM2", "pydicom/tests/test_dataelem.py::DataElementTests::test_description_group_length", "pydicom/tests/test_dataelem.py::DataElementTests::test_description_unknown", "pydicom/tests/test_dataelem.py::DataElementTests::test_description_unknown_private", "pydicom/tests/test_dataelem.py::DataElementTests::test_empty_binary_values", "pydicom/tests/test_dataelem.py::DataElementTests::test_equality_class_members", "pydicom/tests/test_dataelem.py::DataElementTests::test_getitem_raises", "pydicom/tests/test_dataelem.py::DataElementTests::test_inequality_sequence", "pydicom/tests/test_dataelem.py::DataElementTests::test_inequality_standard", "pydicom/tests/test_dataelem.py::DataElementTests::test_private_repeater_tag", "pydicom/tests/test_dataelem.py::DataElementTests::test_private_tag_in_repeater_range", "pydicom/tests/test_dataelem.py::DataElementTests::test_repeater_str", "pydicom/tests/test_dataelem.py::DataElementTests::test_repr_seq", "pydicom/tests/test_dataelem.py::DataElementTests::test_repval_large_elem", "pydicom/tests/test_dataelem.py::DataElementTests::test_repval_large_vm", "pydicom/tests/test_dataelem.py::DataElementTests::test_repval_strange_type", "pydicom/tests/test_dataelem.py::DataElementTests::test_str_no_vr", "pydicom/tests/test_dataelem.py::RawDataElementTests::testKeyError", "pydicom/tests/test_dataelem.py::RawDataElementTests::testTagWithoutEncodingPython3", "pydicom/tests/test_dataelem.py::RawDataElementTests::testValidTag", "pydicom/tests/test_dataelem.py::RawDataElementTests::test_unknown_vr", "pydicom/tests/test_multival.py::TestMultiValue::testMultiDS", "pydicom/tests/test_multival.py::TestMultiValue::testEmptyElements", "pydicom/tests/test_multival.py::TestMultiValue::testLimits", "pydicom/tests/test_multival.py::TestMultiValue::testAppend", "pydicom/tests/test_multival.py::TestMultiValue::testSetIndex", "pydicom/tests/test_multival.py::TestMultiValue::testDeleteIndex", "pydicom/tests/test_multival.py::TestMultiValue::testExtend", "pydicom/tests/test_multival.py::TestMultiValue::testSlice", "pydicom/tests/test_multival.py::TestMultiValue::testIssue236DeepCopy", "pydicom/tests/test_multival.py::TestMultiValue::test_equal", "pydicom/tests/test_multival.py::TestMultiValue::test_not_equal"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-903", "base_commit": "88ca0bff105c75a632d7351acb6895b70230fa12", "patch": "diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -3,7 +3,7 @@\n \n from __future__ import absolute_import\n \n-import struct\n+import warnings\n from struct import pack\n \n from pydicom import compat\n@@ -439,27 +439,19 @@ def write_data_element(fp, data_element, encodings=None):\n # Write element's tag\n fp.write_tag(data_element.tag)\n \n- # If explicit VR, write the VR\n- VR = data_element.VR\n- if not fp.is_implicit_VR:\n- if len(VR) != 2:\n- msg = (\"Cannot write ambiguous VR of '{}' for data element with \"\n- \"tag {}.\\nSet the correct VR before writing, or use an \"\n- \"implicit VR transfer syntax\".format(\n- VR, repr(data_element.tag)))\n- raise ValueError(msg)\n- if not in_py2:\n- fp.write(bytes(VR, default_encoding))\n- else:\n- fp.write(VR)\n- if VR in extra_length_VRs:\n- fp.write_US(0) # reserved 2 bytes\n-\n # write into a buffer to avoid seeking back which can be expansive\n buffer = DicomBytesIO()\n buffer.is_little_endian = fp.is_little_endian\n buffer.is_implicit_VR = fp.is_implicit_VR\n \n+ VR = data_element.VR\n+ if not fp.is_implicit_VR and len(VR) != 2:\n+ msg = (\"Cannot write ambiguous VR of '{}' for data element with \"\n+ \"tag {}.\\nSet the correct VR before writing, or use an \"\n+ \"implicit VR transfer syntax\".format(\n+ VR, repr(data_element.tag)))\n+ raise ValueError(msg)\n+\n if data_element.is_raw:\n # raw data element values can be written as they are\n buffer.write(data_element.value)\n@@ -496,18 +488,29 @@ def write_data_element(fp, data_element, encodings=None):\n 'start with an item tag')\n \n value_length = buffer.tell()\n+ if (not fp.is_implicit_VR and VR not in extra_length_VRs and\n+ not is_undefined_length and value_length > 0xffff):\n+ # see PS 3.5, section 6.2.2 for handling of this case\n+ msg = ('The value for the data element {} exceeds the size '\n+ 'of 64 kByte and cannot be written in an explicit transfer '\n+ 'syntax. The data element VR is changed from \"{}\" to \"UN\" '\n+ 'to allow saving the data.'\n+ .format(data_element.tag, VR))\n+ warnings.warn(msg)\n+ VR = 'UN'\n+\n+ # write the VR for explicit transfer syntax\n+ if not fp.is_implicit_VR:\n+ if not in_py2:\n+ fp.write(bytes(VR, default_encoding))\n+ else:\n+ fp.write(VR)\n+ if VR in extra_length_VRs:\n+ fp.write_US(0) # reserved 2 bytes\n+\n if (not fp.is_implicit_VR and VR not in extra_length_VRs and\n not is_undefined_length):\n- try:\n- fp.write_US(value_length) # Explicit VR length field is 2 bytes\n- except struct.error:\n- msg = ('The value for the data element {} exceeds the size '\n- 'of 64 kByte and cannot be written in an explicit transfer '\n- 'syntax. You can save it using Implicit Little Endian '\n- 'transfer syntax, or you have to truncate the value to not '\n- 'exceed the maximum size of 64 kByte.'\n- .format(data_element.tag))\n- raise ValueError(msg)\n+ fp.write_US(value_length) # Explicit VR length field is 2 bytes\n else:\n # write the proper length of the data_element in the length slot,\n # unless is SQ with undefined length.\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -2513,20 +2513,31 @@ def test_writing_too_big_data_in_explicit_encoding(self):\n large_value,\n is_undefined_length=False)\n write_data_element(self.fp, pixel_data)\n+ self.fp.seek(0)\n+ ds = read_dataset(self.fp, True, True)\n+ assert 'DS' == ds[0x30040058].VR\n \n self.fp = DicomBytesIO()\n self.fp.is_little_endian = True\n self.fp.is_implicit_VR = False\n- # shall raise if trying to write it with explicit transfer syntax,\n- # where the length field is 2 bytes long\n- expected_message = (r'The value for the data element \\(3004, 0058\\) '\n- r'exceeds the size of 64 kByte ')\n- with pytest.raises(ValueError, match=expected_message):\n+\n+ msg = (r'The value for the data element \\(3004, 0058\\) exceeds the '\n+ r'size of 64 kByte and cannot be written in an explicit '\n+ r'transfer syntax. The data element VR is changed from '\n+ r'\"DS\" to \"UN\" to allow saving the data.')\n+\n+ with pytest.warns(UserWarning, match=msg):\n write_data_element(self.fp, pixel_data)\n+ self.fp.seek(0)\n+ ds = read_dataset(self.fp, False, True)\n+ assert 'UN' == ds[0x30040058].VR\n \n+ # we expect the same behavior in Big Endian transfer syntax\n self.fp = DicomBytesIO()\n self.fp.is_little_endian = False\n self.fp.is_implicit_VR = False\n- # we expect the same behavior in Big Endian transfer syntax\n- with pytest.raises(ValueError, match=expected_message):\n+ with pytest.warns(UserWarning, match=msg):\n write_data_element(self.fp, pixel_data)\n+ self.fp.seek(0)\n+ ds = read_dataset(self.fp, False, False)\n+ assert 'UN' == ds[0x30040058].VR\n", "problem_statement": "Handling of DS too long to be encoded in explicit encoding\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\nThis is probably not a bug, but I'm not sure about the wanted behavior.\r\nAn RTPlan dataset encoded as Little Endian Implicit contains multiple values in the DS tag DHV Data (3004,0058) with an overall length not fitting into 2 bytes. Trying to write this as explicit Little Endian fails with an exception (`\"ushort format requires 0 <= number <= (0x7fff * 2 + 1)\"`) which is raised by the `pack` call in `write_leUS` while trying to write the length.\r\n\r\nThe standard says for this case in PS3.5, Table 6.2-1 (for VR DS):\r\n```\r\nNote\r\nData Elements with multiple values using this VR may not be properly encoded if Explicit-VR transfer syntax is used and the VL of this attribute exceeds 65534 bytes.\r\n```\r\nSo, as I understand it, this is valid DICOM, that cannot be converted to explicit encoding without data loss.\r\nThe question is how to handle this. What comes to mind:\r\n- truncate the value and log a warning\r\n- raise a meaningful exception\r\n- adapt the behavior depending on some config setting\r\n\r\nAny thoughts?\r\n\r\n<!-- Example: Attribute Error thrown when printing (0x0010, 0x0020) patient Id> 0-->\r\n\r\n#### Steps/Code to Reproduce\r\n<!--\r\nExample:\r\n```py\r\nfrom io import BytesIO\r\nfrom pydicom import dcmread\r\n\r\nbytestream = b'\\x02\\x00\\x02\\x00\\x55\\x49\\x16\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31' \\\r\n b'\\x30\\x30\\x30\\x38\\x2e\\x35\\x2e\\x31\\x2e\\x31\\x2e\\x39\\x00\\x02\\x00\\x10\\x00' \\\r\n b'\\x55\\x49\\x12\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31\\x30\\x30\\x30\\x38' \\\r\n b'\\x2e\\x31\\x2e\\x32\\x00\\x20\\x20\\x10\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x20\\x20' \\\r\n b'\\x20\\x00\\x06\\x00\\x00\\x00\\x4e\\x4f\\x52\\x4d\\x41\\x4c'\r\n\r\nfp = BytesIO(bytestream)\r\nds = dcmread(fp, force=True)\r\n\r\nprint(ds.PatientID)\r\n```\r\nIf the code is too long, feel free to put it in a public gist and link\r\nit in the issue: https://gist.github.com\r\n\r\nWhen possible use pydicom testing examples to reproduce the errors. Otherwise, provide\r\nan anonymous version of the data in order to replicate the errors.\r\n-->\r\n\r\n#### Expected Results\r\n<!-- Please paste or describe the expected results.\r\nExample: No error is thrown and the name of the patient is printed.-->\r\n\r\n#### Actual Results\r\n<!-- Please paste or specifically describe the actual output or traceback.\r\n(Use %xmode to deactivate ipython's trace beautifier)\r\nExample: ```AttributeError: 'FileDataset' object has no attribute 'PatientID'```\r\n-->\r\n\r\n#### Versions\r\n<!--\r\nPlease run the following snippet and paste the output below.\r\nimport platform; print(platform.platform())\r\nimport sys; print(\"Python\", sys.version)\r\nimport pydicom; print(\"pydicom\", pydicom.__version__)\r\n-->\r\n\r\n\r\n<!-- Thanks for contributing! -->\r\n\n", "hints_text": "Interesting situation. To summarize: with implicit VR and the four-byte length it uses, we can read in something longer than **Ex**plicit VR can write, because it uses only two bytes for encoding the length (for VRs like DS).\r\n\r\nI say we catch the exception and re-raise with a meaningful error message. If the user wants to truncate the data to avoid this, they can choose how to do so, i.e. what to leave out. Or they can save the dataset using Implicit VR. The error message could explain those two options.\r\n\r\n\n> I say we catch the exception and re-raise with a meaningful error message\r\n\r\nAgreed - I will have a go at this some time later. \r\nI have to admit that I was quite surprised to see this behavior - while I did know that implicit transfer syntax has other length fields, I never thought that this would ever matter.\nReopen as the fix is incorrect - the VR shall be changed to UN instead (see #900).", "created_at": "2019-07-27T19:22:28Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1033", "base_commit": "701c1062bf66de2b29df68fa5540be6009943885", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -315,32 +315,21 @@ def to_json_dict(self, bulk_data_element_handler, bulk_data_threshold):\n via DICOMweb WADO-RS\n bulk_data_threshold: int\n Size of base64 encoded data element above which a value will be\n- provided in form of a \"BulkDataURI\" rather than \"InlineBinary\"\n+ provided in form of a \"BulkDataURI\" rather than \"InlineBinary\".\n+ Ignored if no bulk data handler is given.\n \n Returns\n -------\n dict\n Mapping representing a JSON encoded data element\n-\n- Raises\n- ------\n- TypeError\n- When size of encoded data element exceeds `bulk_data_threshold`\n- but `bulk_data_element_handler` is ``None`` and hence not callable\n-\n \"\"\"\n json_element = {'vr': self.VR, }\n if self.VR in jsonrep.BINARY_VR_VALUES:\n if not self.is_empty:\n binary_value = self.value\n encoded_value = base64.b64encode(binary_value).decode('utf-8')\n- if len(encoded_value) > bulk_data_threshold:\n- if bulk_data_element_handler is None:\n- raise TypeError(\n- 'No bulk data element handler provided to '\n- 'generate URL for value of data element \"{}\".'\n- .format(self.name)\n- )\n+ if (bulk_data_element_handler is not None and\n+ len(encoded_value) > bulk_data_threshold):\n json_element['BulkDataURI'] = bulk_data_element_handler(\n self\n )\n@@ -398,7 +387,7 @@ def to_json_dict(self, bulk_data_element_handler, bulk_data_threshold):\n )\n return json_element\n \n- def to_json(self, bulk_data_threshold=1, bulk_data_element_handler=None,\n+ def to_json(self, bulk_data_threshold=1024, bulk_data_element_handler=None,\n dump_handler=None):\n \"\"\"Return a JSON representation of the :class:`DataElement`.\n \n@@ -412,7 +401,8 @@ def to_json(self, bulk_data_threshold=1, bulk_data_element_handler=None,\n via DICOMweb WADO-RS\n bulk_data_threshold: int\n Size of base64 encoded data element above which a value will be\n- provided in form of a \"BulkDataURI\" rather than \"InlineBinary\"\n+ provided in form of a \"BulkDataURI\" rather than \"InlineBinary\".\n+ Ignored if no bulk data handler is given.\n dump_handler : callable, optional\n Callable function that accepts a :class:`dict` and returns the\n serialized (dumped) JSON string (by default uses\n@@ -423,12 +413,6 @@ def to_json(self, bulk_data_threshold=1, bulk_data_element_handler=None,\n dict\n Mapping representing a JSON encoded data element\n \n- Raises\n- ------\n- TypeError\n- When size of encoded data element exceeds `bulk_data_threshold`\n- but `bulk_data_element_handler` is ``None`` and hence not callable\n-\n See also\n --------\n Dataset.to_json\ndiff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -2126,11 +2126,11 @@ def from_json(cls, json_dataset, bulk_data_uri_handler=None):\n dataset.add(data_element)\n return dataset\n \n- def to_json_dict(self, bulk_data_threshold=1,\n+ def to_json_dict(self, bulk_data_threshold=1024,\n bulk_data_element_handler=None):\n \"\"\"Return a dictionary representation of the :class:`Dataset`\n conforming to the DICOM JSON Model as described in the DICOM\n- Standard, Part 18, :dcm:`Annex F<part18/chaptr_F.html>`.\n+ Standard, Part 18, :dcm:`Annex F<part18/chapter_F.html>`.\n \n .. versionadded:: 1.4\n \n@@ -2140,7 +2140,7 @@ def to_json_dict(self, bulk_data_threshold=1,\n Threshold for the length of a base64-encoded binary data element\n above which the element should be considered bulk data and the\n value provided as a URI rather than included inline (default:\n- ``1``).\n+ ``1024``). Ignored if no bulk data handler is given.\n bulk_data_element_handler : callable, optional\n Callable function that accepts a bulk data element and returns a\n JSON representation of the data element (dictionary including the\n@@ -2161,7 +2161,7 @@ def to_json_dict(self, bulk_data_threshold=1,\n )\n return json_dataset\n \n- def to_json(self, bulk_data_threshold=1, bulk_data_element_handler=None,\n+ def to_json(self, bulk_data_threshold=1024, bulk_data_element_handler=None,\n dump_handler=None):\n \"\"\"Return a JSON representation of the :class:`Dataset`.\n \n@@ -2175,7 +2175,7 @@ def to_json(self, bulk_data_threshold=1, bulk_data_element_handler=None,\n Threshold for the length of a base64-encoded binary data element\n above which the element should be considered bulk data and the\n value provided as a URI rather than included inline (default:\n- ``1``).\n+ ``1024``). Ignored if no bulk data handler is given.\n bulk_data_element_handler : callable, optional\n Callable function that accepts a bulk data element and returns a\n JSON representation of the data element (dictionary including the\n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -1,12 +1,11 @@\n # -*- coding: utf-8 -*-\n # Copyright 2008-2019 pydicom authors. See LICENSE file for details.\n import json\n-import sys\n \n import pytest\n \n from pydicom import dcmread, compat\n-from pydicom.data import get_testdata_files\n+from pydicom.data import get_testdata_file\n from pydicom.dataelem import DataElement\n from pydicom.dataset import Dataset\n from pydicom.tag import Tag, BaseTag\n@@ -15,7 +14,7 @@\n \n class TestPersonName(object):\n def test_json_pn_from_file(self):\n- with open(get_testdata_files(\"test_PN.json\")[0]) as s:\n+ with open(get_testdata_file(\"test_PN.json\")) as s:\n ds = Dataset.from_json(s.read())\n assert isinstance(ds[0x00080090].value,\n (PersonNameUnicode, PersonName3))\n@@ -144,7 +143,7 @@ def test_from_json(self):\n assert 0x000910AF == ds[0x00091001].value\n assert [0x00100010, 0x00100020, 0x00100030] == ds[0x00091002].value\n \n- def test_invalid_json(self):\n+ def test_invalid_value_in_json(self):\n ds_json = ('{\"00091001\": {\"vr\": \"AT\", \"Value\": [\"000910AG\"]}, '\n '\"00091002\": {\"vr\": \"AT\", \"Value\": [\"00100010\"]}}')\n with pytest.warns(UserWarning, match='Invalid value \"000910AG\" for '\n@@ -153,15 +152,24 @@ def test_invalid_json(self):\n assert ds[0x00091001].value is None\n assert 0x00100010 == ds[0x00091002].value\n \n+ def test_invalid_tag_in_json(self):\n+ ds_json = ('{\"000910AG\": {\"vr\": \"AT\", \"Value\": [\"00091000\"]}, '\n+ '\"00091002\": {\"vr\": \"AT\", \"Value\": [\"00100010\"]}}')\n+ with pytest.raises(ValueError, match='Data element \"000910AG\" could '\n+ 'not be loaded from JSON:'):\n+ ds = Dataset.from_json(ds_json)\n+ assert ds[0x00091001].value is None\n+ assert 0x00100010 == ds[0x00091002].value\n+\n \n class TestDataSetToJson(object):\n def test_json_from_dicom_file(self):\n- ds1 = Dataset(dcmread(get_testdata_files(\"CT_small.dcm\")[0]))\n- ds_json = ds1.to_json(bulk_data_threshold=100000)\n+ ds1 = Dataset(dcmread(get_testdata_file(\"CT_small.dcm\")))\n+ ds_json = ds1.to_json()\n ds2 = Dataset.from_json(ds_json)\n assert ds1 == ds2\n \n- ds_json = ds1.to_json_dict(bulk_data_threshold=100000)\n+ ds_json = ds1.to_json_dict()\n ds2 = Dataset.from_json(ds_json)\n assert ds1 == ds2\n \n@@ -205,7 +213,7 @@ def test_roundtrip(self):\n ds.add_new(0x00091101, 'SH', 'Version2')\n ds.add_new(0x00091102, 'US', 2)\n \n- json_string = ds.to_json(bulk_data_threshold=100)\n+ json_string = ds.to_json()\n json_model = json.loads(json_string)\n \n assert json_model['00080005']['Value'] == ['ISO_IR 100']\n@@ -223,7 +231,7 @@ def test_roundtrip(self):\n ds2 = Dataset.from_json(json_model)\n assert ds == ds2\n \n- json_model2 = ds.to_json_dict(bulk_data_threshold=100)\n+ json_model2 = ds.to_json_dict()\n if compat.in_py2:\n # in Python 2, the encoding of this is slightly different\n # (single vs double quotation marks)\n@@ -274,7 +282,7 @@ def test_sort_order(self):\n \n class TestSequence(object):\n def test_nested_sequences(self):\n- test1_json = get_testdata_files(\"test1.json\")[0]\n+ test1_json = get_testdata_file(\"test1.json\")\n with open(test1_json) as f:\n with pytest.warns(UserWarning,\n match='no bulk data URI handler provided '):\n@@ -288,7 +296,7 @@ class TestBinary(object):\n def test_inline_binary(self):\n ds = Dataset()\n ds.add_new(0x00091002, 'OB', b'BinaryContent')\n- ds_json = ds.to_json_dict(bulk_data_threshold=20)\n+ ds_json = ds.to_json_dict()\n assert \"00091002\" in ds_json\n assert \"QmluYXJ5Q29udGVudA==\" == ds_json[\"00091002\"][\"InlineBinary\"]\n ds1 = Dataset.from_json(ds_json)\n", "problem_statement": "to_json does not work with binary data in pixel_array\n**Describe the issue**\r\nLoading a dicom file and then performing a to_json() on it does not work with binary data in pixel_array.\r\n\r\n\r\n\r\n**Expected behavior**\r\nI would have expected that a base64 conversion is first performed on the binary data and then encoded to json. \r\n\r\n**Steps To Reproduce**\r\nHow to reproduce the issue. Please include:\r\n1. A minimum working code sample\r\n\r\nimport pydicom\r\nds = pydicom.dcmread('path_to_file')\r\noutput = ds.to_json()\r\n\r\n\r\n2. The traceback (if one occurred)\r\n\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/.virtualenvs/my_env/lib/python3.7/site-packages/pydicom/dataset.py\", line 2003, in to_json\r\n dump_handler=dump_handler\r\n File \"/.virtualenvs/my_env/lib/python3.7/site-packages/pydicom/dataset.py\", line 1889, in _data_element_to_json\r\n binary_value = data_element.value.encode('utf-8')\r\nAttributeError: 'bytes' object has no attribute 'encode'\r\n\r\n\r\n3. Which of the following packages are available and their versions:\r\n * Numpy\r\nnumpy==1.17.2\r\n * Pillow\r\nPillow==6.1.0\r\n * JPEG-LS\r\n * GDCM\r\n4. The anonymized DICOM dataset (if possible).\r\n\r\n**Your environment**\r\nPlease run the following and paste the output.\r\n```bash\r\n$ python -c \"import platform; print(platform.platform())\"\r\nDarwin-19.2.0-x86_64-i386-64bit\r\n$ python -c \"import sys; print('Python ', sys.version)\"\r\nPython 3.7.6 (default, Dec 30 2019, 19:38:26) \r\n[Clang 11.0.0 (clang-1100.0.33.16)]\r\n$ python -c \"import pydicom; print('pydicom ', pydicom.__version__)\"\r\npydicom 1.3.0\r\n```\r\n\n", "hints_text": "Can you please check with pydicom 1.4? Binary data handling should have been fixed there. \nok works now once I set the bulk_data_threshold value to a higher value. \r\n\r\nThank you!\nOk, that may be an issue with the data size. Currently, the default for `bulk_data_threshold` is 1, if I remember correctly, which may not be the best value - meaning that all binary data larger than that expect a bulk data element handler. Setting the threshold to a large value shall fix this, if the data is encoded directly.\nAh, you already found that, ok!\r\n\nyep. thanks, works now. \n@darcymason - json support is still flagged as alpha - I think we can consider it at least beta now, and add a small section in the documentation.\r\nWe may also rethink the `bulk_data_threshold` parameter - maybe just ignore it if no bulk data handler is set, and set the default value to some sensible value (1kB or something).\n> @darcymason - json support is still flagged as alpha - I think we can consider it at least beta now, and add a small section in the documentation.\r\n> We may also rethink the `bulk_data_threshold` parameter - maybe just ignore it if no bulk data handler is set, and set the default value to some sensible value (1kB or something).\r\n\r\nI agree that updating the documentation is a good idea for this. As its pretty common to have binary image data in dicom files, and its guaranteed to fail with the default value for bulk_data_threshold\r\n\r\nThanks once again though!\nPing @pieper, @hackermd for comment about `bulk_data_threshold`.\n> We may also rethink the bulk_data_threshold parameter - maybe just ignore it if no bulk data handler is set, and set the default value to some sensible value (1kB or something).\r\n\r\n1k threshold makes sense to me. \ud83d\udc4d ", "created_at": "2020-01-17T20:57:00Z", "version": "1.4", "FAIL_TO_PASS": ["pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestBinary::test_inline_binary"], "PASS_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called"], "environment_setup_commit": "5098c9147fadcb3e5918487036867931435adeb8"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1076", "base_commit": "caf0db105ddf389ff5025937fd5f3aa1e61e85e7", "patch": "diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -1004,7 +1004,7 @@ def dcmwrite(filename, dataset, write_like_original=True):\n 'LT': (write_text, None),\n 'OB': (write_OBvalue, None),\n 'OD': (write_OWvalue, None),\n- 'OF': (write_numbers, 'f'),\n+ 'OF': (write_OWvalue, None),\n 'OL': (write_OWvalue, None),\n 'OW': (write_OWvalue, None),\n 'OV': (write_OWvalue, None),\ndiff --git a/pydicom/values.py b/pydicom/values.py\n--- a/pydicom/values.py\n+++ b/pydicom/values.py\n@@ -634,7 +634,7 @@ def convert_value(VR, raw_data_element, encodings=None):\n 'LT': convert_single_string,\n 'OB': convert_OBvalue,\n 'OD': convert_OBvalue,\n- 'OF': (convert_numbers, 'f'),\n+ 'OF': convert_OWvalue,\n 'OL': convert_OBvalue,\n 'OW': convert_OWvalue,\n 'OV': convert_OVvalue,\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -700,6 +700,20 @@ def test_lut_descriptor_singleton(self):\n assert elem.value == -2816\n assert elem.VR == 'SS'\n \n+ def test_reading_of(self):\n+ \"\"\"Test reading a dataset with OF element.\"\"\"\n+ bs = DicomBytesIO(\n+ b'\\x28\\x00\\x01\\x11\\x53\\x53\\x06\\x00\\x00\\xf5\\x00\\xf8\\x10\\x00'\n+ b'\\xe0\\x7f\\x08\\x00\\x4F\\x46\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x01\\x02\\x03'\n+ )\n+ bs.is_little_endian = True\n+ bs.is_implicit_VR = False\n+\n+ ds = dcmread(bs, force=True)\n+ elem = ds['FloatPixelData']\n+ assert 'OF' == elem.VR\n+ assert b'\\x00\\x01\\x02\\x03' == elem.value\n+\n \n class TestIncorrectVR(object):\n def setup(self):\ndiff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -21,10 +21,11 @@\n from pydicom.dataelem import DataElement, RawDataElement\n from pydicom.filebase import DicomBytesIO\n from pydicom.filereader import dcmread, read_dataset, read_file\n-from pydicom.filewriter import (write_data_element, write_dataset,\n- correct_ambiguous_vr, write_file_meta_info,\n- correct_ambiguous_vr_element, write_numbers,\n- write_PN, _format_DT, write_text)\n+from pydicom.filewriter import (\n+ write_data_element, write_dataset, correct_ambiguous_vr,\n+ write_file_meta_info, correct_ambiguous_vr_element, write_numbers,\n+ write_PN, _format_DT, write_text, write_OWvalue\n+)\n from pydicom.multival import MultiValue\n from pydicom.sequence import Sequence\n from pydicom.uid import (ImplicitVRLittleEndian, ExplicitVRBigEndian,\n@@ -2251,6 +2252,32 @@ def test_write_big_endian(self):\n assert fp.getvalue() == b'\\x00\\x01'\n \n \n+class TestWriteOtherVRs(object):\n+ \"\"\"Tests for writing the 'O' VRs like OB, OW, OF, etc.\"\"\"\n+ def test_write_of(self):\n+ \"\"\"Test writing element with VR OF\"\"\"\n+ fp = DicomBytesIO()\n+ fp.is_little_endian = True\n+ elem = DataElement(0x7fe00008, 'OF', b'\\x00\\x01\\x02\\x03')\n+ write_OWvalue(fp, elem)\n+ assert fp.getvalue() == b'\\x00\\x01\\x02\\x03'\n+\n+ def test_write_of_dataset(self):\n+ \"\"\"Test writing a dataset with an element with VR OF.\"\"\"\n+ fp = DicomBytesIO()\n+ fp.is_little_endian = True\n+ fp.is_implicit_VR = False\n+ ds = Dataset()\n+ ds.is_little_endian = True\n+ ds.is_implicit_VR = False\n+ ds.FloatPixelData = b'\\x00\\x01\\x02\\x03'\n+ ds.save_as(fp)\n+ assert fp.getvalue() == (\n+ # Tag | VR | Length | Value\n+ b'\\xe0\\x7f\\x08\\x00\\x4F\\x46\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x01\\x02\\x03'\n+ )\n+\n+\n class TestWritePN(object):\n \"\"\"Test filewriter.write_PN\"\"\"\n \ndiff --git a/pydicom/tests/test_values.py b/pydicom/tests/test_values.py\n--- a/pydicom/tests/test_values.py\n+++ b/pydicom/tests/test_values.py\n@@ -5,9 +5,10 @@\n import pytest\n \n from pydicom.tag import Tag\n-from pydicom.values import (convert_value, converters, convert_tag,\n- convert_ATvalue, convert_DA_string, convert_text,\n- convert_single_string, convert_AE_string)\n+from pydicom.values import (\n+ convert_value, converters, convert_tag, convert_ATvalue, convert_DA_string,\n+ convert_text, convert_single_string, convert_AE_string\n+)\n \n \n class TestConvertTag(object):\n@@ -188,3 +189,11 @@ def test_convert_value_raises(self):\n # Fix converters\n converters['PN'] = converter_func\n assert 'PN' in converters\n+\n+\n+class TestConvertOValues(object):\n+ \"\"\"Test converting values with the 'O' VRs like OB, OW, OF, etc.\"\"\"\n+ def test_convert_of(self):\n+ \"\"\"Test converting OF.\"\"\"\n+ fp = b'\\x00\\x01\\x02\\x03'\n+ assert b'\\x00\\x01\\x02\\x03' == converters['OF'](fp, True)\n", "problem_statement": "Error writing values with VR OF\n[Related to this comment](https://github.com/pydicom/pydicom/issues/452#issuecomment-614038937) (I think)\r\n\r\n```python\r\nfrom pydicom.dataset import Dataset\r\nds = Dataset()\r\nds.is_little_endian = True\r\nds.is_implicit_VR = True\r\nds.FloatPixelData = b'\\x00\\x00\\x00\\x00'\r\nds.save_as('out.dcm')\r\n```\r\n```\r\nTraceback (most recent call last):\r\n File \".../pydicom/filewriter.py\", line 228, in write_numbers\r\n value.append # works only if list, not if string or number\r\nAttributeError: 'bytes' object has no attribute 'append'\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \".../pydicom/filewriter.py\", line 230, in write_numbers\r\n fp.write(pack(format_string, value))\r\nstruct.error: required argument is not a float\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \".../pydicom/tag.py\", line 27, in tag_in_exception\r\n yield\r\n File \".../pydicom/filewriter.py\", line 543, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \".../pydicom/filewriter.py\", line 472, in write_data_element\r\n writer_function(buffer, data_element, writer_param)\r\n File \".../pydicom/filewriter.py\", line 236, in write_numbers\r\n \"{0}\\nfor data_element:\\n{1}\".format(str(e), str(data_element)))\r\nOSError: required argument is not a float\r\nfor data_element:\r\n(7fe0, 0008) Float Pixel Data OF: b'\\x00\\x00\\x00\\x00'\r\n\r\n[skip]\r\n```\r\n[Error in filewriter](https://github.com/pydicom/pydicom/blob/master/pydicom/filewriter.py#L1007) using `write_numbers` instead of `write_OBvalue`/`write_OWvalue`. Looks like it's been wrong [since 2008](https://github.com/pydicom/pydicom/commit/5d3ea61ffe6877ae79267bf233f258c07c726998). I'm a bit surprised it hasn't come up before.\n", "hints_text": "", "created_at": "2020-04-17T01:12:48Z", "version": "1.4", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_reading_of", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of_dataset", "pydicom/tests/test_values.py::TestConvertOValues::test_convert_of"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_empty_numbers_tag", "pydicom/tests/test_filereader.py::TestReader::test_UTF8_filename", "pydicom/tests/test_filereader.py::TestReader::test_pathlib_path_filename", "pydicom/tests/test_filereader.py::TestReader::test_RTPlan", "pydicom/tests/test_filereader.py::TestReader::test_RTDose", "pydicom/tests/test_filereader.py::TestReader::test_CT", "pydicom/tests/test_filereader.py::TestReader::test_CT_PixelData", "pydicom/tests/test_filereader.py::TestReader::test_no_force", "pydicom/tests/test_filereader.py::TestReader::test_RTStruct", "pydicom/tests/test_filereader.py::TestReader::test_dir", "pydicom/tests/test_filereader.py::TestReader::test_MR", "pydicom/tests/test_filereader.py::TestReader::test_deflate", "pydicom/tests/test_filereader.py::TestReader::test_no_pixels_read", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_SQ", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_tag", "pydicom/tests/test_filereader.py::TestReader::test_tag_with_unknown_length_tag_too_short", "pydicom/tests/test_filereader.py::TestReader::test_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_nested_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_no_meta_group_length", "pydicom/tests/test_filereader.py::TestReader::test_no_transfer_syntax_in_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_little_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_big_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_planar_config", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::TestReader::test_long_specific_char_set", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::TestReader::test_group_length_wrong", "pydicom/tests/test_filereader.py::TestReader::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_empty_file", "pydicom/tests/test_filereader.py::TestReader::test_empty_specific_character_set", "pydicom/tests/test_filereader.py::TestReader::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor_empty", "pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor_singleton", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_seq_item_looks_like_explicit_VR", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_AE", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OV_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_SV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UV_explicit_little", "pydicom/tests/test_filereader.py::TestDeferredRead::test_time_check", "pydicom/tests/test_filereader.py::TestDeferredRead::test_file_exists", "pydicom/tests/test_filereader.py::TestDeferredRead::test_values_identical", "pydicom/tests/test_filereader.py::TestDeferredRead::test_zipped_deferred", "pydicom/tests/test_filereader.py::TestDeferredRead::test_filelike_deferred", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelDataArray", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_object", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_like_object", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding", "pydicom/tests/test_values.py::TestConvertTag::test_big_endian", "pydicom/tests/test_values.py::TestConvertTag::test_little_endian", "pydicom/tests/test_values.py::TestConvertTag::test_offset", "pydicom/tests/test_values.py::TestConvertAE::test_strip_blanks", "pydicom/tests/test_values.py::TestConvertText::test_single_value", "pydicom/tests/test_values.py::TestConvertText::test_multi_value", "pydicom/tests/test_values.py::TestConvertText::test_single_value_with_backslash", "pydicom/tests/test_values.py::TestConvertText::test_single_value_with_delimiters", "pydicom/tests/test_values.py::TestConvertText::test_value_ending_with_padding", "pydicom/tests/test_values.py::TestConvertAT::test_big_endian", "pydicom/tests/test_values.py::TestConvertAT::test_little_endian", "pydicom/tests/test_values.py::TestConvertAT::test_empty_bytestring", "pydicom/tests/test_values.py::TestConvertDA::test_big_endian", "pydicom/tests/test_values.py::TestConvertDA::test_little_endian", "pydicom/tests/test_values.py::TestConvertDA::test_empty_bytestring", "pydicom/tests/test_values.py::TestConvertValue::test_convert_value_raises"], "environment_setup_commit": "5098c9147fadcb3e5918487036867931435adeb8"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1458", "base_commit": "8da0b9b215ebfad5756051c891def88e426787e7", "patch": "diff --git a/pydicom/pixel_data_handlers/numpy_handler.py b/pydicom/pixel_data_handlers/numpy_handler.py\n--- a/pydicom/pixel_data_handlers/numpy_handler.py\n+++ b/pydicom/pixel_data_handlers/numpy_handler.py\n@@ -43,7 +43,9 @@\n | (0028,0100) | BitsAllocated | 1 | 1, 8, 16, 32, | Required |\n | | | | 64 | |\n +-------------+---------------------------+------+---------------+----------+\n-| (0028,0103) | PixelRepresentation | 1 | 0, 1 | Required |\n+| (0028,0101) | BitsStored | 1 | 1, 8, 12, 16 | Optional |\n++-------------+---------------------------+------+---------------+----------+\n+| (0028,0103) | PixelRepresentation | 1C | 0, 1 | Optional |\n +-------------+---------------------------+------+---------------+----------+\n \n \"\"\"\n@@ -284,16 +286,28 @@ def get_pixeldata(ds: \"Dataset\", read_only: bool = False) -> \"np.ndarray\":\n \"the dataset\"\n )\n \n+ # Attributes required by both Floating Point Image Pixel Module Attributes\n+ # and Image Pixel Description Macro Attributes\n required_elements = [\n- 'BitsAllocated', 'Rows', 'Columns', 'PixelRepresentation',\n+ 'BitsAllocated', 'Rows', 'Columns',\n 'SamplesPerPixel', 'PhotometricInterpretation'\n ]\n+ if px_keyword[0] == 'PixelData':\n+ # Attributess required by Image Pixel Description Macro Attributes\n+ required_elements.extend(['PixelRepresentation', 'BitsStored'])\n missing = [elem for elem in required_elements if elem not in ds]\n if missing:\n raise AttributeError(\n \"Unable to convert the pixel data as the following required \"\n \"elements are missing from the dataset: \" + \", \".join(missing)\n )\n+ if ds.SamplesPerPixel > 1:\n+ if not hasattr(ds, 'PlanarConfiguration'):\n+ raise AttributeError(\n+ \"Unable to convert the pixel data as the following \"\n+ \"conditionally required element is missing from the dataset: \"\n+ \"PlanarConfiguration\"\n+ )\n \n # May be Pixel Data, Float Pixel Data or Double Float Pixel Data\n pixel_data = getattr(ds, px_keyword[0])\n", "test_patch": "diff --git a/pydicom/tests/test_numpy_pixel_data.py b/pydicom/tests/test_numpy_pixel_data.py\n--- a/pydicom/tests/test_numpy_pixel_data.py\n+++ b/pydicom/tests/test_numpy_pixel_data.py\n@@ -26,6 +26,8 @@\n * PlanarConfiguration\n \"\"\"\n \n+from copy import deepcopy\n+\n import pytest\n \n from pydicom import config\n@@ -1068,6 +1070,7 @@ def test_endianness_not_set(self):\n ds.Rows = 10\n ds.Columns = 10\n ds.BitsAllocated = 16\n+ ds.BitsStored = 16\n ds.PixelRepresentation = 0\n ds.SamplesPerPixel = 1\n ds.PhotometricInterpretation = 'MONOCHROME2'\n@@ -1105,16 +1108,60 @@ def test_no_pixel_data_raises(self):\n with pytest.raises(AttributeError, match=msg):\n get_pixeldata(ds)\n \n- def test_missing_required_elem(self):\n+ def test_missing_required_elem_pixel_data_monochrome(self):\n \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n- ds = dcmread(EXPL_16_1_1F)\n- del ds.BitsAllocated\n+ required_attrs = (\n+ 'BitsAllocated',\n+ 'BitsStored',\n+ 'Rows',\n+ 'Columns',\n+ 'SamplesPerPixel',\n+ 'PhotometricInterpretation',\n+ 'PixelRepresentation',\n+ )\n+ for attr in required_attrs:\n+ ds = dcmread(EXPL_16_1_1F)\n+ delattr(ds, attr)\n+ msg = (\n+ r\"Unable to convert the pixel data as the following required \"\n+ r\"elements are missing from the dataset: {}\".format(attr)\n+ )\n+ with pytest.raises(AttributeError, match=msg):\n+ get_pixeldata(ds)\n+\n+ def test_missing_required_elem_pixel_data_color(self):\n+ \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n+ ds = dcmread(EXPL_8_3_1F)\n+ del ds.Rows\n+ del ds.Columns\n+ msg = (\n+ r\"Unable to convert the pixel data as the following required \"\n+ r\"elements are missing from the dataset: Rows, Columns\"\n+ )\n+ with pytest.raises(AttributeError, match=msg):\n+ get_pixeldata(ds)\n+\n+ def test_missing_conditionally_required_elem_pixel_data_color(self):\n+ \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n+ ds = dcmread(EXPL_8_3_1F)\n+ del ds.PlanarConfiguration\n+ msg = (\n+ r\"Unable to convert the pixel data as the following conditionally \"\n+ r\"required element is missing from the dataset: \"\n+ r\"PlanarConfiguration\"\n+ )\n+ with pytest.raises(AttributeError, match=msg):\n+ get_pixeldata(ds)\n+\n+ def test_missing_required_elem_float_pixel_data_monochrome(self):\n+ \"\"\"Tet get_pixeldata raises if dataset missing required element.\"\"\"\n+ ds = dcmread(IMPL_32_1_1F)\n+ ds.FloatPixelData = ds.PixelData\n+ del ds.PixelData\n del ds.Rows\n- del ds.SamplesPerPixel\n msg = (\n r\"Unable to convert the pixel data as the following required \"\n- r\"elements are missing from the dataset: BitsAllocated, Rows, \"\n- r\"SamplesPerPixel\"\n+ r\"elements are missing from the dataset: Rows\"\n )\n with pytest.raises(AttributeError, match=msg):\n get_pixeldata(ds)\n", "problem_statement": "Pixel Representation attribute should be optional for pixel data handler\n**Describe the bug**\r\nThe NumPy pixel data handler currently [requires the Pixel Representation attribute](https://github.com/pydicom/pydicom/blob/8da0b9b215ebfad5756051c891def88e426787e7/pydicom/pixel_data_handlers/numpy_handler.py#L46). This is problematic, because in case of Float Pixel Data or Double Float Pixel Data the attribute shall be absent. Compare [Floating Point Image Pixel Module Attributes](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.24.html) versus [Image Pixel Description Macro Attributes](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.6.3.html#table_C.7-11c)\r\n\r\n**Expected behavior**\r\nI would expect the `Dataset.pixel_array` property to be able to decode a Float Pixel Data or Double Float Pixel Data element without presence of the Pixel Representation element in the metadata.\r\n\r\n**Steps To Reproduce**\r\n```python\r\nimport numpy as np\r\nfrom pydicom.dataset import Dataset, FileMetaDataset\r\n\r\n\r\nds = Dataset()\r\nds.file_meta = FileMetaDataset()\r\nds.file_meta.TransferSyntaxUID = '1.2.840.10008.1.2.1'\r\n\r\nds.BitsAllocated = 32\r\nds.SamplesPerPixel = 1\r\nds.Rows = 5\r\nds.Columns = 5\r\nds.PhotometricInterpretation = 'MONOCHROME2'\r\n\r\npixel_array = np.zeros((ds.Rows, ds.Columns), dtype=np.float32)\r\nds.FloatPixelData = pixel_array.flatten().tobytes()\r\n\r\nnp.array_equal(ds.pixel_array, pixel_array)\r\n```\n", "hints_text": "", "created_at": "2021-08-04T15:22:07Z", "version": "2.2", "FAIL_TO_PASS": ["pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_required_elem_pixel_data_monochrome", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_conditionally_required_elem_pixel_data_color"], "PASS_TO_PASS": ["pydicom/tests/test_numpy_pixel_data.py::test_unsupported_syntaxes", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_supported_dataset", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NoNumpyHandler::test_pixel_array_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_environment", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_unsupported_syntax_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_dataset_pixel_array_handler_needs_convert", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_dataset_pixel_array_no_pixels", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_dcmtk.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG-lossy.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_jpeg_gdcm.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/guest/jy1682/.pydicom/data/emri_small_jpeg_2k_lossless.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/JPEG2000.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_can_access_unsupported_dataset[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_RLE.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_8bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[numpy]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[NumPy]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[np]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[np_handler]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_decompress_using_handler[numpy_handler]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_16bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_pixel_array_32bit_un_signed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_1sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame_odd_size", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame_ybr422", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_8bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/liver_1frame.dcm-data0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/liver.dcm-data1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A.dcm-data2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_rgb_small_odd.dcm-data3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/SC_ybr_full_422_uncompressed.dcm-data4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_2frame.dcm-data5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb.dcm-data6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_2frame.dcm-data7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small.dcm-data8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/emri_small.dcm-data9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit.dcm-data10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit_2frame.dcm-data11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_1frame.dcm-data12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose.dcm-data13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit.dcm-data14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_properties[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit_2frame.dcm-data15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_1bit_1sample_3frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_1frame_padded", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_1sample_10frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_16bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_1sample_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_3sample_2frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_float_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_32bit_float_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_64bit_float_1frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_little_64bit_float_15frame", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/liver_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/liver_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/liver.dcm-/n/fs/guest/jy1682/.pydicom/data/liver_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A.dcm-/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/OBXXXX1A_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/MR_small_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/emri_small.dcm-/n/fs/guest/jy1682/.pydicom/data/emri_small_big_endian.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_16bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_16bit_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_16bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_1frame.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_expb_1frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose.dcm-/n/fs/p-swe-bench/temp/tmpqcg17m39/pydicom__pydicom__2.2/pydicom/data/test_files/rtdose_expb.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_32bit.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_big_endian_datasets[/n/fs/guest/jy1682/.pydicom/data/SC_rgb_32bit_2frame.dcm-/n/fs/guest/jy1682/.pydicom/data/SC_rgb_expb_32bit_2frame.dcm]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_endianness_not_set", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_NumpyHandler::test_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_no_pixel_data_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_required_elem_pixel_data_color", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_required_elem_float_pixel_data_monochrome", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unknown_pixel_representation_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_unsupported_syntaxes_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_bad_length_raises", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_missing_padding_warns", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_change_photometric_interpretation", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_array_read_only_bit_packed", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_ybr422_excess_padding", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_ybr422_wrong_interpretation", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_float_pixel_data", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_GetPixelData::test_double_float_pixel_data", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[-output0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00-output1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01-output2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x02-output3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x04-output4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x08-output5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x10-output6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[@-output8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80-output9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xaa-output10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xf0-output11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x0f-output12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff-output13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x00-output14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x01-output15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\x80-output16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x00\\xff-output17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x01\\x80-output18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\x80\\x80-output19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_UnpackBits::test_unpack[\\xff\\x80-output20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00-input1]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x02-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x08-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x10-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80-input9]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xaa-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xf0-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x0f-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x00-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x01-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\x80-input16]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x00\\xff-input17]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x01\\x80-input18]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\x80\\x80-input19]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack[\\xff\\x80-input20]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_non_binary_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_ndarray_input", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_padding", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00@-input0]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x10-input2]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x08-input3]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x04-input4]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x02-input5]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x00\\x01-input6]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x80-input7]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[@-input8]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x10-input10]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x08-input11]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x04-input12]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x02-input13]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[\\x01-input14]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_pack_partial[-input15]", "pydicom/tests/test_numpy_pixel_data.py::TestNumpy_PackBits::test_functional"], "environment_setup_commit": "0fa18d2a2179c92efc22200ed6b3689e66cecf92"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1720", "base_commit": "a8be738418dee0a2b93c241fbd5e0bc82f4b8680", "patch": "diff --git a/pydicom/config.py b/pydicom/config.py\n--- a/pydicom/config.py\n+++ b/pydicom/config.py\n@@ -268,6 +268,18 @@ def disable_value_validation() -> Generator:\n settings._writing_validation_mode = writing_mode\n \n \n+@contextmanager\n+def strict_reading() -> Generator:\n+ \"\"\"Context manager to temporarily enably strict value validation\n+ for reading.\"\"\"\n+ original_reading_mode = settings._reading_validation_mode\n+ try:\n+ settings.reading_validation_mode = RAISE\n+ yield\n+ finally:\n+ settings._reading_validation_mode = original_reading_mode\n+\n+\n convert_wrong_length_to_UN = False\n \"\"\"Convert a field VR to \"UN\" and return bytes if bytes length is invalid.\n Default ``False``.\ndiff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -16,6 +16,7 @@\n \"\"\"\n import copy\n from bisect import bisect_left\n+from contextlib import nullcontext\n import io\n from importlib.util import find_spec as have_package\n import inspect # for __dir__\n@@ -2490,18 +2491,23 @@ def to_json_dict(\n :class:`Dataset` representation based on the DICOM JSON Model.\n \"\"\"\n json_dataset = {}\n- for key in self.keys():\n- json_key = '{:08X}'.format(key)\n- try:\n- data_element = self[key]\n- json_dataset[json_key] = data_element.to_json_dict(\n- bulk_data_element_handler=bulk_data_element_handler,\n- bulk_data_threshold=bulk_data_threshold\n- )\n- except Exception as exc:\n- logger.error(f\"Error while processing tag {json_key}\")\n- if not suppress_invalid_tags:\n- raise exc\n+ context = (\n+ config.strict_reading() if suppress_invalid_tags\n+ else nullcontext()\n+ )\n+ with context:\n+ for key in self.keys():\n+ json_key = '{:08X}'.format(key)\n+ try:\n+ data_element = self[key]\n+ json_dataset[json_key] = data_element.to_json_dict(\n+ bulk_data_element_handler=bulk_data_element_handler,\n+ bulk_data_threshold=bulk_data_threshold\n+ )\n+ except Exception as exc:\n+ logger.error(f\"Error while processing tag {json_key}\")\n+ if not suppress_invalid_tags:\n+ raise exc\n \n return json_dataset\n \ndiff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -1248,6 +1248,48 @@ def DS(\n return DSfloat(val, auto_format, validation_mode)\n \n \n+class ISfloat(float):\n+ \"\"\"Store value for an element with VR **IS** as :class:`float`.\n+\n+ Stores original integer string for exact rewriting of the string\n+ originally read or stored.\n+\n+ Note: By the DICOM standard, IS can only be an :class:`int`,\n+ however, it is not uncommon to see float IS values. This class\n+ is used if the config settings allow non-strict reading.\n+\n+ Generally, use :class:`~pydicom.valuerep.IS` to create IS values,\n+ this is returned instead if the value cannot be represented as an\n+ :class:`int`. See :class:`~pydicom.valuerep.IS` for details of the\n+ parameters and return values.\n+ \"\"\"\n+ def __new__( # type: ignore[misc]\n+ cls: Type[\"ISfloat\"], val: Union[str, float, Decimal],\n+ validation_mode: int = None\n+ ) -> float:\n+ return super().__new__(cls, val)\n+\n+ def __init__(self, val: Union[str, float, Decimal],\n+ validation_mode: int = None) -> None:\n+ # If a string passed, then store it\n+ if isinstance(val, str):\n+ self.original_string = val.strip()\n+ elif isinstance(val, (IS, ISfloat)) and hasattr(val, 'original_string'):\n+ self.original_string = val.original_string\n+ if validation_mode:\n+ msg = (\n+ f'Value \"{str(self)}\" is not valid for elements with a VR '\n+ 'of IS'\n+ )\n+ if validation_mode == config.WARN:\n+ warnings.warn(msg)\n+ elif validation_mode == config.RAISE:\n+ msg += (\n+ \"\\nSet reading_validation_mode to WARN or IGNORE to bypass\"\n+ )\n+ raise TypeError(msg)\n+\n+\n class IS(int):\n \"\"\"Store value for an element with VR **IS** as :class:`int`.\n \n@@ -1258,7 +1300,7 @@ class IS(int):\n def __new__( # type: ignore[misc]\n cls: Type[\"IS\"], val: Union[None, str, int, float, Decimal],\n validation_mode: int = None\n- ) -> Optional[Union[str, \"IS\"]]:\n+ ) -> Optional[Union[str, \"IS\", \"ISfloat\"]]:\n \"\"\"Create instance if new integer string\"\"\"\n if val is None:\n return val\n@@ -1272,16 +1314,16 @@ def __new__( # type: ignore[misc]\n validate_value(\"IS\", val, validation_mode)\n \n try:\n- newval = super().__new__(cls, val)\n+ newval: Union[IS, ISfloat] = super().__new__(cls, val)\n except ValueError:\n # accept float strings when no integer loss, e.g. \"1.0\"\n newval = super().__new__(cls, float(val))\n \n- # check if a float or Decimal passed in, then could have lost info,\n- # and will raise error. E.g. IS(Decimal('1')) is ok, but not IS(1.23)\n- # IS('1.23') will raise ValueError\n+ # If a float or Decimal was passed in, check for non-integer,\n+ # i.e. could lose info if converted to int\n+ # If so, create an ISfloat instead (if allowed by settings)\n if isinstance(val, (float, Decimal, str)) and newval != float(val):\n- raise TypeError(\"Could not convert value to integer without loss\")\n+ newval = ISfloat(val, validation_mode)\n \n # Checks in case underlying int is >32 bits, DICOM does not allow this\n if (not -2**31 <= newval < 2**31 and\n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -5,6 +5,7 @@\n \n import pytest\n \n+from pydicom import config\n from pydicom import dcmread\n from pydicom.data import get_testdata_file\n from pydicom.dataelem import DataElement, RawDataElement\n@@ -293,13 +294,10 @@ def test_suppress_invalid_tags_with_failed_dataelement(self):\n # we have to add a RawDataElement as creating a DataElement would\n # already raise an exception\n ds[0x00082128] = RawDataElement(\n- Tag(0x00082128), 'IS', 4, b'5.25', 0, True, True)\n-\n- with pytest.raises(TypeError):\n- ds.to_json_dict()\n+ Tag(0x00082128), 'IS', 4, b'5.25', 0, True, True\n+ )\n \n ds_json = ds.to_json_dict(suppress_invalid_tags=True)\n-\n assert \"00082128\" not in ds_json\n \n \ndiff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -6,6 +6,7 @@\n from datetime import datetime, date, time, timedelta, timezone\n from decimal import Decimal\n from itertools import chain\n+from io import BytesIO\n import pickle\n import math\n import sys\n@@ -19,9 +20,10 @@\n from pydicom.data import get_testdata_file\n from pydicom.dataset import Dataset\n from pydicom._dicom_dict import DicomDictionary, RepeatersDictionary\n+from pydicom.filereader import read_dataset\n from pydicom.tag import Tag\n from pydicom.valuerep import (\n- DS, IS, DSfloat, DSdecimal, PersonName, VR, STANDARD_VR,\n+ DS, IS, DSfloat, DSdecimal, ISfloat, PersonName, VR, STANDARD_VR,\n AMBIGUOUS_VR, STR_VR, BYTES_VR, FLOAT_VR, INT_VR, LIST_VR\n )\n from pydicom.values import convert_value\n@@ -889,11 +891,31 @@ def test_valid_value(self, disable_value_validation):\n assert 42 == IS(\"42.0\")\n assert 42 == IS(42.0)\n \n+ def test_float_value(self):\n+ \"\"\"Read binary value of IS that is actually a float\"\"\"\n+ # from issue #1661\n+ # Create BytesIO with single data element for Exposure (0018,1152)\n+ # length 4, value \"14.5\"\n+ bin_elem = b\"\\x18\\x00\\x52\\x11\\x04\\x00\\x00\\x0014.5\"\n+ with BytesIO(bin_elem) as bio:\n+ ds = read_dataset(bio, True, True)\n+ assert isinstance(ds.Exposure, ISfloat)\n+ assert ds.Exposure == 14.5\n+\n+ # Strict checking raises an error\n+ with pytest.raises(ValueError):\n+ _ = IS(\"14.5\", validation_mode=config.RAISE)\n+ with pytest.raises(TypeError):\n+ _ = IS(14.5, validation_mode=config.RAISE)\n+\n+ def test_float_init(self):\n+ \"\"\"New ISfloat created from another behaves correctly\"\"\"\n+ is1 = IS(\"14.5\", validation_mode=config.IGNORE)\n+ is2 = IS(is1)\n+ assert is1 == is2\n+ assert is2.original_string == is1.original_string\n+\n def test_invalid_value(self, disable_value_validation):\n- with pytest.raises(TypeError, match=\"Could not convert value\"):\n- IS(0.9)\n- with pytest.raises(TypeError, match=\"Could not convert value\"):\n- IS(\"0.9\")\n with pytest.raises(ValueError, match=\"could not convert string\"):\n IS(\"foo\")\n \n", "problem_statement": "Strict adherence to VR during parsing is detrimental due to commonplace vendor interpretations\n**Describe the bug**\r\nDICOM Files from GE modalities, which when parsed, raise a TypeError caused by \"violating\" the VR imposed by the DICOM standard; however, real world modalities have and continue to generate such files for good cause.\r\n\r\nFor example the following is raised\r\n\r\n`TypeError('Could not convert value to integer without loss')`\r\n\r\nby a real world DICOM file which has a value\r\n\r\n`(0018,1152) IS [14.5] # 4, 1 Exposure`\r\n\r\nwhere IS is a Value Representation defined as\r\n\r\n> IS - Integer String\r\n\r\n> A string of characters representing an Integer in base-10 (decimal), shall contain only the characters 0 - 9, with an optional leading \"+\" or \"-\". It may be padded with leading and/or trailing spaces. Embedded spaces are not allowed.\r\n\r\n> The integer, n, represented shall be in the range: -231<= n <= (231-1).\r\n\r\n[See DICOM Part 5 Section 6.2](https://dicom.nema.org/dicom/2013/output/chtml/part05/sect_6.2.html)\r\n\r\nwhich means `14.5` is an invalid value due to the fractional portion .5 which definitely would lead to a loss in precision if converted to a pure integer value (of 14). \r\n\r\nAfter discussion with a senior engineer for the vendor, the following dialogue was obtained which quotes an article by David Clune, a well-respected, long-time member of the DICOM committee and community:\r\n\r\n> The tag pair in question is meant to contain the mAs value used for the exposure, which is not constrained to integer values, but for some reason the DICOM standard defines it as such.\r\n\r\n> An interesting article from someone responsible for maintaining the DICOM documentation explains the conundrum quite well: \r\n\r\nhttp://dclunie.blogspot.com/2008/11/dicom-exposure-attribute-fiasco.html\r\n\r\n> Of note are two excerpts from that article:\r\n\r\n> \"The original ACR-NEMA standard specified ASCII numeric data elements for Exposure, Exposure Time and X-Ray Tube Current that could be decimal values; for no apparent reason DICOM 3.0 in 1993 constrained these to be integers, which for some modalities and subjects are too small to be sufficiently precise\"\r\n\r\n> and\r\n\r\n> \"The authors of DICOM, in attempting to maintain some semblance of backward compatibility with ACR-NEMA and at the same time apply more precise constraints, re-defined all ACR-NEMA data elements of VR AN as either IS or DS, the former being the AN integer numbers (with new size constraints), and the latter being the AN fixed point and floating point numbers. In the process of categorizing the old data elements into either IS or DS, not only were the obvious integers (like counts of images and other things) made into integers, but it appears that also any \"real world\" attribute that in somebody's expert opinion did not need greater precision than a whole integer, was so constrained as well.\"\r\n\r\n> I have inspected a few random DICOM files generated by various modalities and the value is stored accurately, even though it is a violation of the explicit value representation. Additionally, I have worked with (and support) various PACS platforms, and this is the first time this has been raised as an issue. So technically, you are correct that encoding that value as decimal violates the explicit VR, but it appears to be common practice to do so. \r\n\r\n**Expected behavior**\r\nTo deal with the reality of history with respect to the current standard, my opinion, as a long-standing DICOM PACS implementer at Medstrat, is that there is nothing to gain and everything to lose by raising a `TypeError` here. For cases where an integer VR, such as `IS`, could be read as a floating point number instead, then it should be allowed to be so, for at least a limited whitelist of tags.\r\n\r\nArguments against which come to mind are of the ilk that do not heed \"Although practicality beats purity\" as can be read if you \r\n\r\n[`>>> import this`](https://peps.python.org/pep-0020/)\r\n\r\n> Special cases aren't special enough to break the rules.\r\n> Although practicality beats purity.\r\n\r\n**Steps To Reproduce**\r\n\r\n`(0018,1152) IS [14.5] # 4, 1 Exposure`\r\n\r\nSet any DICOM file to have the above for `Exposure` and then do this:\r\n\r\n```\r\n>>> from pydicom import config\r\n>>> pydicom.__version__\r\n'2.3.0'\r\n>>> config.settings.reading_validation_mode = config.IGNORE\r\n>>> ds = pydicom.dcmread('1.2.840.113619.2.107.20220429121335.1.1.dcm')\r\n>>> ds\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/dataset.py\", line 2306, in __str__\r\n return self._pretty_str()\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/dataset.py\", line 2020, in _pretty_str\r\n for elem in self:\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/dataset.py\", line 1240, in __iter__\r\n yield self[tag]\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/dataset.py\", line 939, in __getitem__\r\n self[tag] = DataElement_from_raw(elem, character_set, self)\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/dataelem.py\", line 859, in DataElement_from_raw\r\n value = convert_value(vr, raw, encoding)\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/values.py\", line 771, in convert_value\r\n return converter(byte_string, is_little_endian, num_format)\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/values.py\", line 348, in convert_IS_string\r\n return MultiString(num_string, valtype=pydicom.valuerep.IS)\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/valuerep.py\", line 1213, in MultiString\r\n return valtype(splitup[0])\r\n File \"/usr/local/lib/python3.7/site-packages/pydicom/valuerep.py\", line 1131, in __new__\r\n raise TypeError(\"Could not convert value to integer without loss\")\r\nTypeError: Could not convert value to integer without loss\r\n```\r\n\r\n**Your environment**\r\n\r\n```bash\r\nmodule | version\r\n------ | -------\r\nplatform | Darwin-21.5.0-x86_64-i386-64bit\r\nPython | 3.7.5 (v3.7.5:5c02a39a0b, Oct 14 2019, 18:49:57) [Clang 6.0 (clang-600.0.57)]\r\npydicom | 2.2.2\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | _module not found_\r\nPIL | _module not found_\r\npylibjpeg | _module not found_\r\nopenjpeg | _module not found_\r\nlibjpeg | _module not found_\r\n```\r\n\n", "hints_text": "Thank you for that thorough explanation (and of course we all know and respect David Clunie \ud83d\ude04 )!\r\nI understand the specific problem with `Exposure Time` (for a similar reason, there exists the tag `Exposure in \u03bcAs` additionally to `Exposure`, but no such thing exists for `Exposure Time`), and I am aware that this is not the only case where float values are written into `IS`. \r\n\r\nI think a similar issue came up before, and my preference would be to make this behavior dependent on the validation mode. The default validation mode for reading is to issue a warning, while for writing new data it is to raise an exception. This would not resolve the problem, though. The real problem is in the implementation of the tag class: the class representing `IS` values is derived from `int`. In my opinion, it would make sense to change that, though I'm not sure if we can do this consistently in a backwards-compatible way.\r\n\r\n@darcymason - I'm quite sure that we have discussed this before, I will try to find the respective issue. Anyway, what are your current thoughts here? \r\n\r\nCC @dclunie\r\n\nAh ok, @gsmethells has already [commented](https://github.com/pydicom/pydicom/issues/1643#issuecomment-1180789608) in the respective issue #1643.\n> I'm quite sure that we have discussed this before\r\n\r\nYes, it has come up several times.\r\n\r\nA new thought has come to me (maybe not thought through properly, or maybe someone has mentioned this before and I'm just thinking it is new): maybe we could create an ISFloat class, operating similarly to the DSFloat idea. Then, just have an allow_IS_float config flag, perhaps even true by default (return an ISFloat only if it is not an exact int). Python allows mixed math anyway, so I don't see any real problem in returning a non-int if further math is done. Only problem might be code that did an `isinstance` check against `IS` but that should be very rare.\n> maybe we could create an ISFloat class, operating similarly to the DSFloat idea\r\n\r\nMy preference would be to change the `IS` class to support both `int` and `float`. We cannot always use float, as that could decrease the precision of integers, but in the case that float numbers are written in the tag, I would prefer to return a float. Not sure what problems this would bring, though... \r\nAdditionally, I think we can still couple the behavior to the validation mode, but I'm not completely sure here.\n> My preference would be to change the `IS` class to support both `int` and `float`.\r\n\r\nIs that actually possible to do, without recreating all the class methods for `int` (or `float`) for math operations?\n> Is that actually possible to do, without recreating all the class methods for int (or float) for math operations?\r\n\r\nI guess not - that would be the downside of that approach. Also an `isinstance(int)` would fail, of course. It is probably better to use `ISFloat` as you proposed and dynamically decide which class to use.\n> It is probably better to use ISFloat as you proposed and dynamically decide which class to use.\r\n\r\nActually that is what you have proposed - sorry, I misread that, I understood that you wanted to configure which class to use. Yes, I like your proposal!\n> Is that actually possible to do, without recreating all the class methods for int (or float) for math operations?\r\n\r\nActually, I feel like we did return a different class from `__new__` somewhere, or at least talked about it. It turns out that it is possible to [return a different class from `__new__`](https://stackoverflow.com/questions/20221858/python-new-method-returning-something-other-than-class-instance). I'm not sure it is advisable, though, that is really not being explicit to the user.\n> Actually, I feel like we did return a different class from `__new__` somewhere\r\n\r\nYes, we actually use this to return either a string or an int/float from `IS`/`DS`. This is also a common pattern in Python (they use it for example in `pathlib`), so I think it would not be unexpected.\nThank you for taking the time to discuss ideas and consider this. I understand wanting to adhere tightly to the standard (we do so for edge cases the majority of the time ourselves for our ortho PACS). I also understand the desire to listen to the \"import this\" zen of \"Simple is better than complex\" and, yes, I understand all too well how a large system can grow complicated.\r\n\r\nMy usual pause comes when my design desires run up against DICOM files in the field where there is a common violation of the standard. We maintain petabytes of DICOM images and this issue is common. I would be happy if reading/writing `dataset`s from/to files via pydicom continued to support maintaining existing values, regardless of whether those values violate the standard, (it does now, but is that an intentional design decision? A `dataset` only raises a `TypeError` when the value is directly attempted to be read out, whether via `__iter__` or otherwise) and also provided a (new/existing?) preference for reading `int` VR tag values as `float`.\r\n\r\nMy two cents.\n> reading/writing `dataset`s from/to files via pydicom continued to support maintaining existing values, regardless of whether those values violate the standard\r\n\r\nAny other position would become a deal breaker for our use of the library if it were ever otherwise, simply due to the realities of supporting customers. Especially when it comes to the need to update tags (e.g., a misspelled PatientName) while keeping other unrelated tags the same (i.e., no side-effects).\nSetting 2.4 milestone to at least consider this for the release.", "created_at": "2022-10-26T19:54:28Z", "version": "2.3", "FAIL_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestDataSetToJson::test_suppress_invalid_tags", "pydicom/tests/test_json.py::TestDataSetToJson::test_suppress_invalid_tags_with_failed_dataelement", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_2", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_within_SQ", "pydicom/tests/test_json.py::TestNumeric::test_numeric_values", "pydicom/tests/test_json.py::TestNumeric::test_numeric_types", "pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestTM::test_pickling_tm_from_time", "pydicom/tests/test_valuerep.py::TestTM::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestTM::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_comparison", "pydicom/tests/test_valuerep.py::TestTM::test_time_behavior", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDT::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDT::test_comparison", "pydicom/tests/test_valuerep.py::TestDT::test_datetime_behavior", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDA::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDA::test_comparison", "pydicom/tests/test_valuerep.py::TestDA::test_date_behavior", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[3.14159265358979]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[-1234.456e78]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E-5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E+5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[+1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[42", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[nan]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[3.141592653589793]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1,000]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[127.0.0.1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1.e]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.0-1.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.0-0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.0--0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.123-0.123]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.321--0.321]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1e-05-1e-05]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[3.141592653589793-3.14159265358979]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-3.141592653589793--3.1415926535898]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[5.385940192876374e-07-5.3859401929e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-5.385940192876374e-07--5.385940193e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[12342534378.125532-12342534378.1255]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[64070869985876.78-64070869985876.8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.7976931348623157e+308-1.797693135e+308]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_wrong_type", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_new_empty[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_new_empty[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str_value[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str_value[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_length", "pydicom/tests/test_valuerep.py::TestDSfloat::test_handle_missing_leading_zero", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat_auto_format", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-nan]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan2]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSfloat::test_hash", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_new_empty", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_str_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_repr", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_string_too_long", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_string_too_long_raises", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val4]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val5]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val6]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val7]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal_auto_format", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_hash", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_str_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_float_value", "pydicom/tests/test_valuerep.py::TestIS::test_float_init", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestIS::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestIS::test_hash", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_no_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains", "pydicom/tests/test_valuerep.py::TestPersonName::test_length", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_veterinary", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator_from_bytes", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time", "pydicom/tests/test_valuerep.py::test_person_name_unicode_warns", "pydicom/tests/test_valuerep.py::test_set_value[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_set_value[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_set_value[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_set_value[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_set_value[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_set_value[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_set_value[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_set_value[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_set_value[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_set_value[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_set_value[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_set_value[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_set_value[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_set_value[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[OV-bytes-vm020-vmN20-SelectorOVValue]", "pydicom/tests/test_valuerep.py::test_set_value[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_set_value[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_set_value[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_set_value[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_set_value[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_set_value[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_set_value[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_set_value[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_set_value[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_set_value[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_set_value[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_set_value[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_set_value[UV-int-vm037-vmN37-SelectorUVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OV-bytes-vm020-vmN20-SelectorOVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UV-int-vm037-vmN37-SelectorUVValue]", "pydicom/tests/test_valuerep.py::TestVR::test_behavior", "pydicom/tests/test_valuerep.py::TestVR::test_all_present"], "PASS_TO_PASS": [], "environment_setup_commit": "a8be738418dee0a2b93c241fbd5e0bc82f4b8680"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-816", "base_commit": "3551f5b5a5f8d4de3ed92e5e479ac8c74a8c893a", "patch": "diff --git a/pydicom/charset.py b/pydicom/charset.py\n--- a/pydicom/charset.py\n+++ b/pydicom/charset.py\n@@ -125,15 +125,24 @@ def decode_string(value, encodings, delimiters):\n \"\"\"\n # shortcut for the common case - no escape sequences present\n if ESC not in value:\n+ first_encoding = encodings[0]\n try:\n- return value.decode(encodings[0])\n+ return value.decode(first_encoding)\n+ except LookupError:\n+ if config.enforce_valid_values:\n+ raise\n+ warnings.warn(u\"Unknown encoding '{}' - \"\n+ u\"using default encoding instead\"\n+ .format(first_encoding))\n+ first_encoding = default_encoding\n+ return value.decode(first_encoding)\n except UnicodeError:\n if config.enforce_valid_values:\n raise\n- warnings.warn(u\"Failed to decode byte string with encoding {} - \"\n+ warnings.warn(u\"Failed to decode byte string with encoding '{}' - \"\n u\"using replacement characters in decoded \"\n- u\"string\".format(encodings[0]))\n- return value.decode(encodings[0], errors='replace')\n+ u\"string\".format(first_encoding))\n+ return value.decode(first_encoding, errors='replace')\n \n # Each part of the value that starts with an escape sequence is decoded\n # separately. If it starts with an escape sequence, the\n", "test_patch": "diff --git a/pydicom/tests/test_charset.py b/pydicom/tests/test_charset.py\n--- a/pydicom/tests/test_charset.py\n+++ b/pydicom/tests/test_charset.py\n@@ -100,6 +100,26 @@ def test_standard_file(self):\n ds.decode()\n assert u'CompressedSamples^CT1' == ds.PatientName\n \n+ def test_invalid_character_set(self):\n+ \"\"\"charset: replace invalid encoding with default encoding\"\"\"\n+ ds = dcmread(get_testdata_files(\"CT_small.dcm\")[0])\n+ ds.read_encoding = None\n+ ds.SpecificCharacterSet = 'Unsupported'\n+ with pytest.warns(UserWarning,\n+ match=u\"Unknown encoding 'Unsupported' \"\n+ u\"- using default encoding instead\"):\n+ ds.decode()\n+ assert u'CompressedSamples^CT1' == ds.PatientName\n+\n+ def test_invalid_character_set_enforce_valid(self):\n+ \"\"\"charset: raise on invalid encoding\"\"\"\n+ config.enforce_valid_values = True\n+ ds = dcmread(get_testdata_files(\"CT_small.dcm\")[0])\n+ ds.read_encoding = None\n+ ds.SpecificCharacterSet = 'Unsupported'\n+ with pytest.raises(LookupError, match='unknown encoding: Unsupported'):\n+ ds.decode()\n+\n def test_decoding_with_specific_tags(self):\n \"\"\"Decoding is correctly applied even if Specific Character Set\n is not in specific tags...\"\"\"\n@@ -126,8 +146,8 @@ def test_bad_encoded_single_encoding(self):\n elem = DataElement(0x00100010, 'PN',\n b'\\xc4\\xe9\\xef\\xed\\xf5\\xf3\\xe9\\xef\\xf2')\n \n- with pytest.warns(UserWarning, match='Failed to decode byte string '\n- 'with encoding UTF8'):\n+ with pytest.warns(UserWarning, match=\"Failed to decode byte string \"\n+ \"with encoding 'UTF8'\"):\n pydicom.charset.decode(elem, ['ISO_IR 192'])\n assert u'\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd' == elem.value\n \n@@ -235,9 +255,11 @@ def test_patched_charset(self):\n # make sure no warning is issued for the correct value\n assert 1 == len(w)\n \n- # not patched incorrect encoding raises\n+ # not patched incorrect encoding is replaced by default encoding\n elem = DataElement(0x00100010, 'PN', b'Buc^J\\xc3\\xa9r\\xc3\\xb4me')\n- with pytest.raises(LookupError):\n+ with pytest.warns(UserWarning,\n+ match=u\"Unknown encoding 'ISOIR 192' - \"\n+ u\"using default encoding instead\"):\n pydicom.charset.decode(elem, ['ISOIR 192'])\n \n # Python encoding also can be used directly\n", "problem_statement": "LookupError: unknown encoding: Not Supplied\n#### Description\r\nOutput from `ds = pydicom.read_file(dcmFile)` (an RTSTRUCT dicom file, SOP UID 1.2.840.10008.5.1.4.1.1.481.3) results in some tags throwing a LookupError: \"LookupError: unknown encoding: Not Supplied\"\r\nSpecific tags which cannot be decoded are as follows:\r\n['DeviceSerialNumber',\r\n 'Manufacturer',\r\n 'ManufacturerModelName',\r\n 'PatientID',\r\n 'PatientName',\r\n 'RTROIObservationsSequence',\r\n 'ReferringPhysicianName',\r\n 'SeriesDescription',\r\n 'SoftwareVersions',\r\n 'StructureSetLabel',\r\n 'StructureSetName',\r\n 'StructureSetROISequence',\r\n 'StudyDescription',\r\n 'StudyID']\r\n\r\nI suspect that it's due to the fact that `ds.SpecificCharacterSet = 'Not Supplied'`, but when I try to set `ds.SpecificCharacterSet` to something reasonable (ie ISO_IR_100 or 'iso8859'), it doesn't seem to make any difference.\r\n\r\nReading the same file, with NO modifications, in gdcm does not result in any errors and all fields are readable.\r\n\r\n#### Steps/Code to Reproduce\r\n```py\r\nimport pydicom \r\nds = pydicom.read_file(dcmFile)\r\nprint(ds.PatientName)\r\n```\r\n\r\n#### Expected Results\r\nNo error is thrown and the name of the patient is printed.\r\n\r\n#### Actual Results\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"C:\\Users\\Amanda\\AppData\\Local\\Continuum\\anaconda3\\envs\\itk\\lib\\site-packages\\pydicom\\valuerep.py\", line 706, in __str__\r\n return '='.join(self.components).__str__()\r\n File \"C:\\Users\\Amanda\\AppData\\Local\\Continuum\\anaconda3\\envs\\itk\\lib\\site-packages\\pydicom\\valuerep.py\", line 641, in components\r\n self._components = _decode_personname(groups, self.encodings)\r\n File \"C:\\Users\\Amanda\\AppData\\Local\\Continuum\\anaconda3\\envs\\itk\\lib\\site-packages\\pydicom\\valuerep.py\", line 564, in _decode_personname\r\n for comp in components]\r\n File \"C:\\Users\\Amanda\\AppData\\Local\\Continuum\\anaconda3\\envs\\itk\\lib\\site-packages\\pydicom\\valuerep.py\", line 564, in <listcomp>\r\n for comp in components]\r\n File \"C:\\Users\\Amanda\\AppData\\Local\\Continuum\\anaconda3\\envs\\itk\\lib\\site-packages\\pydicom\\charset.py\", line 129, in decode_string\r\n return value.decode(encodings[0])\r\nLookupError: unknown encoding: Not Supplied\r\n\r\n#### Versions\r\nPlatform: Windows-10-10.0.17763-SP0\r\nPython Version: Python 3.6.4 |Anaconda, Inc.| (default, Mar 12 2018, 20:20:50) [MSC v.1900 64 bit (AMD64)]\r\npydicom Version: pydicom 1.2.2\r\n\n", "hints_text": "You said on the pynetdicom issue you can't upload an anonymised file, but can you open the file in a hex editor and post the raw byte output from the first few (non-identifying) elements? From the start of the file to the end of say (0008,0070) should be enough.\r\n\r\nAlternatively you could truncate the file at the end of the (0008,0070) element and upload that.\r\n\r\nIf you need to know how to interpret the encoded data check out [Part 5, Chapter 7](http://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html) of the DICOM Standard. And if the file's been saved in the [DICOM File Format](http://dicom.nema.org/medical/dicom/current/output/chtml/part10/chapter_7.html) there may also be a 128 byte header following by 'DICM' before the start of the dataset (which we don't need).\n> open the file in a hex editor and post the raw byte output from the first few (non-identifying) elements\r\n\r\nAlternatively:\r\n```\r\nimport pydicom.config\r\npydicom.config.debug(True)\r\nds = dcmread(youfilename)\r\n```\r\nAnd as suggested copy the first non-identifying part of the debug output for posting.\nPlease find the truncated dataset attached as requested. I wasn't allowed to upload a *.dcm file so just wrote it as a *.txt file. The file is readable by pydicom but exhibits the same aforementioned problems, where the \"LookupError: unknown encoding: Not Supplied\" happens only for the Manufacturer tag.\r\n\r\n[truncated.txt](https://github.com/pydicom/pydicom/files/2947883/truncated.txt)\r\n\nOkay, so I've tried deleting SpecificCharacterSet and the error still occurs. I think pydicom is still holding on to the original values, and needs some code to handle the case when SpecificCharacterSet is deleted or set again after reading the file. We can dig into it a little further.\r\n\r\n\nWorkaround:\r\n```python\r\nfrom pydicom import dcmread\r\n\r\nds = dcmread('path/to/file')\r\ndel ds.SpecificCharacterSet\r\nds.read_encoding = []\r\n```\r\n\nBrilliant! That worked! \r\n\r\nThank you for the quick fix! I've found pydicom is a lot more user-friendly than gdcm so I'm really glad I don't have to resort to that. \ud83d\ude00 \nNo problem, @mrbean-bremen do you want to handle the underlying issue?\nCertainly - as I may have introduced it... Not sure if I'll find the time today though. ", "created_at": "2019-03-10T15:41:44Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding", "pydicom/tests/test_charset.py::TestCharset::test_patched_charset"], "PASS_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_encodings", "pydicom/tests/test_charset.py::TestCharset::test_nested_character_sets", "pydicom/tests/test_charset.py::TestCharset::test_inherited_character_set_in_sequence", "pydicom/tests/test_charset.py::TestCharset::test_standard_file", "pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set_enforce_valid", "pydicom/tests/test_charset.py::TestCharset::test_decoding_with_specific_tags", "pydicom/tests/test_charset.py::TestCharset::test_bad_charset", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_code_extensions_not_allowed", "pydicom/tests/test_charset.py::TestCharset::test_convert_encodings_warnings", "pydicom/tests/test_charset.py::TestCharset::test_convert_python_encodings", "pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_patched_code_extension_charset", "pydicom/tests/test_charset.py::TestCharset::test_multi_charset_default_value", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_personname", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_text", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_code_extensions[ISO", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrArab-\\u0642\\u0628\\u0627\\u0646\\u064a^\\u0644\\u0646\\u0632\\u0627\\u0631]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFren-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFrenMulti-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGerm-\\xc4neas^R\\xfcdiger]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGreek-\\u0394\\u03b9\\u03bf\\u03bd\\u03c5\\u03c3\\u03b9\\u03bf\\u03c2]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH31-Yamada^Tarou=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH32-\\uff94\\uff8f\\uff80\\uff9e^\\uff80\\uff9b\\uff73=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrHbrw-\\u05e9\\u05e8\\u05d5\\u05df^\\u05d3\\u05d1\\u05d5\\u05e8\\u05d4]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrI2-Hong^Gildong=\\u6d2a^\\u5409\\u6d1e=\\ud64d^\\uae38\\ub3d9]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMulti-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMultiExplicitIR6-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrKoreanMulti-\\uae40\\ud76c\\uc911]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrRuss-\\u041b\\u044e\\u043ace\\u043c\\u0431yp\\u0433]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX1-Wang^XiaoDong=\\u738b^\\u5c0f\\u6771]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX2-Wang^XiaoDong=\\u738b^\\u5c0f\\u4e1c]", "pydicom/tests/test_charset.py::TestCharset::test_changed_character_set"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-916", "base_commit": "a94cc9996d2c716298c846f2dbba84f9f901e0a7", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -329,41 +329,60 @@ def from_json(cls, dataset_class, tag, vr, value, value_key,\n # Some DICOMweb services get this wrong, so we\n # workaround the issue and warn the user\n # rather than raising an error.\n- logger.error(\n+ logger.warning(\n 'value of data element \"{}\" with VR Person Name (PN) '\n 'is not formatted correctly'.format(tag)\n )\n elem_value.append(v)\n else:\n- elem_value.extend(list(v.values()))\n- if vm == '1':\n+ if 'Phonetic' in v:\n+ comps = ['', '', '']\n+ elif 'Ideographic' in v:\n+ comps = ['', '']\n+ else:\n+ comps = ['']\n+ if 'Alphabetic' in v:\n+ comps[0] = v['Alphabetic']\n+ if 'Ideographic' in v:\n+ comps[1] = v['Ideographic']\n+ if 'Phonetic' in v:\n+ comps[2] = v['Phonetic']\n+ elem_value.append('='.join(comps))\n+ if len(elem_value) == 1:\n+ elem_value = elem_value[0]\n+ elif not elem_value:\n+ elem_value = empty_value_for_VR(vr)\n+ elif vr == 'AT':\n+ elem_value = []\n+ for v in value:\n try:\n- elem_value = elem_value[0]\n- except IndexError:\n- elem_value = ''\n+ elem_value.append(int(v, 16))\n+ except ValueError:\n+ warnings.warn('Invalid value \"{}\" for AT element - '\n+ 'ignoring it'.format(v))\n+ value = value[0]\n+ if not elem_value:\n+ elem_value = empty_value_for_VR(vr)\n+ elif len(elem_value) == 1:\n+ elem_value = elem_value[0]\n else:\n- if vm == '1':\n- if value_key == 'InlineBinary':\n- elem_value = base64.b64decode(value)\n- elif value_key == 'BulkDataURI':\n- if bulk_data_uri_handler is None:\n- logger.warning(\n- 'no bulk data URI handler provided for retrieval '\n- 'of value of data element \"{}\"'.format(tag)\n- )\n- elem_value = b''\n- else:\n- elem_value = bulk_data_uri_handler(value)\n+ if isinstance(value, list) and len(value) == 1:\n+ value = value[0]\n+ if value_key == 'InlineBinary':\n+ elem_value = base64.b64decode(value)\n+ elif value_key == 'BulkDataURI':\n+ if bulk_data_uri_handler is None:\n+ logger.warning(\n+ 'no bulk data URI handler provided for retrieval '\n+ 'of value of data element \"{}\"'.format(tag)\n+ )\n+ elem_value = empty_value_for_VR(vr, raw=True)\n else:\n- if value:\n- elem_value = value[0]\n- else:\n- elem_value = value\n+ elem_value = bulk_data_uri_handler(value)\n else:\n elem_value = value\n if elem_value is None:\n- logger.warning('missing value for data element \"{}\"'.format(tag))\n- elem_value = ''\n+ elem_value = empty_value_for_VR(vr)\n \n elem_value = jsonrep.convert_to_python_number(elem_value, vr)\n \n@@ -404,11 +423,9 @@ def to_json(self, bulk_data_element_handler,\n but `bulk_data_element_handler` is ``None`` and hence not callable\n \n \"\"\"\n- # TODO: Determine whether more VRs need to be converted to strings\n- _VRs_TO_QUOTE = ['AT', ]\n json_element = {'vr': self.VR, }\n if self.VR in jsonrep.BINARY_VR_VALUES:\n- if self.value is not None:\n+ if not self.is_empty:\n binary_value = self.value\n encoded_value = base64.b64encode(binary_value).decode('utf-8')\n if len(encoded_value) > bulk_data_threshold:\n@@ -440,35 +457,35 @@ def to_json(self, bulk_data_element_handler,\n ]\n json_element['Value'] = value\n elif self.VR == 'PN':\n- elem_value = self.value\n- if elem_value is not None:\n- if compat.in_py2:\n- elem_value = PersonNameUnicode(elem_value, 'UTF8')\n- if len(elem_value.components) > 2:\n- json_element['Value'] = [\n- {'Phonetic': elem_value.components[2], },\n- ]\n- elif len(elem_value.components) > 1:\n- json_element['Value'] = [\n- {'Ideographic': elem_value.components[1], },\n- ]\n+ if not self.is_empty:\n+ elem_value = []\n+ if self.VM > 1:\n+ value = self.value\n else:\n- json_element['Value'] = [\n- {'Alphabetic': elem_value.components[0], },\n- ]\n+ value = [self.value]\n+ for v in value:\n+ if compat.in_py2:\n+ v = PersonNameUnicode(v, 'UTF8')\n+ comps = {'Alphabetic': v.components[0]}\n+ if len(v.components) > 1:\n+ comps['Ideographic'] = v.components[1]\n+ if len(v.components) > 2:\n+ comps['Phonetic'] = v.components[2]\n+ elem_value.append(comps)\n+ json_element['Value'] = elem_value\n+ elif self.VR == 'AT':\n+ if not self.is_empty:\n+ value = self.value\n+ if self.VM == 1:\n+ value = [value]\n+ json_element['Value'] = [format(v, '08X') for v in value]\n else:\n- if self.value is not None:\n- is_multivalue = isinstance(self.value, MultiValue)\n- if self.VM > 1 or is_multivalue:\n+ if not self.is_empty:\n+ if self.VM > 1:\n value = self.value\n else:\n value = [self.value]\n- # ensure it's a list and not another iterable\n- # (e.g. tuple), which would not be JSON serializable\n- if self.VR in _VRs_TO_QUOTE:\n- json_element['Value'] = [str(v) for v in value]\n- else:\n- json_element['Value'] = [v for v in value]\n+ json_element['Value'] = [v for v in value]\n if hasattr(json_element, 'Value'):\n json_element['Value'] = jsonrep.convert_to_python_number(\n json_element['Value'], self.VR\ndiff --git a/pydicom/jsonrep.py b/pydicom/jsonrep.py\n--- a/pydicom/jsonrep.py\n+++ b/pydicom/jsonrep.py\n@@ -2,6 +2,8 @@\n \"\"\"Methods for converting Datasets and DataElements to/from json\"\"\"\n \n # Order of keys is significant!\n+from pydicom.compat import int_type\n+\n JSON_VALUE_KEYS = ('Value', 'BulkDataURI', 'InlineBinary',)\n \n BINARY_VR_VALUES = ['OW', 'OB', 'OD', 'OF', 'OL', 'UN',\n@@ -30,7 +32,7 @@ def convert_to_python_number(value, vr):\n return None\n number_type = None\n if vr in VRs_TO_BE_INTS:\n- number_type = int\n+ number_type = int_type\n if vr in VRs_TO_BE_FLOATS:\n number_type = float\n if number_type is not None:\ndiff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -646,9 +646,13 @@ def __init__(self, val, encodings=None, original_string=None):\n # this is the decoded string - save the original string if\n # available for easier writing back\n self.original_string = original_string\n- self._components = tuple(val.split('='))\n+ components = val.split('=')\n+ # Remove empty elements from the end to avoid trailing '='\n+ while len(components) and not components[-1]:\n+ components.pop()\n+ self._components = tuple(components)\n \n- # if the encoding is not given, leave it as undefined (None)\n+ # if the encoding is not given, leave it as undefined (None)\n self.encodings = _verify_encodings(encodings)\n self._dict = {}\n \n@@ -812,7 +816,7 @@ def formatted(self, format_str):\n \n def __bool__(self):\n if self.original_string is None:\n- return (self._components is not None and\n+ return (bool(self._components) and\n (len(self._components) > 1 or bool(self._components[0])))\n return bool(self.original_string)\n \n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -1,89 +1,226 @@\n # -*- coding: utf-8 -*-\n # Copyright 2008-2019 pydicom authors. See LICENSE file for details.\n+import json\n+\n import pytest\n+\n+from pydicom import dcmread, compat\n from pydicom.data import get_testdata_files\n from pydicom.dataelem import DataElement\n from pydicom.dataset import Dataset\n-from pydicom import compat\n-\n+from pydicom.tag import Tag, BaseTag\n from pydicom.valuerep import PersonNameUnicode, PersonName3\n \n \n-def test_json_PN():\n- s = open(get_testdata_files(\"test_PN.json\")[0], \"r\").read()\n- ds = Dataset.from_json(s)\n- assert isinstance(ds[0x00080090].value,\n- (PersonNameUnicode, PersonName3))\n- assert isinstance(ds[0x00100010].value,\n- (PersonNameUnicode, PersonName3))\n- inner_seq = ds[0x04000561].value[0][0x04000550]\n- dataelem = inner_seq[0][0x00100010]\n- assert isinstance(dataelem.value, (PersonNameUnicode, PersonName3))\n-\n-\[email protected](compat.in_py2,\n- reason='JSON conversion not yet working in Python 2')\n-def test_dataelem_from_json():\n- tag = 0x0080090\n- vr = \"PN\"\n- value = [{\"Alphabetic\": \"\"}]\n- dataelem = DataElement.from_json(Dataset, tag, vr, value, \"Value\")\n- assert isinstance(dataelem.value, (PersonNameUnicode, PersonName3))\n-\n-\n-def test_json_roundtrip():\n- ds = Dataset()\n- ds.add_new(0x00080005, 'CS', 'ISO_IR 100')\n- ds.add_new(0x00090010, 'LO', 'Creator 1.0')\n- ds.add_new(0x00091001, 'SH', 'Version1')\n- ds.add_new(0x00091002, 'OB', b'BinaryContent')\n- ds.add_new(0x00091003, 'OW', b'\\x0102\\x3040\\x5060')\n- ds.add_new(0x00091004, 'OF', b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07')\n- ds.add_new(0x00091005, 'OD', b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'\n- b'\\x01\\x01\\x02\\x03\\x04\\x05\\x06\\x07')\n- ds.add_new(0x00091006, 'OL', b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'\n- b'\\x01\\x01\\x02\\x03')\n- ds.add_new(0x00091007, 'UI', '1.2.3.4.5.6')\n- ds.add_new(0x00091008, 'DA', '20200101')\n- ds.add_new(0x00091009, 'TM', '115500')\n- ds.add_new(0x0009100a, 'DT', '20200101115500.000000')\n- ds.add_new(0x0009100b, 'UL', 3000000000)\n- ds.add_new(0x0009100c, 'SL', -2000000000)\n- ds.add_new(0x0009100d, 'US', 40000)\n- ds.add_new(0x0009100e, 'SS', -22222)\n- ds.add_new(0x0009100f, 'FL', 3.14)\n- ds.add_new(0x00091010, 'FD', 3.14159265)\n- ds.add_new(0x00091011, 'CS', 'TEST MODE')\n- ds.add_new(0x00091012, 'PN', 'CITIZEN^1')\n- ds.add_new(0x00091013, 'PN', u'Yamada^Tarou=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046')\n- ds.add_new(0x00091014, 'IS', '42')\n- ds.add_new(0x00091015, 'DS', '3.14159265')\n- ds.add_new(0x00091016, 'AE', b'CONQUESTSRV1')\n- ds.add_new(0x00091017, 'AS', '055Y')\n- ds.add_new(0x00091018, 'LT', 50 * u'\u041a\u0430\u043b\u0438\u043d\u043a\u0430,')\n- ds.add_new(0x00091019, 'UC', 'LONG CODE VALUE')\n- ds.add_new(0x0009101a, 'UN', b'\\x0102\\x3040\\x5060')\n- ds.add_new(0x0009101b, 'UR', 'https://example.com')\n- ds.add_new(0x0009101c, 'AT', b'\\x10\\x00\\x20\\x00\\x10\\x00\\x30\\x00\\x10')\n- ds.add_new(0x0009101d, 'ST', 100 * u'\u0639\u0644\u064a \u0628\u0627\u0628\u0627')\n- ds.add_new(0x0009101e, 'SH', u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2')\n- ds.add_new(0x00090011, 'LO', 'Creator 2.0')\n- ds.add_new(0x00091101, 'SH', 'Version2')\n- ds.add_new(0x00091102, 'US', 2)\n-\n- jsonmodel = ds.to_json(bulk_data_threshold=100)\n- ds2 = Dataset.from_json(jsonmodel)\n-\n- assert ds2.SpecificCharacterSet == ['ISO_IR 100']\n-\n-\n-def test_json_private_DS_VM():\n- test1_json = get_testdata_files(\"test1.json\")[0]\n- jsonmodel = open(test1_json, 'r').read()\n- ds = Dataset.from_json(jsonmodel)\n- import json\n- jsonmodel2 = ds.to_json(dump_handler=lambda d: json.dumps(d, indent=2))\n- ds2 = Dataset.from_json(jsonmodel2)\n-\n- assert ds.PatientIdentityRemoved == 'YES'\n- assert ds2.PatientIdentityRemoved == 'YES'\n+class TestPersonName(object):\n+ def test_json_PN_from_file(self):\n+ with open(get_testdata_files(\"test_PN.json\")[0]) as s:\n+ ds = Dataset.from_json(s.read())\n+ assert isinstance(ds[0x00080090].value,\n+ (PersonNameUnicode, PersonName3))\n+ assert isinstance(ds[0x00100010].value,\n+ (PersonNameUnicode, PersonName3))\n+ inner_seq = ds[0x04000561].value[0][0x04000550]\n+ dataelem = inner_seq[0][0x00100010]\n+ assert isinstance(dataelem.value, (PersonNameUnicode, PersonName3))\n+\n+ def test_PN_components_to_json(self):\n+ def check_name(tag, components):\n+ # we cannot directly compare the dictionaries, as they are not\n+ # ordered in Python 2\n+ value = ds_json[tag]['Value']\n+ assert 1 == len(value)\n+ value = value[0]\n+ if len(components) == 3:\n+ assert components[2] == value['Phonetic']\n+ else:\n+ assert 'Phonetic' not in value\n+ if len(components) >= 2:\n+ assert components[1] == value['Ideographic']\n+ else:\n+ assert 'Ideographic' not in value\n+ assert components[0] == value['Alphabetic']\n+\n+ ds = Dataset()\n+ ds.add_new(0x00100010, 'PN', u'Yamada^Tarou=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046')\n+ ds.add_new(0x00091001, 'PN', u'Yamada^Tarou')\n+ ds.add_new(0x00091002, 'PN', u'Yamada^Tarou==')\n+ ds.add_new(0x00091003, 'PN', u'=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046')\n+ ds.add_new(0x00091004, 'PN', u'Yamada^Tarou==\u3084\u307e\u3060^\u305f\u308d\u3046')\n+ ds.add_new(0x00091005, 'PN', u'==\u3084\u307e\u3060^\u305f\u308d\u3046')\n+ ds.add_new(0x00091006, 'PN', u'=\u5c71\u7530^\u592a\u90ce')\n+ ds.add_new(0x00091007, 'PN', u'Yamada^Tarou=\u5c71\u7530^\u592a\u90ce')\n+ ds_json = json.loads(ds.to_json())\n+ check_name('00100010', ['Yamada^Tarou', u'\u5c71\u7530^\u592a\u90ce', u'\u3084\u307e\u3060^\u305f\u308d\u3046'])\n+ check_name('00091001', ['Yamada^Tarou'])\n+ check_name('00091002', ['Yamada^Tarou'])\n+ check_name('00091003', ['', u'\u5c71\u7530^\u592a\u90ce', u'\u3084\u307e\u3060^\u305f\u308d\u3046'])\n+ check_name('00091004', ['Yamada^Tarou', '', u'\u3084\u307e\u3060^\u305f\u308d\u3046'])\n+ check_name('00091005', ['', '', u'\u3084\u307e\u3060^\u305f\u308d\u3046'])\n+ check_name('00091006', ['', u'\u5c71\u7530^\u592a\u90ce'])\n+ check_name('00091007', ['Yamada^Tarou', u'\u5c71\u7530^\u592a\u90ce'])\n+\n+ def test_PN_components_from_json(self):\n+ # this is the encoded dataset from the previous test, with some\n+ # empty components omitted\n+ ds_json = (u'{\"00100010\": {\"vr\": \"PN\", \"Value\": [{\"Alphabetic\": '\n+ u'\"Yamada^Tarou\", \"Ideographic\": \"\u5c71\u7530^\u592a\u90ce\", '\n+ u'\"Phonetic\": \"\u3084\u307e\u3060^\u305f\u308d\u3046\"}]}, '\n+ u'\"00091001\": {\"vr\": \"PN\", \"Value\": '\n+ u'[{\"Alphabetic\": \"Yamada^Tarou\"}]}, '\n+ u'\"00091002\": {\"vr\": \"PN\", \"Value\": '\n+ u'[{\"Alphabetic\": \"Yamada^Tarou\", \"Ideographic\": \"\", '\n+ u'\"Phonetic\": \"\"}]}, '\n+ u'\"00091003\": {\"vr\": \"PN\", \"Value\": [{'\n+ u'\"Ideographic\": \"\u5c71\u7530^\u592a\u90ce\", '\n+ u'\"Phonetic\": \"\u3084\u307e\u3060^\u305f\u308d\u3046\"}]}, '\n+ u'\"00091004\": {\"vr\": \"PN\", \"Value\": '\n+ u'[{\"Alphabetic\": \"Yamada^Tarou\", '\n+ u'\"Phonetic\": \"\u3084\u307e\u3060^\u305f\u308d\u3046\"}]}, '\n+ u'\"00091005\": {\"vr\": \"PN\", \"Value\": '\n+ u'[{\"Phonetic\": \"\u3084\u307e\u3060^\u305f\u308d\u3046\"}]}, '\n+ u'\"00091006\": {\"vr\": \"PN\", \"Value\":'\n+ u' [{\"Ideographic\": \"\u5c71\u7530^\u592a\u90ce\"}]}, '\n+ u'\"00091007\": {\"vr\": \"PN\", \"Value\": '\n+ u'[{\"Alphabetic\": \"Yamada^Tarou\", '\n+ u'\"Ideographic\": \"\u5c71\u7530^\u592a\u90ce\"}]}}')\n+ if compat.in_py2:\n+ ds_json = ds_json.encode('UTF8')\n+\n+ ds = Dataset.from_json(ds_json)\n+ assert u'Yamada^Tarou=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046' == ds.PatientName\n+ assert u'Yamada^Tarou' == ds[0x00091001].value\n+ assert u'Yamada^Tarou' == ds[0x00091002].value\n+ assert u'=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046' == ds[0x00091003].value\n+ assert u'Yamada^Tarou==\u3084\u307e\u3060^\u305f\u308d\u3046' == ds[0x00091004].value\n+ assert u'==\u3084\u307e\u3060^\u305f\u308d\u3046' == ds[0x00091005].value\n+ assert u'=\u5c71\u7530^\u592a\u90ce' == ds[0x00091006].value\n+ assert u'Yamada^Tarou=\u5c71\u7530^\u592a\u90ce' == ds[0x00091007].value\n+\n+ def test_empty_value(self):\n+ ds = Dataset()\n+ ds.add_new(0x00100010, 'PN', '')\n+ ds_json = json.loads(ds.to_json())\n+ assert '00100010' in ds_json\n+ assert 'Value' not in ds_json['00100010']\n+\n+ def test_multi_value_to_json(self):\n+ ds = Dataset()\n+ patient_names = [u'Buc^J\u00e9r\u00f4me', u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2', u'\u041b\u044e\u043ace\u043c\u0431yp\u0433']\n+ ds.add_new(0x00091001, 'PN', patient_names)\n+ ds_json = json.loads(ds.to_json())\n+ assert [{'Alphabetic': u'Buc^J\u00e9r\u00f4me'},\n+ {'Alphabetic': u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2'},\n+ {'Alphabetic': u'\u041b\u044e\u043ace\u043c\u0431yp\u0433'}] == ds_json['00091001']['Value']\n+\n+ def test_dataelem_from_json(self):\n+ tag = 0x0080090\n+ vr = \"PN\"\n+ value = [{\"Alphabetic\": \"\"}]\n+ dataelem = DataElement.from_json(Dataset, tag, vr, value, \"Value\")\n+ assert isinstance(dataelem.value, (PersonNameUnicode, PersonName3))\n+\n+\n+class TestAT(object):\n+ def test_to_json(self):\n+ ds = Dataset()\n+ ds.add_new(0x00091001, 'AT', [0x00100010, 0x00100020])\n+ ds.add_new(0x00091002, 'AT', Tag(0x28, 0x02))\n+ ds.add_new(0x00091003, 'AT', BaseTag(0x00280002))\n+ ds.add_new(0x00091004, 'AT', [0x00280002, Tag('PatientName')])\n+ ds_json = json.loads(ds.to_json())\n+\n+ assert ['00100010', '00100020'] == ds_json['00091001']['Value']\n+ assert ['00280002'] == ds_json['00091002']['Value']\n+ assert ['00280002'] == ds_json['00091003']['Value']\n+ assert ['00280002', '00100010'] == ds_json['00091004']['Value']\n+\n+ def test_from_json(self):\n+ ds_json = ('{\"00091001\": {\"vr\": \"AT\", \"Value\": [\"000910AF\"]}, '\n+ '\"00091002\": {\"vr\": \"AT\", \"Value\": [\"00100010\", '\n+ '\"00100020\", \"00100030\"]}}')\n+ ds = Dataset.from_json(ds_json)\n+ assert 0x000910AF == ds[0x00091001].value\n+ assert [0x00100010, 0x00100020, 0x00100030] == ds[0x00091002].value\n+\n+ def test_invalid_json(self):\n+ ds_json = ('{\"00091001\": {\"vr\": \"AT\", \"Value\": [\"000910AG\"]}, '\n+ '\"00091002\": {\"vr\": \"AT\", \"Value\": [\"00100010\"]}}')\n+ with pytest.warns(UserWarning, match='Invalid value \"000910AG\" for '\n+ 'AT element - ignoring it'):\n+ ds = Dataset.from_json(ds_json)\n+ assert ds[0x00091001].value is None\n+ assert 0x00100010 == ds[0x00091002].value\n+\n+\n+class TestDataSetToJson(object):\n+ def test_json_from_dicom_file(self):\n+ ds1 = Dataset(dcmread(get_testdata_files(\"CT_small.dcm\")[0]))\n+ ds_json = ds1.to_json(bulk_data_threshold=100000)\n+ ds2 = Dataset.from_json(ds_json)\n+ assert ds1 == ds2\n+\n+ def test_roundtrip(self):\n+ ds = Dataset()\n+ ds.add_new(0x00080005, 'CS', 'ISO_IR 100')\n+ ds.add_new(0x00090010, 'LO', 'Creator 1.0')\n+ ds.add_new(0x00091001, 'SH', 'Version1')\n+ ds.add_new(0x00091002, 'OB', b'BinaryContent')\n+ ds.add_new(0x00091003, 'OW', b'\\x0102\\x3040\\x5060')\n+ ds.add_new(0x00091004, 'OF', b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07')\n+ ds.add_new(0x00091005, 'OD', b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'\n+ b'\\x01\\x01\\x02\\x03\\x04\\x05\\x06\\x07')\n+ ds.add_new(0x00091006, 'OL', b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'\n+ b'\\x01\\x01\\x02\\x03')\n+ ds.add_new(0x00091007, 'UI', '1.2.3.4.5.6')\n+ ds.add_new(0x00091008, 'DA', '20200101')\n+ ds.add_new(0x00091009, 'TM', '115500')\n+ ds.add_new(0x0009100a, 'DT', '20200101115500.000000')\n+ ds.add_new(0x0009100b, 'UL', 3000000000)\n+ ds.add_new(0x0009100c, 'SL', -2000000000)\n+ ds.add_new(0x0009100d, 'US', 40000)\n+ ds.add_new(0x0009100e, 'SS', -22222)\n+ ds.add_new(0x0009100f, 'FL', 3.14)\n+ ds.add_new(0x00091010, 'FD', 3.14159265)\n+ ds.add_new(0x00091011, 'CS', 'TEST MODE')\n+ ds.add_new(0x00091012, 'PN', 'CITIZEN^1')\n+ ds.add_new(0x00091013, 'PN', u'Yamada^Tarou=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046')\n+ ds.add_new(0x00091014, 'IS', '42')\n+ ds.add_new(0x00091015, 'DS', '3.14159265')\n+ ds.add_new(0x00091016, 'AE', b'CONQUESTSRV1')\n+ ds.add_new(0x00091017, 'AS', '055Y')\n+ ds.add_new(0x00091018, 'LT', 50 * u'\u041a\u0430\u043b\u0438\u043d\u043a\u0430,')\n+ ds.add_new(0x00091019, 'UC', 'LONG CODE VALUE')\n+ ds.add_new(0x0009101a, 'UN', b'\\x0102\\x3040\\x5060')\n+ ds.add_new(0x0009101b, 'UR', 'https://example.com')\n+ ds.add_new(0x0009101c, 'AT', [0x00100010, 0x00100020])\n+ ds.add_new(0x0009101d, 'ST', 100 * u'\u0639\u0644\u064a \u0628\u0627\u0628\u0627')\n+ ds.add_new(0x0009101e, 'SH', u'\u0394\u03b9\u03bf\u03bd\u03c5\u03c3\u03b9\u03bf\u03c2')\n+ ds.add_new(0x00090011, 'LO', 'Creator 2.0')\n+ ds.add_new(0x00091101, 'SH', 'Version2')\n+ ds.add_new(0x00091102, 'US', 2)\n+\n+ json_string = ds.to_json(bulk_data_threshold=100)\n+ json_model = json.loads(json_string)\n+ assert json_model['00080005']['Value'] == ['ISO_IR 100']\n+ assert json_model['00091007']['Value'] == ['1.2.3.4.5.6']\n+ assert json_model['0009100A']['Value'] == ['20200101115500.000000']\n+ assert json_model['0009100B']['Value'] == [3000000000]\n+ assert json_model['0009100C']['Value'] == [-2000000000]\n+ assert json_model['0009100D']['Value'] == [40000]\n+ assert json_model['0009100F']['Value'] == [3.14]\n+ assert json_model['00091010']['Value'] == [3.14159265]\n+ assert json_model['00091018']['Value'] == [50 * u'\u041a\u0430\u043b\u0438\u043d\u043a\u0430,']\n+\n+ ds2 = Dataset.from_json(json_string)\n+ assert ds == ds2\n+\n+ def test_json_private_DS_VM(self):\n+ test1_json = get_testdata_files(\"test1.json\")[0]\n+ jsonmodel = open(test1_json, 'r').read()\n+ ds = Dataset.from_json(jsonmodel)\n+ jsonmodel2 = ds.to_json(dump_handler=lambda d: json.dumps(d, indent=2))\n+ ds2 = Dataset.from_json(jsonmodel2)\n+\n+ assert ds.PatientIdentityRemoved == 'YES'\n+ assert ds2.PatientIdentityRemoved == 'YES'\n", "problem_statement": "To_Json 'str' object has no attribute 'components'\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\n<!-- Example: Attribute Error thrown when printing (0x0010, 0x0020) patient Id> 0-->\r\n\r\nWhen converting a dataset to json the following error occurs.\r\n```\r\nTraceback (most recent call last):\r\n File \"/anaconda3/lib/python3.6/threading.py\", line 916, in _bootstrap_inner\r\n self.run()\r\n File \"/anaconda3/lib/python3.6/threading.py\", line 864, in run\r\n self._target(*self._args, **self._kwargs)\r\n File \"~/pacs-proxy/pacs/service.py\", line 172, in saveFunction\r\n jsonObj = ds.to_json()\r\n File \"~/lib/python3.6/site-packages/pydicom/dataset.py\", line 2046, in to_json\r\n dump_handler=dump_handler\r\n File \"~/lib/python3.6/site-packages/pydicom/dataelem.py\", line 447, in to_json\r\n if len(elem_value.components) > 2:\r\nAttributeError: 'str' object has no attribute 'components'\r\n```\r\n#### Steps/Code to Reproduce\r\n\r\nds = pydicom.dcmread(\"testImg\")\r\njsonObj = ds.to_json()\r\n\r\nI'm working on getting an anonymous version of the image, will update. But any advice, suggestions would be appreciated.\r\n\r\n#### \n", "hints_text": "Thanks for the report! \r\nFor some reason, the value is not a `PersonName3` instance, as expected, but a string - this is obviously a bug. No need to provide a test dataset, as this is reproducible with existing test data. I will have a look tonight.\nAwesome. Thank you very much. This is the last hurdle for our project. :D", "created_at": "2019-08-06T19:27:04Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_PN_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_PN_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip"], "PASS_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_PN_from_file", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_private_DS_VM"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1674", "base_commit": "e77e6586fa38e6f7e98efca80d560d0fea8a9669", "patch": "diff --git a/pydicom/cli/main.py b/pydicom/cli/main.py\n--- a/pydicom/cli/main.py\n+++ b/pydicom/cli/main.py\n@@ -10,10 +10,11 @@\n import argparse\n import pkg_resources\n import re\n+import sys\n from typing import Tuple, cast, List, Any, Dict, Optional, Callable\n \n from pydicom import dcmread\n-from pydicom.data.data_manager import get_testdata_file\n+from pydicom.data.data_manager import get_charset_files, get_testdata_file\n from pydicom.dataset import Dataset\n \n \n@@ -132,6 +133,14 @@ def filespec_parser(filespec: str) -> List[Tuple[Dataset, Any]]:\n except NotImplementedError: # will get this if absolute path passed\n pydicom_filename = \"\"\n \n+ # Check if filename is in charset files\n+ if not pydicom_filename:\n+ try:\n+ char_filenames = get_charset_files(filename)\n+ pydicom_filename = char_filenames[0]\n+ except NotImplementedError: # will get this if absolute path passed\n+ pass\n+\n if prefix == \"pydicom\":\n filename = pydicom_filename\n \n@@ -201,8 +210,11 @@ def main(args: Optional[List[str]] = None) -> None:\n \"\"\"\n global subparsers\n \n+ py_version = sys.version.split()[0]\n+\n parser = argparse.ArgumentParser(\n- prog=\"pydicom\", description=\"pydicom command line utilities\"\n+ prog=\"pydicom\",\n+ description=f\"pydicom command line utilities (Python {py_version})\"\n )\n subparsers = parser.add_subparsers(help=\"subcommand help\")\n \ndiff --git a/pydicom/util/codify.py b/pydicom/util/codify.py\n--- a/pydicom/util/codify.py\n+++ b/pydicom/util/codify.py\n@@ -18,7 +18,8 @@\n import os.path\n import re\n import sys\n-from typing import Optional, List, Callable\n+from typing import Optional, List, Callable, cast\n+from collections import deque\n \n import pydicom\n from pydicom.datadict import dictionary_keyword\n@@ -80,7 +81,8 @@ def code_dataelem(\n dataelem: DataElement,\n dataset_name: str = \"ds\",\n exclude_size: Optional[int] = None,\n- include_private: bool = False\n+ include_private: bool = False,\n+ var_names: Optional[deque] = None\n ) -> str:\n \"\"\"Code lines for a single DICOM data element\n \n@@ -96,7 +98,8 @@ def code_dataelem(\n will only have a commented string for a value,\n causing a syntax error when the code is run,\n and thus prompting the user to remove or fix that line.\n-\n+ var_names: Union[deque, None]\n+ Used internally to ensure unique variable names in nested sequences.\n Returns\n -------\n str\n@@ -106,7 +109,8 @@ def code_dataelem(\n \n if dataelem.VR == VR.SQ:\n return code_sequence(\n- dataelem, dataset_name, exclude_size, include_private\n+ dataelem, dataset_name, exclude_size, include_private,\n+ var_names=var_names\n )\n \n # If in DICOM dictionary, set using the keyword\n@@ -143,6 +147,7 @@ def code_sequence(\n exclude_size: Optional[int] = None,\n include_private: bool = False,\n name_filter: Callable[[str], str] = default_name_filter,\n+ var_names: Optional[deque] = None,\n ) -> str:\n \"\"\"Code lines for recreating a Sequence data element\n \n@@ -162,6 +167,8 @@ def code_sequence(\n name_filter: Callable[[str], str]\n A callable taking a sequence name or sequence item name, and returning\n a shorter name for easier code reading\n+ var_names: Union[deque, None]\n+ Used internally to ensure unique variable names in nested sequences.\n \n Returns\n -------\n@@ -169,6 +176,15 @@ def code_sequence(\n A string containing code lines to recreate a DICOM sequence\n \"\"\"\n \n+ # Normally var_names is given from code_dataset, but for some tests need\n+ # to initialize it\n+ if var_names is None:\n+ var_names = deque()\n+\n+ def unique_name(name: str) -> str:\n+ name_count = cast(deque, var_names).count(name) - 1\n+ return name if name_count == 0 else name + f\"_{name_count}\"\n+\n lines = []\n seq = dataelem.value\n seq_name = dataelem.name\n@@ -183,8 +199,11 @@ def code_sequence(\n lines.append(\"# \" + seq_name)\n \n # Code line to create a new Sequence object\n- if name_filter:\n- seq_var = name_filter(seq_keyword)\n+ seq_var = name_filter(seq_keyword)\n+ var_names.append(seq_var)\n+ orig_seq_var = seq_var\n+ seq_var = unique_name(seq_var)\n+\n lines.append(seq_var + \" = Sequence()\")\n \n # Code line to add the sequence to its parent\n@@ -208,14 +227,29 @@ def code_sequence(\n lines.append(\"# \" + seq_name + \": \" + seq_item_name + \" \" + index_str)\n \n # Determine the variable name to use for the sequence item (dataset)\n- ds_name = seq_var.replace(\"_sequence\", \"\") + index_str\n+ ds_name = orig_seq_var.replace(\"_sequence\", \"\") + index_str\n \n- # Code the sequence item\n- code_item = code_dataset(ds, ds_name, exclude_size, include_private)\n- lines.append(code_item)\n+ # Append \"_#\" if name already in use (in parent sequences)\n+ var_names.append(ds_name)\n+ ds_name = unique_name(ds_name)\n+\n+ # Code the sequence item dataset\n+ code_item = code_dataset(\n+ ds, ds_name, exclude_size, include_private, var_names=var_names\n+ )\n \n- # Code the line to append the item to its parent sequence\n- lines.append(seq_var + \".append(\" + ds_name + \")\")\n+ # Remove variable name from stored list, this dataset complete\n+ var_names.pop()\n+\n+ # Code dataset creation and appending that to sequence, then the rest\n+ # This keeps the logic close together, rather than after many items set\n+ code_split = code_item.splitlines()\n+ lines.append(code_split[0]) # \"<ds_name> = Dataset()\"\n+ lines.append(f\"{seq_var}.append({ds_name})\")\n+ lines.extend(code_split[1:])\n+\n+ # Remove sequence variable name we've used\n+ var_names.pop()\n \n # Join the lines and return a single string\n return line_term.join(lines)\n@@ -227,6 +261,7 @@ def code_dataset(\n exclude_size: Optional[int] = None,\n include_private: bool = False,\n is_file_meta: bool = False,\n+ var_names: Optional[deque] = None\n ) -> str:\n \"\"\"Return Python code for creating `ds`.\n \n@@ -245,6 +280,8 @@ def code_dataset(\n data elements will be coded.\n is_file_meta : bool, optional\n ``True`` if `ds` contains file meta information elements.\n+ var_names: deque, optional\n+ Used internally to ensure unique variable names in nested sequences.\n \n Returns\n -------\n@@ -252,8 +289,12 @@ def code_dataset(\n The codified dataset.\n \"\"\"\n \n+ if var_names is None:\n+ var_names = deque()\n lines = []\n+\n ds_class = \" = FileMetaDataset()\" if is_file_meta else \" = Dataset()\"\n+\n lines.append(dataset_name + ds_class)\n for dataelem in ds:\n # If a private data element and flag says so, skip it and go to next\n@@ -261,7 +302,8 @@ def code_dataset(\n continue\n # Otherwise code the line and add it to the lines list\n code_line = code_dataelem(\n- dataelem, dataset_name, exclude_size, include_private\n+ dataelem, dataset_name, exclude_size, include_private,\n+ var_names=var_names\n )\n lines.append(code_line)\n # Add blank line if just coded a sequence\n@@ -270,6 +312,7 @@ def code_dataset(\n # If sequence was end of this dataset, remove the extra blank line\n if len(lines) and lines[-1] == \"\":\n lines.pop()\n+\n # Join all the code lines and return them\n return line_term.join(lines)\n \n@@ -313,8 +356,8 @@ def code_file_from_dataset(\n \n Parameters\n ----------\n- filename : str\n- Complete path and filename of a DICOM file to convert\n+ ds : Dataset\n+ A pydicom Dataset to convert\n exclude_size : Union[int,None]\n If not None, values longer than this (in bytes)\n will only have a commented string for a value,\n@@ -336,6 +379,7 @@ def code_file_from_dataset(\n filename = ds.get(\"filename\")\n identifier = f\"DICOM file '{filename}'\" if filename else \"non-file dataset\"\n \n+ lines.append(\"# -*- coding: utf-8 -*-\")\n lines.append(f\"# Coded version of {identifier}\")\n lines.append(\"# Produced by pydicom codify utility script\")\n \n@@ -385,7 +429,7 @@ def set_parser_arguments(\n parser.add_argument(\n \"outfile\",\n nargs=\"?\",\n- type=argparse.FileType(\"w\"),\n+ type=argparse.FileType(\"w\", encoding=\"UTF-8\"),\n help=(\n \"Filename to write Python code to, if not specified then code is \"\n \"written to stdout\"\n", "test_patch": "diff --git a/pydicom/tests/test_cli.py b/pydicom/tests/test_cli.py\n--- a/pydicom/tests/test_cli.py\n+++ b/pydicom/tests/test_cli.py\n@@ -1,3 +1,4 @@\n+# -*- coding: utf-8 -*-\n # Copyright 2020 pydicom authors. See LICENSE file for details.\n \"\"\"Tests for command-line interface\"\"\"\n \n@@ -138,6 +139,13 @@ def test_codify_data_element(self, capsys):\n with pytest.raises(NotImplementedError):\n main(\"codify pydicom::rtplan.dcm::RTPlanLabel\".split())\n \n+ def test_codify_UTF8(self, capsys):\n+ \"\"\"CLI `codify` command creates code with utf-8 characters\"\"\"\n+ main(f\"codify pydicom::chrFren.dcm\".split())\n+ out, _ = capsys.readouterr()\n+ assert out.startswith(\"# -*- coding: utf-8 -*-\")\n+ assert \"Buc^J\u00e9r\u00f4me\" in out\n+\n def test_help(self, capsys):\n \"\"\"CLI `help` command gives expected output\"\"\"\n # With subcommand\ndiff --git a/pydicom/tests/test_util.py b/pydicom/tests/test_util.py\n--- a/pydicom/tests/test_util.py\n+++ b/pydicom/tests/test_util.py\n@@ -5,12 +5,11 @@\n \n import pytest\n \n-from pydicom import config, dcmread\n+from pydicom import config, dcmread, Dataset, Sequence\n from pydicom import filereader\n from pydicom._private_dict import private_dictionaries\n from pydicom.data import get_testdata_file\n from pydicom.dataelem import DataElement\n-from pydicom.dataset import Dataset\n from pydicom.tag import Tag\n from pydicom.uid import (\n ImplicitVRLittleEndian, ExplicitVRBigEndian, ExplicitVRLittleEndian\n@@ -23,6 +22,7 @@\n default_name_filter,\n code_imports,\n code_dataelem,\n+ code_dataset,\n main as codify_main,\n )\n from pydicom.util.dump import *\n@@ -134,15 +134,34 @@ def test_code_sequence(self):\n \"\\n\"\n \"# Control Point Sequence: Control Point 1\\n\"\n \"cp1 = Dataset()\\n\"\n- \"cp1.PatientID = '1234'\\n\"\n- \"cp_sequence.append(cp1)\"\n+ \"cp_sequence.append(cp1)\\n\"\n+ \"cp1.PatientID = '1234'\"\n )\n \n assert out == code_dataelem(elem)\n \n- def test_code_dataset(self):\n- \"\"\"Test utils.codify.code_dataset\"\"\"\n- pass\n+ def test_codify_recurring_keyword(self):\n+ \"\"\"Test utils.codify.code_dataset with same keyword nested\"\"\"\n+ # Create fake Dataset with repeated DICOM keyword nested\n+ # (0040, a730) Content Sequence 1 item(s) ----\n+ # (0040, a040) Value Type CS: 'CODE'\n+ # (0040, a730) Content Sequence 1 item(s) ----\n+ # (0040, a040) Value Type CS: 'CODE'\n+\n+ ds = Dataset()\n+ ds.ContentSequence = seq1 = Sequence()\n+ seq1.append(Dataset())\n+ seq1[0].ValueType = \"CODE\"\n+ seq1[0].ContentSequence = seq2 = Sequence()\n+ seq2.append(Dataset())\n+ seq2[0].ValueType = \"CODE_1\"\n+ ds_code = code_dataset(ds)\n+\n+ # normal 1st use of var name\n+ assert \"content1.ValueType = 'CODE'\" in ds_code\n+\n+ # Nested item of same name should have subscript\n+ assert \"content1_1.ValueType = 'CODE_1'\" in ds_code\n \n def test_code_file(self, capsys):\n \"\"\"Test utils.codify.code_file\"\"\"\n", "problem_statement": "Codify not generating content sequences correctly\n**Describe the bug**\r\nI am trying to generate a radiation dose structure report. I ran Codify on an existing RDSR to generate a template. The sequence content is reproduced but does not seem to be attached to the base dataset. When I run the generated python file the dicom file it saves has no sequence content information.\r\n\r\n**Expected behavior**\r\nI expect the dicom file generated by the python code from Codify to be similar to the original file.\r\n\r\n**Steps To Reproduce**\r\n$ python codify X-RayRadiationDoseReport001_ESR.dcm rdsr.py\r\n$ python rsdr.py\r\n\r\nI am not able to attached the above files but can supply them.\r\n\r\n**Your environment**\r\nmodule | version\r\n------ | -------\r\nplatform | Linux-5.18.7-200.fc36.x86_64-x86_64-with-glibc2.35\r\nPython | 3.10.5 (main, Jun 9 2022, 00:00:00) [GCC 12.1.1 20220507 (Red Hat 12.1.1-1)]\r\npydicom | 2.3.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.22.4\r\nPIL | 9.2.0\r\npylibjpeg | _module not found_\r\nopenjpeg | _module not found_\r\nlibjpeg | _module not found_\r\n\r\nRegards\r\nAlan\n", "hints_text": "Hi Alan,\r\n\r\nI'm happy to look into this, but may need a file to work with. But perhaps we can first have a look at the generated code, which normally immediately attaches any sequence it creates. For example:\r\n\r\n```\r\n$ pydicom codify pydicom::rtplan.dcm\r\n```\r\nGives lines like\r\n\r\n```python\r\n# Beam Sequence\r\nbeam_sequence = Sequence()\r\nds.BeamSequence = beam_sequence\r\n```\r\n\r\nand then proceeds to create a new Dataset, set its data elements, and eventually `append` it to the sequence:\r\n\r\n```python\r\n# Beam Sequence: Beam 1\r\nbeam1 = Dataset()\r\nbeam1.Manufacturer = 'Linac co.'\r\nbeam1.InstitutionName = 'Here'\r\n.\r\n.\r\n.\r\nbeam_sequence.append(beam1)\r\n```\r\nCan you check your generated code for those kinds of patterns and let us know what you see?\r\n\r\n\nHi Darcy\r\n\r\nThanks for the guidance. Stepping through the code I've picked up two problems. The first has to do with nested content. Eg. if the DICOM file has:\r\n\r\n\r\nThe second Content1 overwrites the first. See lines 121-191 in the attached file.\r\n\r\n[rdsr.txt](https://github.com/pydicom/pydicom/files/9356766/rdsr.txt) Rename this file to rsdr.py.\r\n\r\nThe second problem is more puzzling. In lines 121-191 we have:\r\n\r\n```\r\ncontent_sequence = Sequence()\r\nds.ContentSequence = content_sequence\r\n\r\n# Content Sequence: Content 1\r\ncontent1 = Dataset()\r\ncontent1.add_new((0x0040, 0x0000), 'UL', 512)\r\ncontent1.RelationshipType = 'HAS CONCEPT MOD'\r\ncontent1.ValueType = 'CODE'\r\n.\r\n.\r\n.\r\ncontent_sequence.append(content1)\r\n```\r\nAfter stepping though this ds.ContentSequence is still empty even though there are definitely items in content1 and the items were added to content_sequence. It is not related to the nested content as content2 (lines 193 - 223 in rdsr.py) which has no nested content shows the same behaviour.\r\n\r\nIf I shift the line \"ds.ContentSequence = content_sequence\" to just before the save statement at the end of the file the script crashes while saving with:\r\nRecursionError: maximum recursion depth exceeded while calling a Python object\r\nThis suggests two things:\r\n1) The previous code is generating a nested loop somewhere.\r\n2) The line \"ds.ContentSequence = content_sequence\" appears to be creating a copy of content_sequence. My understanding of python is that an assigning objects should merely update pointers, but this does not appear to be the case.\r\n\r\nI would suggest generating content names that reflect the content level if possible, eg. content1-1.\r\n\r\nRegards\r\nAlan\nAlan, if you are unable to share your RDSR for testing, do you want to check the behaviour is the same with one of the OpenREM test RDSR files and use that for Darcy or anyone else to work on? One of the more straight forward ones, maybe [this Siemens Flash one](https://bitbucket.org/openrem/openrem/src/develop/openrem/remapp/tests/test_files/CT-RDSR-Siemens_Flash-TAP-SS.dcm)?\nHi Ed\r\nI ran Codify on CT-RDSR-Siemens_Flash-TAP-SS.dcm as you suggested. This gave the attached file:\r\n[CT-RDSR-Siemens_Flash-TAP-SS.py.txt](https://github.com/pydicom/pydicom/files/9359044/CT-RDSR-Siemens_Flash-TAP-SS.py.txt) rename to .py\r\nRunning this file produces a dicom file 10 times smaller than the original file (attached)\r\n[CT-RDSR-Siemens_Flash-TAP-SS_from_codify.dcm.txt](https://github.com/pydicom/pydicom/files/9359049/CT-RDSR-Siemens_Flash-TAP-SS_from_codify.dcm.txt) Rename to .dcm\r\nLooking at this in a dicom viewer the sequence content is gone.\r\nHope this helps\r\nRegards\r\nAlan\r\n\r\n\r\n\n> The second Content1 overwrites the first.\r\n> ...\r\n> I would suggest generating content names that reflect the content level if possible, eg. content1-1.\r\n\r\nRight, it makes sense - the code didn't consider that a nested item could have the same name. I can update that.\r\n\r\n\r\n> RecursionError: maximum recursion depth exceeded while calling a Python object\r\n\r\nNot too surprising - I think I hit recursion problems when I first wrote codify.\r\n\r\nThanks for the detailed investigation and example files (thanks also @edmcdonagh for the suggestion). I can set up some failing tests with those and then see about fixing them. I've got some time in the next couple of days, hopefully it isn't too difficult and I can get a PR soon.", "created_at": "2022-08-18T17:35:33Z", "version": "2.3", "FAIL_TO_PASS": ["pydicom/tests/test_cli.py::TestCLIcall::test_codify_UTF8", "pydicom/tests/test_util.py::TestCodify::test_code_sequence", "pydicom/tests/test_util.py::TestCodify::test_codify_recurring_keyword"], "PASS_TO_PASS": ["pydicom/tests/test_cli.py::TestFilespec::test_syntax[extra:colon]", "pydicom/tests/test_cli.py::TestFilespec::test_syntax[no_callable()]", "pydicom/tests/test_cli.py::TestFilespec::test_syntax[no_equals", "pydicom/tests/test_cli.py::TestFilespec::test_syntax[BeamSequence[0]extra]", "pydicom/tests/test_cli.py::TestFilespec::test_syntax[BeamSequence[x]]", "pydicom/tests/test_cli.py::TestFilespec::test_elem_not_exists[NotThere]", "pydicom/tests/test_cli.py::TestFilespec::test_elem_not_exists[BeamSequenceXX]", "pydicom/tests/test_cli.py::TestFilespec::test_elem_not_exists[BeamDose]", "pydicom/tests/test_cli.py::TestFilespec::test_bad_index[BeamSequence[42]]", "pydicom/tests/test_cli.py::TestFilespec::test_bad_index[BeamSequence[-42]]", "pydicom/tests/test_cli.py::TestFilespec::test_offers_pydicom_testfile", "pydicom/tests/test_cli.py::TestFilespec::test_colons", "pydicom/tests/test_cli.py::TestFilespecElementEval::test_correct_values", "pydicom/tests/test_cli.py::TestCLIcall::test_bare_command", "pydicom/tests/test_cli.py::TestCLIcall::test_codify_command", "pydicom/tests/test_cli.py::TestCLIcall::test_codify_data_element", "pydicom/tests/test_cli.py::TestCLIcall::test_help", "pydicom/tests/test_cli.py::TestCLIcall::test_show_command", "pydicom/tests/test_cli.py::TestCLIcall::test_show_options", "pydicom/tests/test_util.py::TestCodify::test_camel_to_underscore", "pydicom/tests/test_util.py::TestCodify::test_tag_repr", "pydicom/tests/test_util.py::TestCodify::test_default_name_filter", "pydicom/tests/test_util.py::TestCodify::test_code_imports", "pydicom/tests/test_util.py::TestCodify::test_code_dataelem_standard", "pydicom/tests/test_util.py::TestCodify::test_code_dataelem_exclude_size", "pydicom/tests/test_util.py::TestCodify::test_code_dataelem_private", "pydicom/tests/test_util.py::TestCodify::test_code_dataelem_sequence", "pydicom/tests/test_util.py::TestCodify::test_code_file", "pydicom/tests/test_util.py::TestDump::test_print_character", "pydicom/tests/test_util.py::TestDump::test_filedump", "pydicom/tests/test_util.py::TestDump::test_datadump", "pydicom/tests/test_util.py::TestDump::test_hexdump", "pydicom/tests/test_util.py::TestDump::test_pretty_print", "pydicom/tests/test_util.py::TestFixer::test_fix_separator_callback", "pydicom/tests/test_util.py::TestFixer::test_fix_separator", "pydicom/tests/test_util.py::TestFixer::test_mismatch_callback", "pydicom/tests/test_util.py::TestFixer::test_fix_mismatch", "pydicom/tests/test_util.py::TestHexUtil::test_hex_to_bytes", "pydicom/tests/test_util.py::TestHexUtil::test_bytes_to_hex", "pydicom/tests/test_util.py::TestDataElementCallbackTests::test_bad_separator", "pydicom/tests/test_util.py::TestDataElementCallbackTests::test_impl_vr_comma", "pydicom/tests/test_util.py::TestDataElementCallbackTests::test_null_value_for_fixed_vr", "pydicom/tests/test_util.py::TestDataElementCallbackTests::test_space_delimiter", "pydicom/tests/test_util.py::TestDataElementCallbackTests::test_process_unknown_vr", "pydicom/tests/test_util.py::TestLeanRead::test_explicit_little", "pydicom/tests/test_util.py::TestLeanRead::test_implicit_little", "pydicom/tests/test_util.py::TestLeanRead::test_explicit_big", "pydicom/tests/test_util.py::TestLeanRead::test_no_tsyntax", "pydicom/tests/test_util.py::TestLeanRead::test_no_meta", "pydicom/tests/test_util.py::TestLeanRead::test_UN_sequence"], "environment_setup_commit": "a8be738418dee0a2b93c241fbd5e0bc82f4b8680"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1228", "base_commit": "8112bb69bfc0423c3a08cb89e7960defbe7237bf", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -231,7 +231,12 @@ def from_json(\n vr: str,\n value: object,\n value_key: Union[str, None],\n- bulk_data_uri_handler: Optional[Callable[[str], object]] = None\n+ bulk_data_uri_handler: Optional[\n+ Union[\n+ Callable[[BaseTag, str, str], object],\n+ Callable[[str], object]\n+ ]\n+ ] = None\n ) -> _DataElement:\n \"\"\"Return a :class:`DataElement` from JSON.\n \n@@ -251,7 +256,8 @@ def from_json(\n Key of the data element that contains the value\n (options: ``{\"Value\", \"InlineBinary\", \"BulkDataURI\"}``)\n bulk_data_uri_handler: callable or None\n- Callable function that accepts the \"BulkDataURI\" of the JSON\n+ Callable function that accepts either the tag, vr and \"BulkDataURI\"\n+ or just the \"BulkDataURI\" of the JSON\n representation of a data element and returns the actual value of\n that data element (retrieved via DICOMweb WADO-RS)\n \n@@ -260,8 +266,14 @@ def from_json(\n DataElement\n \"\"\"\n # TODO: test wado-rs retrieve wrapper\n- converter = JsonDataElementConverter(dataset_class, tag, vr, value,\n- value_key, bulk_data_uri_handler)\n+ converter = JsonDataElementConverter(\n+ dataset_class,\n+ tag,\n+ vr,\n+ value,\n+ value_key,\n+ bulk_data_uri_handler\n+ )\n elem_value = converter.get_element_values()\n try:\n return cls(tag=tag, value=elem_value, VR=vr)\ndiff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -2218,7 +2218,12 @@ def walk(\n def from_json(\n cls: Type[_Dataset],\n json_dataset: Union[Dict[str, bytes], str],\n- bulk_data_uri_handler: Optional[Callable[[bytes], object]] = None\n+ bulk_data_uri_handler: Optional[\n+ Union[\n+ Callable[[BaseTag, str, str], object],\n+ Callable[[str], object]\n+ ]\n+ ] = None\n ) -> _Dataset:\n \"\"\"Add elements to the :class:`Dataset` from DICOM JSON format.\n \n@@ -2232,7 +2237,8 @@ def from_json(\n :class:`dict` or :class:`str` representing a DICOM Data Set\n formatted based on the DICOM JSON Model.\n bulk_data_uri_handler : callable, optional\n- Callable function that accepts the \"BulkDataURI\" of the JSON\n+ Callable function that accepts either the tag, vr and \"BulkDataURI\"\n+ or just the \"BulkDataURI\" of the JSON\n representation of a data element and returns the actual value of\n data element (retrieved via DICOMweb WADO-RS).\n \n@@ -2263,7 +2269,7 @@ def from_json(\n def to_json_dict(\n self,\n bulk_data_threshold: int = 1024,\n- bulk_data_element_handler: Optional[Callable[[DataElement], bytes]] = None # noqa\n+ bulk_data_element_handler: Optional[Callable[[DataElement], str]] = None # noqa\n ) -> _Dataset:\n \"\"\"Return a dictionary representation of the :class:`Dataset`\n conforming to the DICOM JSON Model as described in the DICOM\n@@ -2301,7 +2307,7 @@ def to_json_dict(\n def to_json(\n self,\n bulk_data_threshold: int = 1024,\n- bulk_data_element_handler: Optional[Callable[[DataElement], bytes]] = None, # noqa\n+ bulk_data_element_handler: Optional[Callable[[DataElement], str]] = None, # noqa\n dump_handler: Optional[Callable[[\"Dataset\"], str]] = None\n ) -> str:\n \"\"\"Return a JSON representation of the :class:`Dataset`.\ndiff --git a/pydicom/jsonrep.py b/pydicom/jsonrep.py\n--- a/pydicom/jsonrep.py\n+++ b/pydicom/jsonrep.py\n@@ -2,9 +2,12 @@\n \"\"\"Methods for converting Datasets and DataElements to/from json\"\"\"\n \n import base64\n+from inspect import signature\n+import inspect\n+from typing import Callable, Optional, Union\n import warnings\n \n-from pydicom.valuerep import PersonName\n+from pydicom.tag import BaseTag\n \n # Order of keys is significant!\n JSON_VALUE_KEYS = ('Value', 'BulkDataURI', 'InlineBinary',)\n@@ -54,8 +57,20 @@ class JsonDataElementConverter:\n .. versionadded:: 1.4\n \"\"\"\n \n- def __init__(self, dataset_class, tag, vr, value, value_key,\n- bulk_data_uri_handler):\n+ def __init__(\n+ self,\n+ dataset_class,\n+ tag,\n+ vr,\n+ value,\n+ value_key,\n+ bulk_data_uri_handler: Optional[\n+ Union[\n+ Callable[[BaseTag, str, str], object],\n+ Callable[[str], object]\n+ ]\n+ ] = None\n+ ):\n \"\"\"Create a new converter instance.\n \n Parameters\n@@ -63,7 +78,7 @@ def __init__(self, dataset_class, tag, vr, value, value_key,\n dataset_class : dataset.Dataset derived class\n Class used to create sequence items.\n tag : BaseTag\n- The data element tag.\n+ The data element tag or int.\n vr : str\n The data element value representation.\n value : list\n@@ -72,7 +87,8 @@ def __init__(self, dataset_class, tag, vr, value, value_key,\n Key of the data element that contains the value\n (options: ``{\"Value\", \"InlineBinary\", \"BulkDataURI\"}``)\n bulk_data_uri_handler: callable or None\n- Callable function that accepts the \"BulkDataURI\" of the JSON\n+ Callable function that accepts either the tag, vr and \"BulkDataURI\"\n+ or just the \"BulkDataURI\" of the JSON\n representation of a data element and returns the actual value of\n that data element (retrieved via DICOMweb WADO-RS)\n \"\"\"\n@@ -81,7 +97,15 @@ def __init__(self, dataset_class, tag, vr, value, value_key,\n self.vr = vr\n self.value = value\n self.value_key = value_key\n- self.bulk_data_uri_handler = bulk_data_uri_handler\n+ if (\n+ bulk_data_uri_handler and\n+ len(signature(bulk_data_uri_handler).parameters) == 1\n+ ):\n+ def wrapped_bulk_data_handler(tag, vr, value):\n+ return bulk_data_uri_handler(value)\n+ self.bulk_data_element_handler = wrapped_bulk_data_handler\n+ else:\n+ self.bulk_data_element_handler = bulk_data_uri_handler\n \n def get_element_values(self):\n \"\"\"Return a the data element value or list of values.\n@@ -124,13 +148,13 @@ def get_element_values(self):\n if not isinstance(value, str):\n fmt = '\"{}\" of data element \"{}\" must be a string.'\n raise TypeError(fmt.format(self.value_key, self.tag))\n- if self.bulk_data_uri_handler is None:\n+ if self.bulk_data_element_handler is None:\n warnings.warn(\n 'no bulk data URI handler provided for retrieval '\n 'of value of data element \"{}\"'.format(self.tag)\n )\n return empty_value_for_VR(self.vr, raw=True)\n- return self.bulk_data_uri_handler(value)\n+ return self.bulk_data_element_handler(self.tag, self.vr, value)\n return empty_value_for_VR(self.vr)\n \n def get_regular_element_value(self, value):\n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -334,7 +334,18 @@ def test_invalid_bulkdata_uri(self):\n Dataset.from_json(ds_json)\n \n def test_bulk_data_reader_is_called(self):\n- def bulk_data_reader(_):\n+ def bulk_data_reader(value):\n+ return b'xyzzy'\n+\n+ json_data = {\n+ \"00091002\": {\"vr\": \"OB\", \"BulkDataURI\": \"https://a.dummy.url\"}\n+ }\n+ ds = Dataset().from_json(json.dumps(json_data), bulk_data_reader)\n+\n+ assert b'xyzzy' == ds[0x00091002].value\n+\n+ def test_bulk_data_reader_is_called_2(self):\n+ def bulk_data_reader(tag, vr, value):\n return b'xyzzy'\n \n json_data = {\n", "problem_statement": "Add Tag and VR to the bulk data handling in `from_json`\nCurrently, if you convert back to a Dataset format from a JSON format, you MUST re-hydrate all of the bulk data URI's or you will loose the information.\r\n\r\nThis causes a problem if you just wish to use the Dataset's header (maybe to extract some data, or rearrange some data), because now you have to pay the cost of getting all the pixel data and then handling the pixel data again upon conversion back to JSON\r\n\r\n**Describe the solution you'd like**\r\nAdd the tag and the vr to the bulk data handler in `from_json` (this can be done in a backwards compatible way). This will allow the user to store the BulkDataURI's by tag in a map, return dummy data large enough to trigger the bulk handling when to_json is called next, and to use the map to convert back to the original URI's when bulk handling is triggered from to_json.\r\n\r\nI'm going to drop a PR tomorrow that does this in a fully backward compatible, non-breaking fashion.\r\n\n", "hints_text": "", "created_at": "2020-10-18T17:24:48Z", "version": "2.0", "FAIL_TO_PASS": ["pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_2"], "PASS_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called"], "environment_setup_commit": "9d69811e539774f296c2f289839147e741251716"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1365", "base_commit": "bd82f01faf4212f6e43f55a1cc6da17956122d8f", "patch": "diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -135,6 +135,8 @@ def __init__(self, val: Union[str, _DA, datetime.date]) -> None:\n self.original_string = val\n elif isinstance(val, DA) and hasattr(val, 'original_string'):\n self.original_string = val.original_string\n+ elif isinstance(val, datetime.date):\n+ self.original_string = f\"{val.year}{val.month:02}{val.day:02}\"\n \n \n class DT(_DateTimeBase, datetime.datetime):\n@@ -242,6 +244,22 @@ def __init__(self, val: Union[str, _DT, datetime.datetime]) -> None:\n self.original_string = val\n elif isinstance(val, DT) and hasattr(val, 'original_string'):\n self.original_string = val.original_string\n+ elif isinstance(val, datetime.datetime):\n+ self.original_string = (\n+ f\"{val.year:04}{val.month:02}{val.day:02}\"\n+ f\"{val.hour:02}{val.minute:02}{val.second:02}\"\n+ )\n+ # milliseconds are seldom used, add them only if needed\n+ if val.microsecond > 0:\n+ self.original_string += f\".{val.microsecond:06}\"\n+ if val.tzinfo is not None:\n+ offset = val.tzinfo.utcoffset(val)\n+ offset_min = offset.days * 24 * 60 + offset.seconds // 60\n+ sign = \"+\" if offset_min >= 0 else \"-\"\n+ offset_min = abs(offset_min)\n+ self.original_string += (\n+ f\"{sign}{offset_min // 60:02}{offset_min % 60:02}\"\n+ )\n \n \n class TM(_DateTimeBase, datetime.time):\n@@ -318,6 +336,13 @@ def __init__(self, val: Union[str, _TM, datetime.time]) -> None:\n self.original_string = val\n elif isinstance(val, TM) and hasattr(val, 'original_string'):\n self.original_string = val.original_string\n+ elif isinstance(val, datetime.time):\n+ self.original_string = (\n+ f\"{val.hour:02}{val.minute:02}{val.second:02}\"\n+ )\n+ # milliseconds are seldom used, add them only if needed\n+ if val.microsecond > 0:\n+ self.original_string += f\".{val.microsecond:06}\"\n \n if platform.python_implementation() == \"PyPy\":\n # Workaround for CPython/PyPy bug in time.__reduce_ex__()\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -300,8 +300,7 @@ def test_multivalue_DA(self):\n DA_expected = date(1961, 8, 4)\n tzinfo = timezone(timedelta(seconds=-21600), '-0600')\n multi_DT_expected = (datetime(1961, 8, 4), datetime(\n- 1963, 11, 22, 12, 30, 0, 0,\n- timezone(timedelta(seconds=-21600), '-0600')))\n+ 1963, 11, 22, 12, 30, 0, 0, tzinfo))\n multi_TM_expected = (time(1, 23, 45), time(11, 11, 11))\n TM_expected = time(11, 11, 11, 1)\n ds = dcmread(datetime_name)\ndiff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -69,11 +69,15 @@ def test_pickling(self):\n \n def test_str(self):\n \"\"\"Test str(TM).\"\"\"\n- x = pydicom.valuerep.TM(\"212223\")\n- assert \"212223\" == str(x)\n- del x.original_string\n- assert not hasattr(x, 'original_string')\n- assert \"21:22:23\" == str(x)\n+ assert \"212223.1234\" == str(pydicom.valuerep.TM(\"212223.1234\"))\n+ assert \"212223\" == str(pydicom.valuerep.TM(\"212223\"))\n+ assert \"212223\" == str(pydicom.valuerep.TM(\"212223\"))\n+ assert \"2122\" == str(pydicom.valuerep.TM(\"2122\"))\n+ assert \"21\" == str(pydicom.valuerep.TM(\"21\"))\n+ assert \"212223\" == str(pydicom.valuerep.TM(time(21, 22, 23)))\n+ assert \"212223.000024\" == str(\n+ pydicom.valuerep.TM(time(21, 22, 23, 24)))\n+ assert \"010203\" == str(pydicom.valuerep.TM(time(1, 2, 3)))\n \n def test_new_empty_str(self):\n \"\"\"Test converting an empty string.\"\"\"\n@@ -185,6 +189,18 @@ def test_new_str_conversion(self):\n with pytest.raises(ValueError, match=msg):\n pydicom.valuerep.DT(\"a2000,00,00\")\n \n+ def test_str(self):\n+ dt = datetime(1911, 12, 13, 21, 21, 23)\n+ assert \"19111213212123\" == str(pydicom.valuerep.DT(dt))\n+ assert \"19111213212123\" == str(pydicom.valuerep.DT(\"19111213212123\"))\n+ assert \"1001.02.03\" == str(pydicom.valuerep.DA(\"1001.02.03\"))\n+ tz_info = timezone(timedelta(seconds=21600), '+0600')\n+ dt = datetime(2022, 1, 2, 8, 9, 7, 123456, tzinfo=tz_info)\n+ assert \"20220102080907.123456+0600\" == str(pydicom.valuerep.DT(dt))\n+ tz_info = timezone(timedelta(seconds=-23400), '-0630')\n+ dt = datetime(2022, 12, 31, 23, 59, 59, 42, tzinfo=tz_info)\n+ assert \"20221231235959.000042-0630\" == str(pydicom.valuerep.DT(dt))\n+\n \n class TestDA:\n \"\"\"Unit tests for pickling DA\"\"\"\n@@ -213,6 +229,11 @@ def test_new_obj_conversion(self):\n with pytest.raises(ValueError, match=msg):\n pydicom.valuerep.DA(123456)\n \n+ def test_str(self):\n+ assert \"10010203\" == str(pydicom.valuerep.DA(date(1001, 2, 3)))\n+ assert \"10010203\" == str(pydicom.valuerep.DA(\"10010203\"))\n+ assert \"1001.02.03\" == str(pydicom.valuerep.DA(\"1001.02.03\"))\n+\n \n class TestIsValidDS:\n \"\"\"Unit tests for the is_valid_ds function.\"\"\"\n", "problem_statement": "DA class is inconsistent\n**Describe the bug**\r\npydicom.valuerep.DA accepts strings or datetime.date objects - but DA objects created with datetime.date inputs are invalid. \r\n\r\n**Expected behavior**\r\nI would expect both of these expressions to generate the same output:\r\n```\r\nprint(f'DA(\"20201117\") => {DA(\"20201117\")}')\r\nprint(f'DA(date(2020, 11, 17)) => {DA(date(2020, 11, 17))}')\r\n```\r\nbut instead I get\r\n```\r\nDA(\"20201117\") => 20201117\r\nDA(date(2020, 11, 17)) => 2020-11-17\r\n```\r\nThe hyphens inserted into the output are not valid DICOM - see the DA description in [Table 6.2-1](http://dicom.nema.org/dicom/2013/output/chtml/part05/sect_6.2.html)\r\n\r\n**Steps To Reproduce**\r\nRun the following commands:\r\n```\r\nfrom pydicom.valuerep import DA\r\nfrom pydicom.dataset import Dataset\r\nfrom datetime import date, datetime\r\n\r\nprint(f'DA(\"20201117\") => {DA(\"20201117\")}')\r\nprint(f'DA(date(2020, 11, 17)) => {DA(date(2020, 11, 17))}')\r\n\r\n# 1. JSON serialization with formatted string works\r\nds = Dataset()\r\nds.ContentDate = '20201117'\r\njson_output = ds.to_json()\r\nprint(f'json_output works = {json_output}')\r\n\r\n# 2. JSON serialization with date object input is invalid.\r\nds = Dataset()\r\nds.ContentDate = str(DA(date(2020, 11, 17)))\r\njson_output = ds.to_json()\r\nprint(f'json_output with str(DA..) - invalid DICOM {json_output}')\r\n\r\n# 3. JSON serialization with date object fails\r\nds = Dataset()\r\nds.ContentDate = DA(date(2020, 11, 17))\r\n\r\n# Exception on this line: TypeError: Object of type DA is not JSON serializable\r\njson_output = ds.to_json()\r\n\r\n```\r\n\r\nI believe that all three approaches should work - but only the first is valid. The method signature on DA's `__new__` method accepts datetime.date objects. \r\n\r\n**Your environment**\r\n```\r\nmodule | version\r\n------ | -------\r\nplatform | macOS-10.15.7-x86_64-i386-64bit\r\nPython | 3.8.6 (default, Oct 8 2020, 14:06:32) [Clang 12.0.0 (clang-1200.0.32.2)]\r\npydicom | 2.1.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.19.4\r\nPIL | 8.0.1\r\n```\r\n\r\n\n", "hints_text": "Thanks for this - I agree that the print output should be consistent, and that the class should work correctly for json.\r\n\nI think that the problem is in the _DateTimeBase method __str__ - there is no 'original_string' so it's calling the __str__ method if the object's superclass and the default for datetime.date puts in the hyphens. The 'DT' class has a similar problem - it's not formatting the time the DICOM way.\nThe easiest way to handle this is probably to add an `original_string` attribute to `DA`, `TM` and `DT`, and set this attribute to the canonical DICOM representation if initialized with a date or time. This would only change the behavior of `__str__` and `__repr__` for these types, and I think that this is indeed the expected behavior.\r\n@darcymason , what do you think? This would actually be a small change, that could make it into the next release.", "created_at": "2021-04-26T19:16:35Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::TestTM::test_str", "pydicom/tests/test_valuerep.py::TestDT::test_str", "pydicom/tests/test_valuerep.py::TestDA::test_str"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_empty_value", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_filename", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of_dataset", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding", "pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestTM::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDT::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[3.14159265358979]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[-1234.456e78]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E-5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E+5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[+1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[42", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[nan]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[3.141592653589793]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1,000]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[127.0.0.1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1.e]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.0-1.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.0-0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.0--0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.123-0.123]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.321--0.321]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1e-05-1e-05]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[3.141592653589793-3.14159265358979]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-3.141592653589793--3.1415926535898]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[5.385940192876374e-07-5.3859401929e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-5.385940192876374e-07--5.385940193e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[12342534378.125532-12342534378.1255]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[64070869985876.78-64070869985876.8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.7976931348623157e+308-1.797693135e+308]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_wrong_type", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_length", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat_auto_format", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-nan]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan2]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf1]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_repr", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val4]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val5]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val6]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val7]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal_auto_format", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_veterinary", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator_from_bytes", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time", "pydicom/tests/test_valuerep.py::test_person_name_unicode_warns"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-965", "base_commit": "ee775c8a137cd8e0b69b46dc24c23648c31fe34c", "patch": "diff --git a/pydicom/config.py b/pydicom/config.py\n--- a/pydicom/config.py\n+++ b/pydicom/config.py\n@@ -87,9 +87,10 @@ def DS_decimal(use_Decimal_boolean=True):\n \"\"\"\n \n use_none_as_empty_text_VR_value = False\n-\"\"\" If ``True``, the value of decoded empty data element is always ``None``.\n-If ``False`` (the default), the value of an empty data element with\n-a text VR is an empty string, for all other VRs it is also ``None``.\n+\"\"\" If ``True``, the value of a decoded empty data element with\n+a text VR is ``None``, otherwise (the default), it is is an empty string.\n+For all other VRs the behavior does not change - the value is en empty\n+list for VR 'SQ' and ``None`` for all other VRs.\n Note that the default of this value will change to ``True`` in version 2.0.\n \"\"\"\n \ndiff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -48,10 +48,12 @@ def empty_value_for_VR(VR, raw=False):\n \n The behavior of this property depends on the setting of\n :attr:`config.use_none_as_empty_value`. If that is set to ``True``,\n- an empty value is always represented by ``None``, otherwise it depends\n- on `VR`. For text VRs (this includes 'AE', 'AS', 'CS', 'DA', 'DT', 'LO',\n- 'LT', 'PN', 'SH', 'ST', 'TM', 'UC', 'UI', 'UR' and 'UT') an empty string\n- is used as empty value representation, for all other VRs, ``None``.\n+ an empty value is represented by ``None`` (except for VR 'SQ'), otherwise\n+ it depends on `VR`. For text VRs (this includes 'AE', 'AS', 'CS', 'DA',\n+ 'DT', 'LO', 'LT', 'PN', 'SH', 'ST', 'TM', 'UC', 'UI', 'UR' and 'UT') an\n+ empty string is used as empty value representation, for all other VRs\n+ except 'SQ', ``None``. For empty sequence values (VR 'SQ') an empty list\n+ is used in all cases.\n Note that this is used only if decoding the element - it is always\n possible to set the value to another empty value representation,\n which will be preserved during the element object lifetime.\n@@ -67,10 +69,12 @@ def empty_value_for_VR(VR, raw=False):\n \n Returns\n -------\n- str or bytes or None\n+ str or bytes or None or list\n The value a data element with `VR` is assigned on decoding\n if it is empty.\n \"\"\"\n+ if VR == 'SQ':\n+ return []\n if config.use_none_as_empty_text_VR_value:\n return None\n if VR in ('AE', 'AS', 'CS', 'DA', 'DT', 'LO', 'LT',\n", "test_patch": "diff --git a/pydicom/tests/test_dataelem.py b/pydicom/tests/test_dataelem.py\n--- a/pydicom/tests/test_dataelem.py\n+++ b/pydicom/tests/test_dataelem.py\n@@ -503,6 +503,23 @@ def check_empty_binary_element(value):\n check_empty_binary_element(MultiValue(int, []))\n check_empty_binary_element(None)\n \n+ def test_empty_sequence_is_handled_as_array(self):\n+ ds = Dataset()\n+ ds.AcquisitionContextSequence = []\n+ elem = ds['AcquisitionContextSequence']\n+ assert bool(elem.value) is False\n+ assert 0 == elem.VM\n+ assert elem.value == []\n+\n+ fp = DicomBytesIO()\n+ fp.is_little_endian = True\n+ fp.is_implicit_VR = True\n+ filewriter.write_dataset(fp, ds)\n+ ds_read = dcmread(fp, force=True)\n+ elem = ds_read['AcquisitionContextSequence']\n+ assert 0 == elem.VM\n+ assert elem.value == []\n+\n \n class TestRawDataElement(object):\n \"\"\"Tests for dataelem.RawDataElement.\"\"\"\n", "problem_statement": "Empty data elements with value representation SQ are set to None\n**Describe the bug**\r\nIn the current `master`, empty data elements are not read correctly from files. The attribute value is set to `None` instead of `[]`.\r\n\r\n**Expected behavior**\r\nCreate empty list `[]` for empty sequence, i.e., a sequence with zero items.\r\n\r\n**Steps To Reproduce**\r\n```python\r\nimport pydicom\r\nds = pydicom.Dataset()\r\nds.AcquisitionContextSequence = []\r\nprint(ds)\r\nds.is_little_endian = True\r\nds.is_implicit_VR = True\r\nds.save_as('/tmp/test.dcm')\r\n\r\nreloaded_ds = pydicom.dcmread('/tmp/test.dcm', force=True)\r\nprint(reloaded_ds)\r\n```\r\nThis prints:\r\n```\r\n(0040, 0555) Acquisition Context Sequence 0 item(s) ----\r\n...\r\nTypeError: With tag (0040, 0555) got exception: object of type 'NoneType' has no len()\r\nTraceback (most recent call last):\r\n File \"/private/tmp/pydicom/pydicom/tag.py\", line 30, in tag_in_exception\r\n yield\r\n File \"/private/tmp/pydicom/pydicom/dataset.py\", line 1599, in _pretty_str\r\n len(data_element.value)))\r\nTypeError: object of type 'NoneType' has no len()\r\n```\r\n\r\n**Your environment**\r\n```\r\nDarwin-18.6.0-x86_64-i386-64bit\r\nPython 3.7.3 (default, Mar 27 2019, 09:23:15)\r\n[Clang 10.0.1 (clang-1001.0.46.3)]\r\npydicom 1.4.0.dev0\r\n```\n", "hints_text": "", "created_at": "2019-11-01T14:43:06Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_dataelem.py::TestDataElement::test_empty_sequence_is_handled_as_array"], "PASS_TO_PASS": ["pydicom/tests/test_dataelem.py::TestDataElement::test_VM_1", "pydicom/tests/test_dataelem.py::TestDataElement::test_VM_2", "pydicom/tests/test_dataelem.py::TestDataElement::test_DSFloat_conversion", "pydicom/tests/test_dataelem.py::TestDataElement::test_backslash", "pydicom/tests/test_dataelem.py::TestDataElement::test_UID", "pydicom/tests/test_dataelem.py::TestDataElement::test_keyword", "pydicom/tests/test_dataelem.py::TestDataElement::test_retired", "pydicom/tests/test_dataelem.py::TestDataElement::test_description_group_length", "pydicom/tests/test_dataelem.py::TestDataElement::test_description_unknown_private", "pydicom/tests/test_dataelem.py::TestDataElement::test_description_unknown", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_standard_element", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_private_element", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_sequence_element", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_not_rlement", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_inheritance", "pydicom/tests/test_dataelem.py::TestDataElement::test_equality_class_members", "pydicom/tests/test_dataelem.py::TestDataElement::test_inequality_standard", "pydicom/tests/test_dataelem.py::TestDataElement::test_inequality_sequence", "pydicom/tests/test_dataelem.py::TestDataElement::test_hash", "pydicom/tests/test_dataelem.py::TestDataElement::test_repeater_str", "pydicom/tests/test_dataelem.py::TestDataElement::test_str_no_vr", "pydicom/tests/test_dataelem.py::TestDataElement::test_repr_seq", "pydicom/tests/test_dataelem.py::TestDataElement::test_getitem_raises", "pydicom/tests/test_dataelem.py::TestDataElement::test_repval_large_elem", "pydicom/tests/test_dataelem.py::TestDataElement::test_repval_large_vm", "pydicom/tests/test_dataelem.py::TestDataElement::test_repval_strange_type", "pydicom/tests/test_dataelem.py::TestDataElement::test_private_tag_in_repeater_range", "pydicom/tests/test_dataelem.py::TestDataElement::test_private_repeater_tag", "pydicom/tests/test_dataelem.py::TestDataElement::test_known_tags_with_UN_VR", "pydicom/tests/test_dataelem.py::TestDataElement::test_unknown_tags_with_UN_VR", "pydicom/tests/test_dataelem.py::TestDataElement::test_tag_with_long_value_UN_VR", "pydicom/tests/test_dataelem.py::TestDataElement::test_empty_text_values[True-None]", "pydicom/tests/test_dataelem.py::TestDataElement::test_empty_text_values[False-]", "pydicom/tests/test_dataelem.py::TestDataElement::test_empty_binary_values", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_key_error", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_valid_tag", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_data_element_without_encoding", "pydicom/tests/test_dataelem.py::TestRawDataElement::test_unknown_vr"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1375", "base_commit": "c14bf96040e4cc930db890638b9f190d4ede0a21", "patch": "diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -2,23 +2,19 @@\n \"\"\"Special classes for DICOM value representations (VR)\"\"\"\n \n import datetime\n-from decimal import Decimal\n-from math import floor, isfinite, log10\n-import platform\n import re\n import sys\n+import warnings\n+from decimal import Decimal\n+from math import floor, isfinite, log10\n+from typing import Sequence as SequenceType\n from typing import (\n- TypeVar, Type, Tuple, Optional, List, Dict, Union, Any, Generator, AnyStr,\n- Callable, Iterator, overload\n+ TypeVar, Type, Tuple, Optional, List, Dict, Union, Any, Generator, Callable\n )\n-from typing import Sequence as SequenceType\n-import warnings\n \n # don't import datetime_conversion directly\n from pydicom import config\n from pydicom.multival import MultiValue\n-from pydicom.uid import UID\n-\n \n # Types\n _T = TypeVar('_T')\n@@ -84,23 +80,23 @@ class DA(_DateTimeBase, datetime.date):\n \n Note that the :class:`datetime.date` base class is immutable.\n \"\"\"\n- def __new__(\n- cls: Type[_DA], val: Union[None, str, _DA, datetime.date]\n- ) -> Optional[_DA]:\n+ def __new__(cls: Type[_DA], *args, **kwargs) -> Optional[_DA]:\n \"\"\"Create an instance of DA object.\n \n Raise an exception if the string cannot be parsed or the argument\n is otherwise incompatible.\n \n- Parameters\n- ----------\n- val : str\n- A string conformant to the DA definition in the DICOM Standard,\n- Part 5, :dcm:`Table 6.2-1<part05/sect_6.2.html#table_6.2-1>`.\n+ The arguments (``*args`` and ``**kwargs``) are either the ones\n+ inherited from :class:`datetime.date`, or the first argument is\n+ a string conformant to the DA definition in the DICOM Standard,\n+ Part 5, :dcm:`Table 6.2-1<part05/sect_6.2.html#table_6.2-1>`,\n+ or it is a :class:`datetime.date` object, or an object of type\n+ :class:`~pydicom.valuerep.DA`.\n \"\"\"\n- if val is None:\n+ if not args or args[0] is None:\n return None\n \n+ val = args[0]\n if isinstance(val, str):\n if val.strip() == '':\n return None # empty date\n@@ -123,14 +119,15 @@ def __new__(\n return super().__new__(cls, val.year, val.month, val.day)\n \n try:\n- return super().__new__(cls, val)\n+ return super().__new__(cls, *args, **kwargs)\n except Exception as exc:\n raise ValueError(\n f\"Unable to convert '{val}' to 'DA' object\"\n ) from exc\n \n- def __init__(self, val: Union[str, _DA, datetime.date]) -> None:\n+ def __init__(self, *args, **kwargs) -> None:\n \"\"\"Create a new **DA** element value.\"\"\"\n+ val = args[0]\n if isinstance(val, str):\n self.original_string = val\n elif isinstance(val, DA) and hasattr(val, 'original_string'):\n@@ -171,23 +168,23 @@ def _utc_offset(value: str) -> datetime.timezone:\n name=value\n )\n \n- def __new__(\n- cls: Type[_DT], val: Union[None, str, _DT, datetime.datetime]\n- ) -> Optional[_DT]:\n+ def __new__(cls: Type[_DT], *args, **kwargs) -> Optional[_DT]:\n \"\"\"Create an instance of DT object.\n \n Raise an exception if the string cannot be parsed or the argument\n is otherwise incompatible.\n \n- Parameters\n- ----------\n- val : str\n- A string conformant to the DT definition in the DICOM Standard,\n- Part 5, :dcm:`Table 6.2-1<part05/sect_6.2.html#table_6.2-1>`.\n+ The arguments (``*args`` and ``**kwargs``) are either the ones\n+ inherited from :class:`datetime.datetime`, or the first argument is\n+ a string conformant to the DT definition in the DICOM Standard,\n+ Part 5, :dcm:`Table 6.2-1<part05/sect_6.2.html#table_6.2-1>`,\n+ or it is a :class:`datetime.datetime` object, or an object of type\n+ :class:`~pydicom.valuerep.DT`.\n \"\"\"\n- if val is None:\n+ if not args or args[0] is None:\n return None\n \n+ val = args[0]\n if isinstance(val, str):\n if val.strip() == '':\n return None\n@@ -233,13 +230,15 @@ def __new__(\n )\n \n try:\n- return super().__new__(cls, val)\n+ return super().__new__(cls, *args, **kwargs)\n except Exception as exc:\n raise ValueError(\n f\"Unable to convert '{val}' to 'DT' object\"\n ) from exc\n \n- def __init__(self, val: Union[str, _DT, datetime.datetime]) -> None:\n+ def __init__(self, *args, **kwargs) -> None:\n+ \"\"\"Create a new **DT** element value.\"\"\"\n+ val = args[0]\n if isinstance(val, str):\n self.original_string = val\n elif isinstance(val, DT) and hasattr(val, 'original_string'):\n@@ -274,23 +273,23 @@ class TM(_DateTimeBase, datetime.time):\n r\"(?(7)(\\.(?P<ms>([0-9]{1,6})?))?))$\"\n )\n \n- def __new__(\n- cls: Type[_TM], val: Union[None, str, _TM, datetime.time]\n- ) -> Optional[_TM]:\n+ def __new__(cls: Type[_TM], *args, **kwargs) -> Optional[_TM]:\n \"\"\"Create an instance of TM object from a string.\n \n Raise an exception if the string cannot be parsed or the argument\n is otherwise incompatible.\n \n- Parameters\n- ----------\n- val : str\n- A string conformant to the TM definition in the DICOM Standard,\n- Part 5, :dcm:`Table 6.2-1<part05/sect_6.2.html#table_6.2-1>`.\n+ The arguments (``*args`` and ``**kwargs``) are either the ones\n+ inherited from :class:`datetime.time`, or the first argument is\n+ a string conformant to the TM definition in the DICOM Standard,\n+ Part 5, :dcm:`Table 6.2-1<part05/sect_6.2.html#table_6.2-1>`,\n+ or it is a :class:`datetime.time` object, or an object of type\n+ :class:`~pydicom.valuerep.TM`.\n \"\"\"\n- if val is None:\n+ if not args or args[0] is None:\n return None\n \n+ val = args[0]\n if isinstance(val, str):\n if val.strip() == '':\n return None # empty time\n@@ -325,13 +324,15 @@ def __new__(\n )\n \n try:\n- return super().__new__(cls, val)\n+ return super().__new__(cls, *args, **kwargs)\n except Exception as exc:\n raise ValueError(\n f\"Unable to convert '{val}' to 'TM' object\"\n ) from exc\n \n- def __init__(self, val: Union[str, _TM, datetime.time]) -> None:\n+ def __init__(self, *args, **kwargs) -> None:\n+ super().__init__()\n+ val = args[0]\n if isinstance(val, str):\n self.original_string = val\n elif isinstance(val, TM) and hasattr(val, 'original_string'):\n@@ -344,16 +345,6 @@ def __init__(self, val: Union[str, _TM, datetime.time]) -> None:\n if val.microsecond > 0:\n self.original_string += f\".{val.microsecond:06}\"\n \n- if platform.python_implementation() == \"PyPy\":\n- # Workaround for CPython/PyPy bug in time.__reduce_ex__()\n- # caused by returning (time, ...) rather than (self.__class__, ...)\n- def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]:\n- return (\n- self.__class__,\n- super()._getstate(protocol),\n- self.__getstate__()\n- )\n-\n \n # Regex to match strings that represent valid DICOM decimal strings (DS)\n _DS_REGEX = re.compile(r'\\s*[\\+\\-]?\\d+(\\.\\d+)?([eE][\\+\\-]?\\d+)?\\s*$')\n", "test_patch": "diff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -5,10 +5,7 @@\n import copy\n from datetime import datetime, date, time, timedelta, timezone\n from decimal import Decimal\n-try:\n- import cPickle as pickle\n-except ImportError:\n- import pickle\n+import pickle\n import math\n import sys\n from typing import Union\n@@ -17,7 +14,6 @@\n from pydicom.values import convert_value\n \n import pydicom\n-import platform\n from pydicom import config\n from pydicom import valuerep\n from pydicom.data import get_testdata_file\n@@ -56,68 +52,70 @@ class TestTM:\n \"\"\"Unit tests for pickling TM\"\"\"\n def test_pickling(self):\n # Check that a pickled TM is read back properly\n- x = pydicom.valuerep.TM(\"212223\")\n- assert time(21, 22, 23) == x\n- x.original_string = \"hello\"\n- assert \"hello\" == x.original_string\n- assert time(21, 22, 23) == x\n- data1_string = pickle.dumps(x)\n- x2 = pickle.loads(data1_string)\n- assert x == x2\n- assert x.original_string == x2.original_string\n- assert str(x) == str(x2)\n-\n- def test_str(self):\n- \"\"\"Test str(TM).\"\"\"\n- assert \"212223.1234\" == str(pydicom.valuerep.TM(\"212223.1234\"))\n- assert \"212223\" == str(pydicom.valuerep.TM(\"212223\"))\n- assert \"212223\" == str(pydicom.valuerep.TM(\"212223\"))\n- assert \"2122\" == str(pydicom.valuerep.TM(\"2122\"))\n- assert \"21\" == str(pydicom.valuerep.TM(\"21\"))\n- assert \"212223\" == str(pydicom.valuerep.TM(time(21, 22, 23)))\n- assert \"212223.000024\" == str(\n- pydicom.valuerep.TM(time(21, 22, 23, 24)))\n- assert \"010203\" == str(pydicom.valuerep.TM(time(1, 2, 3)))\n+ tm = pydicom.valuerep.TM(\"212223\")\n+ assert tm == time(21, 22, 23)\n+ assert tm.original_string == \"212223\"\n+ assert tm == time(21, 22, 23)\n+ loaded_tm = pickle.loads(pickle.dumps(tm))\n+ assert loaded_tm == tm\n+ assert loaded_tm.original_string == tm.original_string\n+ assert str(loaded_tm) == str(tm)\n+\n+ def test_pickling_tm_from_time(self):\n+ tm = pydicom.valuerep.TM(time(21, 22, 23))\n+ assert tm.original_string == \"212223\"\n+ time_string = pickle.dumps(tm)\n+ loaded_tm = pickle.loads(time_string)\n+ assert loaded_tm == tm\n+ assert loaded_tm.original_string == tm.original_string\n+ assert str(loaded_tm) == str(tm)\n+\n+ def test_str_and_repr(self):\n+ assert str(pydicom.valuerep.TM(\"212223.1234\")) == \"212223.1234\"\n+ assert repr(pydicom.valuerep.TM(\"212223.1234\")) == '\"212223.1234\"'\n+ assert str(pydicom.valuerep.TM(\"212223\")) == \"212223\"\n+ assert repr(pydicom.valuerep.TM(\"212223\")) == '\"212223\"'\n+ assert str(pydicom.valuerep.TM(\"2122\")) == \"2122\"\n+ assert repr(pydicom.valuerep.TM(\"2122\")) == '\"2122\"'\n+ assert str(pydicom.valuerep.TM(\"21\")) == \"21\"\n+ assert str(pydicom.valuerep.TM(time(21, 22, 23))) == \"212223\"\n+ assert str(pydicom.valuerep.TM(\n+ time(21, 22, 23, 24))) == \"212223.000024\"\n+ assert str(pydicom.valuerep.TM(time(1, 2, 3))) == \"010203\"\n+ assert repr(pydicom.valuerep.TM(time(1, 2, 3))) == '\"010203\"'\n \n def test_new_empty_str(self):\n \"\"\"Test converting an empty string.\"\"\"\n- x = pydicom.valuerep.TM('')\n- assert x is None\n+ assert pydicom.valuerep.TM('') is None\n \n def test_new_str_conversion(self):\n \"\"\"Test converting strings to times.\"\"\"\n- x = pydicom.valuerep.TM('00')\n- assert \"00\" == str(x)\n- assert time(0, 0, 0) == x\n- x = pydicom.valuerep.TM('23')\n- assert \"23\" == str(x)\n- assert time(23, 0, 0) == x\n+ tm = pydicom.valuerep.TM('00')\n+ assert tm == time(0, 0, 0)\n+ tm = pydicom.valuerep.TM('23')\n+ assert tm == time(23, 0, 0)\n msg = r\"Unable to convert non-conformant value '24' to 'TM' object\"\n with pytest.raises(ValueError, match=msg):\n pydicom.valuerep.TM('24')\n \n- x = pydicom.valuerep.TM('0000')\n- assert \"0000\" == str(x)\n- assert time(0, 0, 0) == x\n- x = pydicom.valuerep.TM('2359')\n- assert \"2359\" == str(x)\n- assert time(23, 59, 0) == x\n+ tm = pydicom.valuerep.TM('0000')\n+ assert tm == time(0, 0, 0)\n+ tm = pydicom.valuerep.TM('2359')\n+ assert tm == time(23, 59, 0)\n msg = r\"Unable to convert non-conformant value '2360' to 'TM' object\"\n with pytest.raises(ValueError, match=msg):\n pydicom.valuerep.TM('2360')\n \n- x = pydicom.valuerep.TM('000000')\n- assert \"000000\" == str(x)\n- assert time(0, 0, 0) == x\n+ tm = pydicom.valuerep.TM('000000')\n+ assert tm == time(0, 0, 0)\n # Valid DICOM TM seconds range is 0..60, but time is 0..59\n msg = (\n r\"'datetime.time' doesn't allow a value of '60' for the \"\n r\"seconds component, changing to '59'\"\n )\n with pytest.warns(UserWarning, match=msg):\n- x = pydicom.valuerep.TM('235960')\n- assert \"235960\" == str(x)\n- assert time(23, 59, 59) == x\n+ tm = pydicom.valuerep.TM('235960')\n+ assert tm == time(23, 59, 59)\n \n msg = r\"Unable to convert non-conformant value '235' to 'TM' object\"\n with pytest.raises(ValueError, match=msg):\n@@ -126,45 +124,101 @@ def test_new_str_conversion(self):\n def test_new_obj_conversion(self):\n \"\"\"Test other conversion attempts.\"\"\"\n assert pydicom.valuerep.TM(None) is None\n- x = pydicom.valuerep.TM(\"010203.123456\")\n- assert time(1, 2, 3, 123456) == pydicom.valuerep.TM(x)\n- assert x == pydicom.valuerep.TM(x)\n- x = pydicom.valuerep.TM(time(1, 2, 3))\n- assert isinstance(x, pydicom.valuerep.TM)\n- assert time(1, 2, 3) == x\n+ tm = pydicom.valuerep.TM(\"010203.123456\")\n+ assert pydicom.valuerep.TM(tm) == time(1, 2, 3, 123456)\n+ assert tm == pydicom.valuerep.TM(tm)\n+ tm = pydicom.valuerep.TM(time(1, 2, 3))\n+ assert isinstance(tm, pydicom.valuerep.TM)\n+ assert tm == time(1, 2, 3)\n \n msg = r\"Unable to convert '123456' to 'TM' object\"\n with pytest.raises(ValueError, match=msg):\n pydicom.valuerep.TM(123456)\n \n+ def test_comparison(self):\n+ tm = pydicom.valuerep.TM(\"010203.123456\")\n+ tm_object = time(1, 2, 3, 123456)\n+ assert tm == tm\n+ assert tm != 1\n+ assert tm == tm_object\n+ assert tm_object == tm\n+ assert hash(tm) == hash(tm_object)\n+ assert tm == pydicom.valuerep.TM(tm_object)\n+ assert tm < time(1, 2, 3, 123457)\n+ assert tm != time(1, 2, 3, 123457)\n+ assert tm < pydicom.valuerep.TM(time(1, 2, 3, 123457))\n+ assert tm <= time(1, 2, 3, 123457)\n+ assert tm <= tm_object\n+ assert tm > time(1, 2, 3)\n+ assert tm > pydicom.valuerep.TM(time(1, 2, 3))\n+ assert tm >= time(1, 2, 3)\n+ assert time(1, 2, 3, 123457) > tm\n+ assert tm_object >= tm\n+ assert time(1, 2, 3) < tm\n+ with pytest.raises(TypeError):\n+ tm > 5\n+\n+ def test_time_behavior(self):\n+ \"\"\"Test that TM behaves like time.\"\"\"\n+ tm = pydicom.valuerep.TM(\"010203.123456\")\n+ assert tm.hour == 1\n+ assert tm.second == 3\n+ assert tm.microsecond == 123456\n+ assert tm.replace(hour=23) == time(23, 2, 3, 123456)\n+ assert \"minute\" in dir(tm)\n+ assert \"original_string\" in dir(tm)\n+\n \n class TestDT:\n \"\"\"Unit tests for pickling DT\"\"\"\n def test_pickling(self):\n # Check that a pickled DT is read back properly\n- x = pydicom.valuerep.DT(\"19111213212123\")\n- assert datetime(1911, 12, 13, 21, 21, 23) == x\n- x.original_string = \"hello\"\n- data1_string = pickle.dumps(x)\n- x2 = pickle.loads(data1_string)\n- assert x == x2\n- assert x.original_string == x2.original_string\n- assert str(x) == str(x2)\n+ dt = pydicom.valuerep.DT(\"19111213212123\")\n+ assert dt == datetime(1911, 12, 13, 21, 21, 23)\n+ data1_string = pickle.dumps(dt)\n+ loaded_dt = pickle.loads(data1_string)\n+ assert loaded_dt == dt\n+ assert dt.original_string == loaded_dt.original_string\n+ assert str(loaded_dt) == str(dt)\n+\n+ def test_pickling_with_timezone(self):\n+ dt = pydicom.valuerep.DT(\"19111213212123-0630\")\n+ loaded_dt = pickle.loads(pickle.dumps(dt))\n+ assert loaded_dt == dt\n+ assert loaded_dt.original_string == dt.original_string\n+ assert str(loaded_dt) == str(dt)\n+\n+ def test_pickling_dt_from_datetime(self):\n+ dt = pydicom.valuerep.DT(datetime(2222, 11, 23, 1, 2, 3, 4))\n+ assert dt.original_string == \"22221123010203.000004\"\n+ loaded_dt = pickle.loads(pickle.dumps(dt))\n+ assert loaded_dt == dt\n+ assert loaded_dt.original_string == dt.original_string\n+ assert str(dt) == str(loaded_dt)\n+\n+ def test_pickling_dt_from_datetime_with_timezone(self):\n+ tz_info = timezone(timedelta(seconds=-23400), '-0630')\n+ dt_object = datetime(2022, 12, 31, 23, 59, 59, 42, tzinfo=tz_info)\n+ dt = pydicom.valuerep.DT(dt_object)\n+ assert dt.original_string == \"20221231235959.000042-0630\"\n+ loaded_dt = pickle.loads(pickle.dumps(dt))\n+ assert dt == loaded_dt\n+ assert dt.original_string == loaded_dt.original_string\n+ assert str(dt) == str(loaded_dt)\n \n def test_new_empty_str(self):\n \"\"\"Test converting an empty string.\"\"\"\n- x = pydicom.valuerep.DT('')\n- assert x is None\n+ assert pydicom.valuerep.DT('') is None\n \n def test_new_obj_conversion(self):\n \"\"\"Test other conversion attempts.\"\"\"\n assert pydicom.valuerep.DT(None) is None\n- x = pydicom.valuerep.DT(\"10010203\")\n- assert datetime(1001, 2, 3) == pydicom.valuerep.DT(x)\n- assert x == pydicom.valuerep.DT(x)\n- x = pydicom.valuerep.DT(datetime(1001, 2, 3))\n- assert isinstance(x, pydicom.valuerep.DT)\n- assert datetime(1001, 2, 3) == x\n+ dt = pydicom.valuerep.DT(\"10010203\")\n+ assert pydicom.valuerep.DT(dt) == datetime(1001, 2, 3)\n+ assert dt == pydicom.valuerep.DT(dt)\n+ dt = pydicom.valuerep.DT(datetime(1001, 2, 3))\n+ assert isinstance(dt, pydicom.valuerep.DT)\n+ assert dt == datetime(1001, 2, 3)\n \n msg = r\"Unable to convert '123456' to 'DT' object\"\n with pytest.raises(ValueError, match=msg):\n@@ -178,9 +232,9 @@ def test_new_str_conversion(self):\n r\"seconds component, changing to '59'\"\n )\n with pytest.warns(UserWarning, match=msg):\n- x = pydicom.valuerep.DT('20010101235960')\n- assert \"20010101235960\" == str(x)\n- assert datetime(2001, 1, 1, 23, 59, 59) == x\n+ dt = pydicom.valuerep.DT('20010101235960')\n+ assert str(dt) == \"20010101235960\"\n+ assert dt == datetime(2001, 1, 1, 23, 59, 59)\n \n msg = (\n r\"Unable to convert non-conformant value 'a2000,00,00' to 'DT' \"\n@@ -189,17 +243,61 @@ def test_new_str_conversion(self):\n with pytest.raises(ValueError, match=msg):\n pydicom.valuerep.DT(\"a2000,00,00\")\n \n- def test_str(self):\n+ def test_str_and_repr(self):\n dt = datetime(1911, 12, 13, 21, 21, 23)\n- assert \"19111213212123\" == str(pydicom.valuerep.DT(dt))\n- assert \"19111213212123\" == str(pydicom.valuerep.DT(\"19111213212123\"))\n- assert \"1001.02.03\" == str(pydicom.valuerep.DA(\"1001.02.03\"))\n+ assert str(pydicom.valuerep.DT(dt)) == \"19111213212123\"\n+ assert repr(pydicom.valuerep.DT(dt)) == '\"19111213212123\"'\n+ assert str(pydicom.valuerep.DT(\"19111213212123\")) == \"19111213212123\"\n+ assert str(pydicom.valuerep.DA(\"1001.02.03\")) == \"1001.02.03\"\n+ assert repr(pydicom.valuerep.DA(\"1001.02.03\")) == '\"1001.02.03\"'\n tz_info = timezone(timedelta(seconds=21600), '+0600')\n dt = datetime(2022, 1, 2, 8, 9, 7, 123456, tzinfo=tz_info)\n- assert \"20220102080907.123456+0600\" == str(pydicom.valuerep.DT(dt))\n+ assert str(pydicom.valuerep.DT(dt)) == \"20220102080907.123456+0600\"\n+ assert repr(pydicom.valuerep.DT(dt)) == '\"20220102080907.123456+0600\"'\n tz_info = timezone(timedelta(seconds=-23400), '-0630')\n dt = datetime(2022, 12, 31, 23, 59, 59, 42, tzinfo=tz_info)\n- assert \"20221231235959.000042-0630\" == str(pydicom.valuerep.DT(dt))\n+ assert str(pydicom.valuerep.DT(dt)) == \"20221231235959.000042-0630\"\n+ assert repr(pydicom.valuerep.DT(dt)) == '\"20221231235959.000042-0630\"'\n+\n+ def test_comparison(self):\n+ dt = pydicom.valuerep.DT(\"19111213212123\")\n+ dt_object = datetime(1911, 12, 13, 21, 21, 23)\n+ assert dt == dt\n+ assert dt != 1\n+ assert dt == dt_object\n+ assert dt_object == dt\n+ assert hash(dt) == hash(dt_object)\n+ assert dt == pydicom.valuerep.DT(dt_object)\n+ assert dt < datetime(1911, 12, 13, 21, 21, 23, 123)\n+ assert dt != datetime(1911, 12, 13, 21, 21, 24)\n+ assert dt < pydicom.valuerep.DT(datetime(1911, 12, 13, 21, 21, 24))\n+ assert dt <= datetime(1911, 12, 13, 21, 21, 23)\n+ assert dt <= dt_object\n+ assert dt > datetime(1911, 12, 13, 21, 21, 22)\n+ assert dt > pydicom.valuerep.DT(datetime(1911, 12, 13, 21, 21, 22))\n+ assert dt >= datetime(1911, 12, 13, 21, 21, 23)\n+ assert datetime(1911, 12, 13, 21, 21, 24) > dt\n+ assert dt_object >= dt\n+ assert datetime(1911, 12, 13, 21, 21, 22) < dt\n+ with pytest.raises(TypeError):\n+ dt > 5\n+\n+ def test_datetime_behavior(self):\n+ \"\"\"Test that DT behaves like datetime.\"\"\"\n+ tz_info = timezone(timedelta(seconds=-23400), '-0630')\n+ dt_object = datetime(2022, 12, 31, 23, 59, 59, 42, tzinfo=tz_info)\n+ dt = pydicom.valuerep.DT(dt_object)\n+ assert dt == dt_object\n+ assert dt_object == dt\n+ assert dt.year == 2022\n+ assert dt.month == 12\n+ assert dt.hour == 23\n+ assert dt.second == 59\n+ assert dt.microsecond == 42\n+ assert dt.tzinfo == tz_info\n+ assert dt.today().date() == dt_object.today().date()\n+ assert \"hour\" in dir(dt)\n+ assert \"original_string\" in dir(dt)\n \n \n class TestDA:\n@@ -229,10 +327,48 @@ def test_new_obj_conversion(self):\n with pytest.raises(ValueError, match=msg):\n pydicom.valuerep.DA(123456)\n \n- def test_str(self):\n- assert \"10010203\" == str(pydicom.valuerep.DA(date(1001, 2, 3)))\n- assert \"10010203\" == str(pydicom.valuerep.DA(\"10010203\"))\n- assert \"1001.02.03\" == str(pydicom.valuerep.DA(\"1001.02.03\"))\n+ def test_str_and_repr(self):\n+ assert str(pydicom.valuerep.DA(date(1001, 2, 3))) == \"10010203\"\n+ assert repr(pydicom.valuerep.DA(date(1001, 2, 3))) == '\"10010203\"'\n+ assert str(pydicom.valuerep.DA(\"10010203\")) == \"10010203\"\n+ assert repr(pydicom.valuerep.DA(\"10010203\")) == '\"10010203\"'\n+ assert str(pydicom.valuerep.DA(\"1001.02.03\")) == \"1001.02.03\"\n+ assert repr(pydicom.valuerep.DA(\"1001.02.03\")) == '\"1001.02.03\"'\n+\n+ def test_comparison(self):\n+ da = pydicom.valuerep.DA(\"19111213\")\n+ da_object = date(1911, 12, 13)\n+ assert da == da\n+ assert da != 1\n+ assert da == da_object\n+ assert hash(da) == hash(da_object)\n+ assert da_object == da\n+ assert da == pydicom.valuerep.DA(da_object)\n+ assert da < date(1911, 12, 14)\n+ assert da != date(1901, 12, 13)\n+ assert da < pydicom.valuerep.DA(date(1912, 12, 13))\n+ assert da <= date(1911, 12, 13)\n+ assert da <= da_object\n+ assert da > date(1911, 12, 12)\n+ assert da > pydicom.valuerep.DA(date(1911, 12, 12))\n+ assert da >= date(1911, 12, 13)\n+ assert date(1911, 12, 14) > da\n+ assert da_object >= da\n+ assert date(1911, 12, 12) < da\n+ with pytest.raises(TypeError):\n+ da > 5\n+\n+ def test_date_behavior(self):\n+ da = pydicom.valuerep.DA(\"10010203\")\n+ da_object = date(1001, 2, 3)\n+ assert da == da_object\n+ assert da_object == da\n+ assert da.year == 1001\n+ assert da.month == 2\n+ assert da.day == 3\n+ assert da.today() == da_object.today()\n+ assert \"day\" in dir(da)\n+ assert \"original_string\" in dir(da)\n \n \n class TestIsValidDS:\n@@ -338,8 +474,8 @@ def test_invalid(self, val: float):\n def test_wrong_type(self):\n \"\"\"Test calling with a string raises an error\"\"\"\n with pytest.raises(\n- TypeError,\n- match=\"'val' must be of type float or decimal.Decimal\"\n+ TypeError,\n+ match=\"'val' must be of type float or decimal.Decimal\"\n ):\n pydicom.valuerep.format_number_as_ds('1.0')\n \n@@ -470,9 +606,9 @@ def test_DSfloat_auto_format(self):\n ]\n )\n def test_enforce_valid_values_value(\n- self,\n- val: Union[float, str],\n- enforce_valid_true_fixture\n+ self,\n+ val: Union[float, str],\n+ enforce_valid_true_fixture\n ):\n \"\"\"Test that errors are raised when value is invalid.\"\"\"\n with pytest.raises(ValueError):\n@@ -568,9 +704,9 @@ def test_auto_format_invalid_string(self, enforce_valid_both_fixture):\n ]\n )\n def test_enforce_valid_values_value(\n- self,\n- val: Union[Decimal, str],\n- enforce_valid_true_fixture\n+ self,\n+ val: Union[Decimal, str],\n+ enforce_valid_true_fixture\n ):\n \"\"\"Test that errors are raised when value is invalid.\"\"\"\n with pytest.raises(ValueError):\n", "problem_statement": "Pickling/unpickling timezone in DT does not work\n**Describe the bug**\r\n\r\nThe following tests fail because the timezone is not set in the unpickled `DT`:\r\n```py\r\n def test_pickling_with_timezone():\r\n dt = pydicom.valuerep.DT(\"19111213212123-0630\")\r\n loaded_dt = pickle.loads(pickle.dumps(dt))\r\n assert dt == loaded_dt\r\n\r\n def test_pickling_dt_from_datetime_with_timezone():\r\n tz_info = timezone(timedelta(seconds=-23400), '-0630')\r\n dt_object = datetime(2022, 12, 31, 23, 59, 59, 42, tzinfo=tz_info)\r\n dt = pydicom.valuerep.DT(dt_object)\r\n loaded_dt = pickle.loads(pickle.dumps(dt))\r\n assert dt == loaded_dt\r\n```\r\n\r\nThis is a spin-off of PR #1365, see [this comment](https://github.com/pydicom/pydicom/pull/1365#issuecomment-829544827).\n", "hints_text": "", "created_at": "2021-05-03T18:27:35Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::TestDT::test_pickling_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_datetime_behavior", "pydicom/tests/test_valuerep.py::TestDA::test_date_behavior"], "PASS_TO_PASS": ["pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestTM::test_pickling_tm_from_time", "pydicom/tests/test_valuerep.py::TestTM::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestTM::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_comparison", "pydicom/tests/test_valuerep.py::TestTM::test_time_behavior", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime", "pydicom/tests/test_valuerep.py::TestDT::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDT::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDT::test_comparison", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDA::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDA::test_comparison", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[3.14159265358979]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[-1234.456e78]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E-5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E+5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[+1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[42", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[nan]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[3.141592653589793]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1,000]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[127.0.0.1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1.e]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.0-1.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.0-0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.0--0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.123-0.123]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.321--0.321]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1e-05-1e-05]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[3.141592653589793-3.14159265358979]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-3.141592653589793--3.1415926535898]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[5.385940192876374e-07-5.3859401929e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-5.385940192876374e-07--5.385940193e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[12342534378.125532-12342534378.1255]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[64070869985876.78-64070869985876.8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.7976931348623157e+308-1.797693135e+308]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_wrong_type", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_length", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat_auto_format", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-nan]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan2]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf1]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_repr", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val4]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val5]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val6]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val7]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal_auto_format", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_veterinary", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator_from_bytes", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time", "pydicom/tests/test_valuerep.py::test_person_name_unicode_warns"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1334", "base_commit": "24a86b316441ac3a46e569779627e24482786a8a", "patch": "diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -3,6 +3,7 @@\n \n import datetime\n from decimal import Decimal\n+from math import floor, isfinite, log10\n import platform\n import re\n import sys\n@@ -329,15 +330,139 @@ def __reduce_ex__(self, protocol: int) -> Union[str, Tuple[Any, ...]]:\n )\n \n \n+# Regex to match strings that represent valid DICOM decimal strings (DS)\n+_DS_REGEX = re.compile(r'\\s*[\\+\\-]?\\d+(\\.\\d+)?([eE][\\+\\-]?\\d+)?\\s*$')\n+\n+\n+def is_valid_ds(s: str) -> bool:\n+ \"\"\"Check whether this string is a valid decimal string.\n+\n+ Valid decimal strings must be 16 characters or fewer, and contain only\n+ characters from a limited set.\n+\n+ Parameters\n+ ----------\n+ s: str\n+ String to test.\n+\n+ Returns\n+ -------\n+ bool\n+ True if the string is a valid decimal string. Otherwise False.\n+ \"\"\"\n+ # Check that the length is within the limits\n+ if len(s) > 16:\n+ return False\n+\n+ return _DS_REGEX.match(s) is not None\n+\n+\n+def format_number_as_ds(val: Union[float, Decimal]) -> str:\n+ \"\"\"Truncate a float's representation to give a valid Decimal String (DS).\n+\n+ DICOM's decimal string (DS) representation is limited to strings with 16\n+ characters and a limited set of characters. This function represents a\n+ float that satisfies these constraints while retaining as much\n+ precision as possible. Some floats are represented using scientific\n+ notation to make more efficient use of the limited number of characters.\n+\n+ Note that this will incur a loss of precision if the number cannot be\n+ represented with 16 characters. Furthermore, non-finite floats (infs and\n+ nans) cannot be represented as decimal strings and will cause an error to\n+ be raised.\n+\n+ Parameters\n+ ----------\n+ val: Union[float, Decimal]\n+ The floating point value whose representation is required.\n+\n+ Returns\n+ -------\n+ str\n+ String representation of the float satisfying the constraints of the\n+ decimal string representation.\n+\n+ Raises\n+ ------\n+ ValueError\n+ If val does not represent a finite value\n+\n+ \"\"\"\n+ if not isinstance(val, (float, Decimal)):\n+ raise TypeError(\"'val' must be of type float or decimal.Decimal\")\n+ if not isfinite(val):\n+ raise ValueError(\n+ \"Cannot encode non-finite floats as DICOM decimal strings. \"\n+ f\"Got '{val}'\"\n+ )\n+\n+ valstr = str(val)\n+\n+ # In the simple case, the default python string representation\n+ # will do\n+ if len(valstr) <= 16:\n+ return valstr\n+\n+ # Decide whether to use scientific notation\n+ logval = log10(abs(val))\n+\n+ # Characters needed for '-' at start\n+ sign_chars = 1 if val < 0.0 else 0\n+\n+ # Numbers larger than 1e14 cannot be correctly represented by truncating\n+ # their string representations to 16 chars, e.g pi * 10^13 would become\n+ # '314159265358979.', which may not be universally understood. This limit\n+ # is 1e13 for negative numbers because of the minus sign.\n+ # For negative exponents, the point of equal precision between scientific\n+ # and standard notation is 1e-4 e.g. '0.00031415926535' and\n+ # '3.1415926535e-04' are both 16 chars\n+ use_scientific = logval < -4 or logval >= (14 - sign_chars)\n+\n+ if use_scientific:\n+ # In principle, we could have a number where the exponent\n+ # needs three digits to be represented (bigger than this cannot be\n+ # represented by floats). Due to floating point limitations\n+ # this is best checked for by doing the string conversion\n+ remaining_chars = 10 - sign_chars\n+ trunc_str = f'%.{remaining_chars}e' % val\n+ if len(trunc_str) > 16:\n+ trunc_str = f'%.{remaining_chars - 1}e' % val\n+ return trunc_str\n+ else:\n+ if logval >= 1.0:\n+ # chars remaining for digits after sign, digits left of '.' and '.'\n+ remaining_chars = 14 - sign_chars - int(floor(logval))\n+ else:\n+ remaining_chars = 14 - sign_chars\n+ return f'%.{remaining_chars}f' % val\n+\n+\n class DSfloat(float):\n \"\"\"Store value for an element with VR **DS** as :class:`float`.\n \n If constructed from an empty string, return the empty string,\n not an instance of this class.\n \n+ Parameters\n+ ----------\n+ val: Union[str, int, float, Decimal]\n+ Value to store as a DS.\n+ auto_format: bool\n+ If True, automatically format the string representation of this\n+ number to ensure it satisfies the constraints in the DICOM standard.\n+ Note that this will lead to loss of precision for some numbers.\n+\n \"\"\"\n+ def __new__(\n+ cls,\n+ val: Union[str, int, float, Decimal],\n+ auto_format: bool = False\n+ ) -> [_DSfloat]:\n+ return super().__new__(cls, val)\n+\n def __init__(\n- self, val: Union[str, int, float, Decimal]\n+ self, val: Union[str, int, float, Decimal],\n+ auto_format: bool = False\n ) -> None:\n \"\"\"Store the original string if one given, for exact write-out of same\n value later.\n@@ -350,28 +475,70 @@ def __init__(\n elif isinstance(val, (DSfloat, DSdecimal)) and has_attribute:\n self.original_string = val.original_string\n \n+ self.auto_format = auto_format\n+ if self.auto_format:\n+ # If auto_format is True, keep the float value the same, but change\n+ # the string representation stored in original_string if necessary\n+ if hasattr(self, 'original_string'):\n+ if not is_valid_ds(self.original_string):\n+ self.original_string = format_number_as_ds(\n+ float(self.original_string)\n+ )\n+ else:\n+ self.original_string = format_number_as_ds(self)\n+\n+ if config.enforce_valid_values and not self.auto_format:\n+ if len(repr(self).strip('\"')) > 16:\n+ raise OverflowError(\n+ \"Values for elements with a VR of 'DS' must be <= 16 \"\n+ \"characters long, but the float provided requires > 16 \"\n+ \"characters to be accurately represented. Use a smaller \"\n+ \"string, set 'config.enforce_valid_values' to False to \"\n+ \"override the length check, or explicitly construct a DS \"\n+ \"object with 'auto_format' set to True\"\n+ )\n+ if not is_valid_ds(repr(self).strip('\"')):\n+ # This will catch nan and inf\n+ raise ValueError(\n+ f'Value \"{str(self)}\" is not valid for elements with a VR '\n+ 'of DS'\n+ )\n+\n def __str__(self) -> str:\n- if hasattr(self, 'original_string'):\n+ if hasattr(self, 'original_string') and not self.auto_format:\n return self.original_string\n \n # Issue #937 (Python 3.8 compatibility)\n return repr(self)[1:-1]\n \n def __repr__(self) -> str:\n+ if self.auto_format and hasattr(self, 'original_string'):\n+ return f'\"{self.original_string}\"'\n return f'\"{super().__repr__()}\"'\n \n \n class DSdecimal(Decimal):\n \"\"\"Store value for an element with VR **DS** as :class:`decimal.Decimal`.\n \n+ Parameters\n+ ----------\n+ val: Union[str, int, float, Decimal]\n+ Value to store as a DS.\n+ auto_format: bool\n+ If True, automatically format the string representation of this\n+ number to ensure it satisfies the constraints in the DICOM standard.\n+ Note that this will lead to loss of precision for some numbers.\n+\n Notes\n -----\n If constructed from an empty string, returns the empty string, not an\n instance of this class.\n+\n \"\"\"\n def __new__(\n cls: Type[_DSdecimal],\n- val: Union[str, int, float, Decimal]\n+ val: Union[str, int, float, Decimal],\n+ auto_format: bool = False\n ) -> Optional[_DSdecimal]:\n \"\"\"Create an instance of DS object, or return a blank string if one is\n passed in, e.g. from a type 2 DICOM blank value.\n@@ -395,19 +562,13 @@ def __new__(\n return None\n \n val = super().__new__(cls, val)\n- if len(str(val)) > 16 and config.enforce_valid_values:\n- raise OverflowError(\n- \"Values for elements with a VR of 'DS' values must be <= 16 \"\n- \"characters long. Use a smaller string, set \"\n- \"'config.enforce_valid_values' to False to override the \"\n- \"length check, or use 'Decimal.quantize()' and initialize \"\n- \"with a 'Decimal' instance.\"\n- )\n \n return val\n \n def __init__(\n- self, val: Union[str, int, float, Decimal]\n+ self,\n+ val: Union[str, int, float, Decimal],\n+ auto_format: bool = False\n ) -> None:\n \"\"\"Store the original string if one given, for exact write-out of same\n value later. E.g. if set ``'1.23e2'``, :class:`~decimal.Decimal` would\n@@ -421,6 +582,35 @@ def __init__(\n elif isinstance(val, (DSfloat, DSdecimal)) and has_str:\n self.original_string = val.original_string\n \n+ self.auto_format = auto_format\n+ if self.auto_format:\n+ # If auto_format is True, keep the float value the same, but change\n+ # the string representation stored in original_string if necessary\n+ if hasattr(self, 'original_string'):\n+ if not is_valid_ds(self.original_string):\n+ self.original_string = format_number_as_ds(\n+ float(self.original_string)\n+ )\n+ else:\n+ self.original_string = format_number_as_ds(self)\n+\n+ if config.enforce_valid_values:\n+ if len(repr(self).strip('\"')) > 16:\n+ raise OverflowError(\n+ \"Values for elements with a VR of 'DS' values must be \"\n+ \"<= 16 characters long. Use a smaller string, set \"\n+ \"'config.enforce_valid_values' to False to override the \"\n+ \"length check, use 'Decimal.quantize()' and initialize \"\n+ \"with a 'Decimal' instance, or explicitly construct a DS \"\n+ \"instance with 'auto_format' set to True\"\n+ )\n+ if not is_valid_ds(repr(self).strip('\"')):\n+ # This will catch nan and inf\n+ raise ValueError(\n+ f'Value \"{str(self)}\" is not valid for elements with a VR '\n+ 'of DS'\n+ )\n+\n def __str__(self) -> str:\n has_str = hasattr(self, 'original_string')\n if has_str and len(self.original_string) <= 16:\n@@ -429,6 +619,8 @@ def __str__(self) -> str:\n return super().__str__()\n \n def __repr__(self) -> str:\n+ if self.auto_format and hasattr(self, 'original_string'):\n+ return f'\"{self.original_string}\"'\n return f'\"{str(self)}\"'\n \n \n@@ -440,7 +632,8 @@ def __repr__(self) -> str:\n \n \n def DS(\n- val: Union[None, str, int, float, Decimal]\n+ val: Union[None, str, int, float, Decimal],\n+ auto_format: bool = False\n ) -> Union[None, str, DSfloat, DSdecimal]:\n \"\"\"Factory function for creating DS class instances.\n \n@@ -458,7 +651,7 @@ def DS(\n if val == '' or val is None:\n return val\n \n- return DSclass(val)\n+ return DSclass(val, auto_format=auto_format)\n \n \n class IS(int):\n", "test_patch": "diff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -9,7 +9,9 @@\n import cPickle as pickle\n except ImportError:\n import pickle\n+import math\n import sys\n+from typing import Union\n \n from pydicom.tag import Tag\n from pydicom.values import convert_value\n@@ -29,6 +31,27 @@\n default_encoding = \"iso8859\"\n \n \[email protected]()\n+def enforce_valid_true_fixture():\n+ \"\"\"Fixture to run tests with enforce_valid_values True and ensure it is\n+ reset afterwards regardless of whether test succeeds.\"\"\"\n+ enforce_flag_original = config.enforce_valid_values\n+ config.enforce_valid_values = True\n+ yield\n+ config.enforce_valid_values = enforce_flag_original\n+\n+\[email protected](params=(True, False))\n+def enforce_valid_both_fixture(request):\n+ \"\"\"Fixture to run tests with enforce_valid_values with both True and False\n+ and ensure it is reset afterwards regardless of whether test succeeds.\n+ \"\"\"\n+ enforce_flag_original = config.enforce_valid_values\n+ config.enforce_valid_values = request.param\n+ yield\n+ config.enforce_valid_values = enforce_flag_original\n+\n+\n class TestTM:\n \"\"\"Unit tests for pickling TM\"\"\"\n def test_pickling(self):\n@@ -191,6 +214,115 @@ def test_new_obj_conversion(self):\n pydicom.valuerep.DA(123456)\n \n \n+class TestIsValidDS:\n+ \"\"\"Unit tests for the is_valid_ds function.\"\"\"\n+ @pytest.mark.parametrize(\n+ 's',\n+ [\n+ '1',\n+ '3.14159265358979',\n+ '-1234.456e78',\n+ '1.234E-5',\n+ '1.234E+5',\n+ '+1',\n+ ' 42', # leading spaces allowed\n+ '42 ', # trailing spaces allowed\n+ ]\n+ )\n+ def test_valid(self, s: str):\n+ \"\"\"Various valid decimal strings.\"\"\"\n+ assert pydicom.valuerep.is_valid_ds(s)\n+\n+ @pytest.mark.parametrize(\n+ 's',\n+ [\n+ 'nan',\n+ '-inf',\n+ '3.141592653589793', # too long\n+ '1,000', # no commas\n+ '1 000', # no embedded spaces\n+ '127.0.0.1', # not a number\n+ '1.e', # not a number\n+ '',\n+ ]\n+ )\n+ def test_invalid(self, s: str):\n+ \"\"\"Various invalid decimal strings.\"\"\"\n+ assert not pydicom.valuerep.is_valid_ds(s)\n+\n+\n+class TestTruncateFloatForDS:\n+ \"\"\"Unit tests for float truncation function\"\"\"\n+ def check_valid(self, s: str) -> bool:\n+ # Use the pydicom test function\n+ if not pydicom.valuerep.is_valid_ds(s):\n+ return False\n+\n+ # Disallow floats ending in '.' since this may not be correctly\n+ # interpreted\n+ if s.endswith('.'):\n+ return False\n+\n+ # Otherwise return True\n+ return True\n+\n+ @pytest.mark.parametrize(\n+ 'val,expected_str',\n+ [\n+ [1.0, \"1.0\"],\n+ [0.0, \"0.0\"],\n+ [-0.0, \"-0.0\"],\n+ [0.123, \"0.123\"],\n+ [-0.321, \"-0.321\"],\n+ [0.00001, \"1e-05\"],\n+ [3.14159265358979323846, '3.14159265358979'],\n+ [-3.14159265358979323846, '-3.1415926535898'],\n+ [5.3859401928763739403e-7, '5.3859401929e-07'],\n+ [-5.3859401928763739403e-7, '-5.385940193e-07'],\n+ [1.2342534378125532912998323e10, '12342534378.1255'],\n+ [6.40708699858767842501238e13, '64070869985876.8'],\n+ [1.7976931348623157e+308, '1.797693135e+308'],\n+ ]\n+ )\n+ def test_auto_format(self, val: float, expected_str: str):\n+ \"\"\"Test truncation of some basic values.\"\"\"\n+ assert pydicom.valuerep.format_number_as_ds(val) == expected_str\n+\n+ @pytest.mark.parametrize(\n+ 'exp', [-101, -100, 100, 101] + list(range(-16, 17))\n+ )\n+ def test_powers_of_pi(self, exp: int):\n+ \"\"\"Raise pi to various powers to test truncation.\"\"\"\n+ val = math.pi * 10 ** exp\n+ s = pydicom.valuerep.format_number_as_ds(val)\n+ assert self.check_valid(s)\n+\n+ @pytest.mark.parametrize(\n+ 'exp', [-101, -100, 100, 101] + list(range(-16, 17))\n+ )\n+ def test_powers_of_negative_pi(self, exp: int):\n+ \"\"\"Raise negative pi to various powers to test truncation.\"\"\"\n+ val = -math.pi * 10 ** exp\n+ s = pydicom.valuerep.format_number_as_ds(val)\n+ assert self.check_valid(s)\n+\n+ @pytest.mark.parametrize(\n+ 'val', [float('-nan'), float('nan'), float('-inf'), float('inf')]\n+ )\n+ def test_invalid(self, val: float):\n+ \"\"\"Test non-finite floating point numbers raise an error\"\"\"\n+ with pytest.raises(ValueError):\n+ pydicom.valuerep.format_number_as_ds(val)\n+\n+ def test_wrong_type(self):\n+ \"\"\"Test calling with a string raises an error\"\"\"\n+ with pytest.raises(\n+ TypeError,\n+ match=\"'val' must be of type float or decimal.Decimal\"\n+ ):\n+ pydicom.valuerep.format_number_as_ds('1.0')\n+\n+\n class TestDS:\n \"\"\"Unit tests for DS values\"\"\"\n def test_empty_value(self):\n@@ -249,6 +381,57 @@ def test_DSdecimal(self):\n assert 1.2345 == y\n assert \"1.2345\" == y.original_string\n \n+ def test_auto_format(self, enforce_valid_both_fixture):\n+ \"\"\"Test truncating floats\"\"\"\n+ x = pydicom.valuerep.DSfloat(math.pi, auto_format=True)\n+\n+ # Float representation should be unaltered by truncation\n+ assert x == math.pi\n+ # String representations should be correctly formatted\n+ assert str(x) == '3.14159265358979'\n+ assert repr(x) == '\"3.14159265358979\"'\n+\n+ def test_auto_format_invalid_string(self, enforce_valid_both_fixture):\n+ \"\"\"If the user supplies an invalid string, this should be formatted.\"\"\"\n+ x = pydicom.valuerep.DSfloat('3.141592653589793', auto_format=True)\n+\n+ # Float representation should be unaltered by truncation\n+ assert x == float('3.141592653589793')\n+ # String representations should be correctly formatted\n+ assert str(x) == '3.14159265358979'\n+ assert repr(x) == '\"3.14159265358979\"'\n+\n+ def test_auto_format_valid_string(self, enforce_valid_both_fixture):\n+ \"\"\"If the user supplies a valid string, this should not be altered.\"\"\"\n+ x = pydicom.valuerep.DSfloat('1.234e-1', auto_format=True)\n+\n+ # Float representation should be correct\n+ assert x == 0.1234\n+ # String representations should be unaltered\n+ assert str(x) == '1.234e-1'\n+ assert repr(x) == '\"1.234e-1\"'\n+\n+ def test_enforce_valid_values_length(self, enforce_valid_true_fixture):\n+ \"\"\"Test that errors are raised when length is too long.\"\"\"\n+ with pytest.raises(OverflowError):\n+ valuerep.DSfloat('3.141592653589793')\n+\n+ @pytest.mark.parametrize(\n+ 'val',\n+ [\n+ 'nan', '-nan', 'inf', '-inf', float('nan'), float('-nan'),\n+ float('-inf'), float('inf')\n+ ]\n+ )\n+ def test_enforce_valid_values_value(\n+ self,\n+ val: Union[float, str],\n+ enforce_valid_true_fixture\n+ ):\n+ \"\"\"Test that errors are raised when value is invalid.\"\"\"\n+ with pytest.raises(ValueError):\n+ valuerep.DSfloat(val)\n+\n \n class TestDSdecimal:\n \"\"\"Unit tests for pickling DSdecimal\"\"\"\n@@ -297,6 +480,52 @@ def test_repr(self):\n x = pydicom.valuerep.DSdecimal('1.2345')\n assert '\"1.2345\"' == repr(x)\n \n+ def test_auto_format(self, enforce_valid_both_fixture):\n+ \"\"\"Test truncating decimal\"\"\"\n+ x = pydicom.valuerep.DSdecimal(Decimal(math.pi), auto_format=True)\n+\n+ # Decimal representation should be unaltered by truncation\n+ assert x == Decimal(math.pi)\n+ # String representations should be correctly formatted\n+ assert str(x) == '3.14159265358979'\n+ assert repr(x) == '\"3.14159265358979\"'\n+\n+ def test_auto_format_invalid_string(self, enforce_valid_both_fixture):\n+ \"\"\"If the user supplies an invalid string, this should be formatted.\"\"\"\n+ x = pydicom.valuerep.DSdecimal('3.141592653589793', auto_format=True)\n+\n+ # Decimal representation should be unaltered by truncation\n+ assert x == Decimal('3.141592653589793')\n+ # String representations should be correctly formatted\n+ assert str(x) == '3.14159265358979'\n+ assert repr(x) == '\"3.14159265358979\"'\n+\n+ @pytest.mark.parametrize(\n+ 'val',\n+ [\n+ 'NaN', '-NaN', 'Infinity', '-Infinity', Decimal('NaN'),\n+ Decimal('-NaN'), Decimal('-Infinity'), Decimal('Infinity')\n+ ]\n+ )\n+ def test_enforce_valid_values_value(\n+ self,\n+ val: Union[Decimal, str],\n+ enforce_valid_true_fixture\n+ ):\n+ \"\"\"Test that errors are raised when value is invalid.\"\"\"\n+ with pytest.raises(ValueError):\n+ valuerep.DSdecimal(val)\n+\n+ def test_auto_format_valid_string(self, enforce_valid_both_fixture):\n+ \"\"\"If the user supplies a valid string, this should not be altered.\"\"\"\n+ x = pydicom.valuerep.DSdecimal('1.234e-1', auto_format=True)\n+\n+ # Decimal representation should be correct\n+ assert x == Decimal('1.234e-1')\n+ # String representations should be unaltered\n+ assert str(x) == '1.234e-1'\n+ assert repr(x) == '\"1.234e-1\"'\n+\n \n class TestIS:\n \"\"\"Unit tests for IS\"\"\"\n@@ -355,7 +584,6 @@ def test_str(self):\n val = pydicom.valuerep.IS(\"1.0\")\n assert \"1.0\" == str(val)\n \n-\n def test_repr(self):\n \"\"\"Test IS.__repr__().\"\"\"\n val = pydicom.valuerep.IS(1)\n@@ -428,13 +656,6 @@ def test_valid_decimal_strings(self):\n assert isinstance(ds, valuerep.DSdecimal)\n assert len(str(ds)) <= 16\n \n- # Now the input string is too long but decimal.Decimal can convert it\n- # to a valid 16-character string\n- long_str = \"-0.000000981338674\"\n- ds = valuerep.DS(long_str)\n- assert isinstance(ds, valuerep.DSdecimal)\n- assert len(str(ds)) <= 16\n-\n def test_invalid_decimal_strings(self, enforce_valid_values):\n # Now the input string truly is invalid\n invalid_string = \"-9.813386743e-006\"\n", "problem_statement": "Strings with Value Representation DS are too long\n**Describe the bug**\r\nStrings of Value Representation DS are restricted to a maximum length of 16 bytes according to [Part 5 Section 6.2](http://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html#para_15754884-9ca2-4b12-9368-d66f32bc8ce1), but `pydicom.valuerep.DS` may represent numbers with more than 16 bytes.\r\n\r\n**Expected behavior**\r\n`pydicom.valuerep.DS` should create a string of maximum length 16, when passed a fixed point number with many decimals.\r\n\r\n**Steps To Reproduce**\r\n```python\r\nlen(str(pydicom.valuerep.DS(3.14159265358979323846264338327950288419716939937510582097)).encode('utf-8'))\r\nlen(str(pydicom.valuerep.DS(\"3.14159265358979323846264338327950288419716939937510582097\")).encode('utf-8'))\r\n```\r\nreturns `17` and `58`, respectively, instead of `16`.\r\n\r\n**Your environment**\r\n```\r\nmodule | version\r\n------ | -------\r\nplatform | macOS-10.15.6-x86_64-i386-64bit\r\nPython | 3.8.6 (default, Oct 8 2020, 14:06:32) [Clang 12.0.0 (clang-1200.0.32.2)]\r\npydicom | 2.0.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.19.4\r\nPIL | 8.0.1\r\n```\n", "hints_text": "Thanks for this, @hackermd. Pydicom has traditionally been permissive about values as they are set, because sometimes people want to replicate existing invalid DICOM. But for sure this should be an error when `config.enforce_valid_values` is `True` (perhaps a warning otherwise), and pydicom should leave it to the calling code to figure out how to truncate the value.\nI've just checked, because I thought I remembered this coming up before. There is a check - but only for `DS` derived from `Decimal` (and when `enforce_valid_values is True`). Wouldn't be hard to replicate the checks for the `DSfloat` class.", "created_at": "2021-04-04T22:06:46Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[3.14159265358979]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[-1234.456e78]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E-5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E+5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[+1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[42", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[nan]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[3.141592653589793]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1,000]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[127.0.0.1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1.e]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.0-1.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.0-0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.0--0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.123-0.123]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.321--0.321]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1e-05-1e-05]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[3.141592653589793-3.14159265358979]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-3.141592653589793--3.1415926535898]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[5.385940192876374e-07-5.3859401929e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-5.385940192876374e-07--5.385940193e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[12342534378.125532-12342534378.1255]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[64070869985876.78-64070869985876.8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.7976931348623157e+308-1.797693135e+308]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_wrong_type", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_length", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-nan]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan2]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf1]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val4]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val5]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val6]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val7]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[False]"], "PASS_TO_PASS": ["pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestTM::test_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDT::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_repr", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_veterinary", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator_from_bytes", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time", "pydicom/tests/test_valuerep.py::test_person_name_unicode_warns"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-958", "base_commit": "40652fc0a18fd9f1204cb3d4b9829e3a8be5cbe0", "patch": "diff --git a/pydicom/charset.py b/pydicom/charset.py\n--- a/pydicom/charset.py\n+++ b/pydicom/charset.py\n@@ -45,7 +45,7 @@\n 'ISO 2022 IR 144': 'iso_ir_144',\n 'ISO 2022 IR 148': 'iso_ir_148',\n 'ISO 2022 IR 149': 'euc_kr',\n- 'ISO 2022 IR 159': 'iso-2022-jp',\n+ 'ISO 2022 IR 159': 'iso2022_jp_2',\n 'ISO 2022 IR 166': 'iso_ir_166',\n 'ISO 2022 IR 58': 'iso_ir_58',\n 'ISO_IR 192': 'UTF8', # from Chinese example, 2008 PS3.5 Annex J p1-4\n@@ -81,7 +81,7 @@\n ESC + b'-M': 'iso_ir_148',\n ESC + b'-T': 'iso_ir_166',\n ESC + b'$)C': 'euc_kr',\n- ESC + b'$(D': 'iso-2022-jp',\n+ ESC + b'$(D': 'iso2022_jp_2',\n ESC + b'$)A': 'iso_ir_58',\n }\n \n@@ -92,7 +92,7 @@\n # To decode them, the escape sequence shall be preserved in the input byte\n # string, and will be removed during decoding by Python.\n handled_encodings = ('iso2022_jp',\n- 'iso-2022-jp',\n+ 'iso2022_jp_2',\n 'iso_ir_58')\n \n \n@@ -165,10 +165,18 @@ def _encode_to_jis_x_0201(value, errors='strict'):\n \n return encoded\n \n-\n def _encode_to_jis_x_0208(value, errors='strict'):\n- \"\"\"Convert a unicode string into JIS X 0208 byte string using iso2022_jp\n- encodings.\n+ \"\"\"Convert a unicode string into JIS X 0208 byte string.\"\"\"\n+ return _encode_to_given_charset(value, 'ISO 2022 IR 87', errors=errors)\n+\n+\n+def _encode_to_jis_x_0212(value, errors='strict'):\n+ \"\"\"Convert a unicode string into JIS X 0212 byte string.\"\"\"\n+ return _encode_to_given_charset(value, 'ISO 2022 IR 159', errors=errors)\n+\n+\n+def _encode_to_given_charset(value, character_set, errors='strict'):\n+ \"\"\"Convert a unicode string into given character set.\n The escape sequence which is located at the end of the encoded value has\n to vary depending on the value 1 of SpecificCharacterSet. So we have to\n trim it and append the correct escape sequence manually.\n@@ -177,6 +185,8 @@ def _encode_to_jis_x_0208(value, errors='strict'):\n ----------\n value : text type\n The unicode string as presented to the user.\n+ character_set: str:\n+ Character set for result.\n errors : str\n The behavior of a character which could not be encoded. This value\n is passed to errors argument of str.encode().\n@@ -185,28 +195,30 @@ def _encode_to_jis_x_0208(value, errors='strict'):\n -------\n byte string\n The encoded string. If some characters in value could not be encoded to\n- JIS X 0208, it depends on the behavior of iso2022_jp encoder.\n+ given character_set, it depends on the behavior of corresponding python\n+ encoder.\n \n Raises\n ------\n UnicodeEncodeError\n If errors is set to 'strict' and `value` could not be encoded with\n- JIS X 0208.\n+ given character_set.\n \"\"\"\n \n+ encoding = python_encoding[character_set]\n # If errors is not strict, this function is used as fallback.\n # So keep the tail escape sequence of encoded for backward compatibility.\n if errors != 'strict':\n- return value.encode('iso2022_jp', errors=errors)\n+ return value.encode(encoding, errors=errors)\n \n- Encoder = codecs.getincrementalencoder('iso2022-jp')\n+ Encoder = codecs.getincrementalencoder(encoding)\n encoder = Encoder()\n \n encoded = encoder.encode(value[0])\n- if encoded[:3] != ENCODINGS_TO_CODES['iso2022_jp']:\n+ if not encoded.startswith(ENCODINGS_TO_CODES[encoding]):\n raise UnicodeEncodeError(\n- 'iso2022_jp', value, 0, len(value),\n- 'Given character is out of ISO IR 87')\n+ encoding, value, 0, len(value),\n+ 'Given character is out of {}'.format(character_set))\n \n for i, c in enumerate(value[1:], 1):\n try:\n@@ -215,10 +227,10 @@ def _encode_to_jis_x_0208(value, errors='strict'):\n e.start = i\n e.end = len(value)\n raise e\n- if b[:3] == ENCODINGS_TO_CODES['iso8859']:\n+ if b[:1] == ESC:\n raise UnicodeEncodeError(\n- 'iso2022_jp', value, i, len(value),\n- 'Given character is out of ISO IR 87')\n+ encoding, value, i, len(value),\n+ 'Given character is out of {}'.format(character_set))\n encoded += b\n return encoded\n \n@@ -262,13 +274,13 @@ def _get_escape_sequence_for_encoding(encoding, encoded=None):\n \n \n # These encodings need escape sequence to handle alphanumeric characters.\n-need_tail_escape_sequence_encodings = ('iso2022_jp', 'iso-2022-jp')\n+need_tail_escape_sequence_encodings = ('iso2022_jp', 'iso2022_jp_2')\n \n \n custom_encoders = {\n 'shift_jis': _encode_to_jis_x_0201,\n 'iso2022_jp': _encode_to_jis_x_0208,\n- 'iso-2022-jp': _encode_to_jis_x_0208\n+ 'iso2022_jp_2': _encode_to_jis_x_0212\n }\n \n \n@@ -562,7 +574,7 @@ def _encode_string_parts(value, encodings):\n # unencoded_part is empty - we are done, return the encoded string\n if best_encoding in need_tail_escape_sequence_encodings:\n encoded += _get_escape_sequence_for_encoding(encodings[0])\n- return encoded\n+ return bytes(encoded)\n \n \n def _encode_string_impl(value, encoding, errors='strict'):\n", "test_patch": "diff --git a/pydicom/tests/test_charset.py b/pydicom/tests/test_charset.py\n--- a/pydicom/tests/test_charset.py\n+++ b/pydicom/tests/test_charset.py\n@@ -9,6 +9,7 @@\n from pydicom.data import get_charset_files, get_testdata_files\n from pydicom.dataelem import DataElement\n from pydicom.filebase import DicomBytesIO\n+from pydicom.valuerep import PersonName3\n \n # The file names (without '.dcm' extension) of most of the character test\n # files, together with the respective decoded PatientName tag values.\n@@ -197,9 +198,9 @@ def test_bad_decoded_multi_byte_encoding(self):\n b'\\x1b$(D\\xc4\\xe9\\xef\\xed\\xf5\\xf3\\xe9\\xef\\xf2')\n \n with pytest.warns(UserWarning, match='Failed to decode byte string '\n- 'with encodings: iso-2022-jp'):\n+ 'with encodings: iso2022_jp_2'):\n pydicom.charset.decode_element(elem, ['ISO 2022 IR 159'])\n- assert u'\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd' == elem.value\n+ assert u'\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd' == elem.value\n \n def test_bad_decoded_multi_byte_encoding_enforce_standard(self):\n \"\"\"Test handling bad encoding for single encoding if\n@@ -207,7 +208,7 @@ def test_bad_decoded_multi_byte_encoding_enforce_standard(self):\n config.enforce_valid_values = True\n elem = DataElement(0x00100010, 'PN',\n b'\\x1b$(D\\xc4\\xe9\\xef\\xed\\xf5\\xf3\\xe9\\xef\\xf2')\n- msg = (\"'iso2022_jp' codec can't decode bytes in position 0-3: \"\n+ msg = (\"'iso2022_jp_2' codec can't decode byte 0xc4 in position 4: \"\n \"illegal multibyte sequence\")\n with pytest.raises(UnicodeDecodeError, match=msg):\n pydicom.charset.decode_element(elem, ['ISO 2022 IR 159'])\n@@ -435,11 +436,26 @@ def test_japanese_multi_byte_personname(self):\n ds_out = dcmread(fp)\n assert original_string == ds_out.PatientName.original_string\n \n+ japanese_pn = PersonName3(u\"Mori^Ogai=\u68ee^\u9dd7\u5916=\u3082\u308a^\u304a\u3046\u304c\u3044\")\n+ pyencs = pydicom.charset.convert_encodings([\"ISO 2022 IR 6\",\n+ \"ISO 2022 IR 87\",\n+ \"ISO 2022 IR 159\"])\n+ actual_encoded = bytes(japanese_pn.encode(pyencs))\n+ expect_encoded = (\n+ b\"\\x4d\\x6f\\x72\\x69\\x5e\\x4f\\x67\\x61\\x69\\x3d\\x1b\\x24\\x42\\x3f\"\n+ b\"\\x39\\x1b\\x28\\x42\\x5e\\x1b\\x24\\x28\\x44\\x6c\\x3f\\x1b\\x24\\x42\"\n+ b\"\\x33\\x30\\x1b\\x28\\x42\\x3d\\x1b\\x24\\x42\\x24\\x62\\x24\\x6a\\x1b\"\n+ b\"\\x28\\x42\\x5e\\x1b\\x24\\x42\\x24\\x2a\\x24\\x26\\x24\\x2c\\x24\\x24\"\n+ b\"\\x1b\\x28\\x42\"\n+ )\n+ assert expect_encoded == actual_encoded\n+\n def test_japanese_multi_byte_encoding(self):\n \"\"\"Test japanese multi byte strings are correctly encoded.\"\"\"\n- encoded = pydicom.charset.encode_string(u'\u3042a\uff71\u30a2',\n- ['shift_jis', 'iso2022_jp'])\n- assert b'\\x1b$B$\"\\x1b(Ja\\x1b)I\\xb1\\x1b$B%\"\\x1b(J' == encoded\n+ encoded = pydicom.charset.encode_string(u'\u3042a\uff71\u30a2\u9f69', ['shift_jis',\n+ 'iso2022_jp', 'iso2022_jp_2'])\n+ expect = b'\\x1b$B$\"\\x1b(Ja\\x1b)I\\xb1\\x1b$B%\"\\x1b$(DmN\\x1b(J'\n+ assert expect == bytes(encoded)\n \n def test_bad_japanese_encoding(self):\n \"\"\"Test japanese multi byte strings are not correctly encoded.\"\"\"\n", "problem_statement": "Encoding to ISO 2022 IR 159 doesn't work\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\nEncoding to ISO 2022 IR 159 doesn't work even if 'ISO 2022 IR 159' is passed to pydicom.charset.convert_encodings.\r\n\r\n#### Steps/Code to Reproduce\r\nISO 2022 IR 159 is designed as supplement characters to ISO 2022 IR 87. So these characters are not frequent use. But person name sometimes contains them. In the following example, the letter of \"\u9dd7\" is only in ISO 2022 IR 159. But we cannot encode them correctly. \r\n\r\n```\r\nimport pydicom\r\n\r\njapanese_pn = u\"Mori^Ogai=\u68ee^\u9dd7\u5916=\u3082\u308a^\u304a\u3046\u304c\u3044\"\r\nspecific_character_sets = [\"ISO 2022 IR 6\", \"ISO 2022 IR 87\", \"ISO 2022 IR 159\"]\r\nexpect_encoded = (\r\n b\"\\x4d\\x6f\\x72\\x69\\x5e\\x4f\\x67\\x61\\x69\\x3d\\x1b\\x24\\x42\\x3f\"\r\n b\"\\x39\\x1b\\x28\\x42\\x5e\\x1b\\x24\\x28\\x44\\x6c\\x3f\\x1b\\x24\\x42\"\r\n b\"\\x33\\x30\\x1b\\x28\\x42\\x3d\\x1b\\x24\\x42\\x24\\x62\\x24\\x6a\\x1b\"\r\n b\"\\x28\\x42\\x5e\\x1b\\x24\\x42\\x24\\x2a\\x24\\x26\\x24\\x2c\\x24\\x24\"\r\n b\"\\x1b\\x28\\x42\"\r\n)\r\n\r\npython_encodings = pydicom.charset.convert_encodings(specific_character_sets)\r\nactual_encoded = pydicom.charset.encode_string(japanese_pn, python_encodings)\r\n\r\nprint(\"actual:{}\".format(actual_encoded))\r\nprint(\"expect:{}\".format(expect_encoded))\r\n```\r\n#### Expected Results\r\n<!-- Please paste or describe the expected results.\r\nExample: No error is thrown and the name of the patient is printed.-->\r\n```\r\nb'Mori^Ogai=\\x1b$B?9\\x1b(B^\\x1b$(Dl?\\x1b$B30\\x1b(B=\\x1b$B$b$j\\x1b(B^\\x1b$B$*$&$,$$\\x1b(B'\r\n```\r\n#### Actual Results\r\n<!-- Please paste or specifically describe the actual output or traceback.\r\n(Use %xmode to deactivate ipython's trace beautifier)\r\nExample: ```AttributeError: 'FileDataset' object has no attribute 'PatientID'```\r\n-->\r\n```\r\nb'Mori^Ogai=?^??=??^????'\r\n```\r\n\r\nAnd the followin exception occurs.\r\n\r\n```\r\n/PATH/TO/MY/PYTHON/PACKAGES/pydicom/charset.py:488: UserWarning: Failed to encode value with encodings: iso8859, iso2022_jp, iso-2022-jp - using replacement characters in encoded string\r\n .format(', '.join(encodings)))\r\n```\r\n\r\n#### Versions\r\n<!--\r\nPlease run the following snippet and paste the output below.\r\nimport platform; print(platform.platform())\r\nimport sys; print(\"Python\", sys.version)\r\nimport pydicom; print(\"pydicom\", pydicom.__version__)\r\n-->\r\n```\r\nLinux-4.15.0-55-generic-x86_64-with-debian-buster-sid\r\nPython 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31)\r\n[GCC 7.3.0]\r\npydicom 1.3.0\r\n```\r\n\r\n\r\n<!-- Thanks for contributing! -->\r\n\n", "hints_text": "In my opinion, this is caused by selecting the wrong python codec corresponding to 'ISO 2022 IR 159'. In the current implementation, 'iso-2022-jp' is used if 'ISO 2022 IR 159' is passed. But 'iso-2022-jp' is alias to 'iso200_jp'. I think we have to use 'iso-2022-jp-2'. It contains all 'iso-2022-jp' characters and 'ISO 2022 IR 159' characters.\r\n\r\nIf you don't mind, please assign this issue to me. I will make a PR for this issue.\nSure, go ahead! And thanks for the support!", "created_at": "2019-10-16T13:06:11Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_japanese_multi_byte_personname", "pydicom/tests/test_charset.py::TestCharset::test_japanese_multi_byte_encoding"], "PASS_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_encodings", "pydicom/tests/test_charset.py::TestCharset::test_nested_character_sets", "pydicom/tests/test_charset.py::TestCharset::test_inherited_character_set_in_sequence", "pydicom/tests/test_charset.py::TestCharset::test_standard_file", "pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set", "pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set_enforce_valid", "pydicom/tests/test_charset.py::TestCharset::test_decoding_with_specific_tags", "pydicom/tests/test_charset.py::TestCharset::test_bad_charset", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_code_extensions_not_allowed", "pydicom/tests/test_charset.py::TestCharset::test_convert_encodings_warnings", "pydicom/tests/test_charset.py::TestCharset::test_convert_python_encodings", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_patched_charset", "pydicom/tests/test_charset.py::TestCharset::test_patched_code_extension_charset", "pydicom/tests/test_charset.py::TestCharset::test_multi_charset_default_value", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_personname", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_text", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_code_extensions[ISO", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrArab-\\u0642\\u0628\\u0627\\u0646\\u064a^\\u0644\\u0646\\u0632\\u0627\\u0631]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFren-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFrenMulti-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGerm-\\xc4neas^R\\xfcdiger]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGreek-\\u0394\\u03b9\\u03bf\\u03bd\\u03c5\\u03c3\\u03b9\\u03bf\\u03c2]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH31-Yamada^Tarou=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH32-\\uff94\\uff8f\\uff80\\uff9e^\\uff80\\uff9b\\uff73=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrHbrw-\\u05e9\\u05e8\\u05d5\\u05df^\\u05d3\\u05d1\\u05d5\\u05e8\\u05d4]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrI2-Hong^Gildong=\\u6d2a^\\u5409\\u6d1e=\\ud64d^\\uae38\\ub3d9]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMulti-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMultiExplicitIR6-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrKoreanMulti-\\uae40\\ud76c\\uc911]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrRuss-\\u041b\\u044e\\u043ace\\u043c\\u0431yp\\u0433]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX1-Wang^XiaoDong=\\u738b^\\u5c0f\\u6771]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX2-Wang^XiaoDong=\\u738b^\\u5c0f\\u4e1c]", "pydicom/tests/test_charset.py::TestCharset::test_changed_character_set", "pydicom/tests/test_charset.py::TestCharset::test_invalid_second_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_japanese_encoding", "pydicom/tests/test_charset.py::TestCharset::test_deprecated_decode"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-863", "base_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9", "patch": "diff --git a/pydicom/charset.py b/pydicom/charset.py\n--- a/pydicom/charset.py\n+++ b/pydicom/charset.py\n@@ -86,6 +86,7 @@\n }\n \n ENCODINGS_TO_CODES = {v: k for k, v in CODES_TO_ENCODINGS.items()}\n+ENCODINGS_TO_CODES['shift_jis'] = ESC + b')I'\n \n # Multi-byte character sets except Korean are handled by Python.\n # To decode them, the escape sequence shall be preserved in the input byte\n@@ -95,6 +96,182 @@\n 'iso_ir_58')\n \n \n+def _encode_to_jis_x_0201(value, errors='strict'):\n+ \"\"\"Convert a unicode string into JIS X 0201 byte string using shift_jis\n+ encodings.\n+ shift_jis is a superset of jis_x_0201. So we can regard the encoded value\n+ as jis_x_0201 if it is single byte character.\n+\n+ Parameters\n+ ----------\n+ value : text type\n+ The unicode string as presented to the user.\n+ errors : str\n+ The behavior of a character which could not be encoded. If 'strict' is\n+ passed, raise an UnicodeEncodeError. If any other value is passed,\n+ non ISO IR 14 characters are replaced by the ASCII '?'.\n+\n+ Returns\n+ -------\n+ byte string\n+ The encoded string. If some characters in value could not be encoded to\n+ JIS X 0201, and `errors` is not set to 'strict', they are replaced to\n+ '?'.\n+\n+ Raises\n+ ------\n+ UnicodeEncodeError\n+ If errors is set to 'strict' and `value` could not be encoded with\n+ JIS X 0201.\n+ \"\"\"\n+\n+ Encoder = codecs.getincrementalencoder('shift_jis')\n+ encoder = Encoder()\n+\n+ # If errors is not strict, this function is used as fallback.\n+ # In this case, we use only ISO IR 14 to encode given value\n+ # without escape sequence.\n+ if errors != 'strict' or value == '':\n+ encoded = b''\n+ for c in value:\n+ try:\n+ b = encoder.encode(c)\n+ except UnicodeEncodeError as e:\n+ b = b'?'\n+\n+ if len(b) != 1 or 0x80 <= ord(b):\n+ b = b'?'\n+ encoded += b\n+ return encoded\n+\n+ encoded = encoder.encode(value[0])\n+ if len(encoded) != 1:\n+ raise UnicodeEncodeError(\n+ 'shift_jis', value, 0, len(value), 'illegal multibyte sequence')\n+\n+ msb = ord(encoded) & 0x80 # msb is 1 for ISO IR 13, 0 for ISO IR 14\n+ for i, c in enumerate(value[1:], 1):\n+ try:\n+ b = encoder.encode(c)\n+ except UnicodeEncodeError as e:\n+ e.start = i\n+ e.end = len(value)\n+ raise e\n+ if len(b) != 1 or ((ord(b) & 0x80) ^ msb) != 0:\n+ character_set = 'ISO IR 14' if msb == 0 else 'ISO IR 13'\n+ msg = 'Given character is out of {}'.format(character_set)\n+ raise UnicodeEncodeError('shift_jis', value, i, len(value), msg)\n+ encoded += b\n+\n+ return encoded\n+\n+\n+def _encode_to_jis_x_0208(value, errors='strict'):\n+ \"\"\"Convert a unicode string into JIS X 0208 byte string using iso2022_jp\n+ encodings.\n+ The escape sequence which is located at the end of the encoded value has\n+ to vary depending on the value 1 of SpecificCharacterSet. So we have to\n+ trim it and append the correct escape sequence manually.\n+\n+ Parameters\n+ ----------\n+ value : text type\n+ The unicode string as presented to the user.\n+ errors : str\n+ The behavior of a character which could not be encoded. This value\n+ is passed to errors argument of str.encode().\n+\n+ Returns\n+ -------\n+ byte string\n+ The encoded string. If some characters in value could not be encoded to\n+ JIS X 0208, it depends on the behavior of iso2022_jp encoder.\n+\n+ Raises\n+ ------\n+ UnicodeEncodeError\n+ If errors is set to 'strict' and `value` could not be encoded with\n+ JIS X 0208.\n+ \"\"\"\n+\n+ # If errors is not strict, this function is used as fallback.\n+ # So keep the tail escape sequence of encoded for backward compatibility.\n+ if errors != 'strict':\n+ return value.encode('iso2022_jp', errors=errors)\n+\n+ Encoder = codecs.getincrementalencoder('iso2022-jp')\n+ encoder = Encoder()\n+\n+ encoded = encoder.encode(value[0])\n+ if encoded[:3] != ENCODINGS_TO_CODES['iso2022_jp']:\n+ raise UnicodeEncodeError(\n+ 'iso2022_jp', value, 0, len(value),\n+ 'Given character is out of ISO IR 87')\n+\n+ for i, c in enumerate(value[1:], 1):\n+ try:\n+ b = encoder.encode(c)\n+ except UnicodeEncodeError as e:\n+ e.start = i\n+ e.end = len(value)\n+ raise e\n+ if b[:3] == ENCODINGS_TO_CODES['iso8859']:\n+ raise UnicodeEncodeError(\n+ 'iso2022_jp', value, i, len(value),\n+ 'Given character is out of ISO IR 87')\n+ encoded += b\n+ return encoded\n+\n+\n+def _get_escape_sequence_for_encoding(encoding, encoded=None):\n+ \"\"\" Return an escape sequence corresponding to the given encoding. If\n+ encoding is 'shift_jis', return 'ESC)I' or 'ESC(J' depending on the first\n+ byte of encoded.\n+\n+ Parameters\n+ ----------\n+ encoding : str\n+ An encoding is used to specify an escape sequence.\n+\n+ encoded : bytes or str\n+ The encoded value is used to chose an escape sequence if encoding is\n+ 'shift_jis'\n+\n+ Returns\n+ -------\n+ string\n+ Escape sequence for encoded value.\n+ \"\"\"\n+\n+ ESC_ISO_IR_14 = ESC + b'(J'\n+ ESC_ISO_IR_13 = ESC + b')I'\n+\n+ if encoding == 'shift_jis':\n+ if encoded is None:\n+ return ESC_ISO_IR_14\n+\n+ if not in_py2:\n+ first_byte = encoded[0]\n+ else:\n+ first_byte = ord(encoded[0])\n+ if 0x80 <= first_byte:\n+ return ESC_ISO_IR_13\n+\n+ return ESC_ISO_IR_14\n+ return ENCODINGS_TO_CODES.get(encoding, b'')\n+\n+\n+# These encodings need escape sequence to handle alphanumeric characters.\n+need_tail_escape_sequence_encodings = ('iso2022_jp', 'iso-2022-jp')\n+\n+\n+custom_encoders = {\n+ 'shift_jis': _encode_to_jis_x_0201,\n+ 'iso2022_jp': _encode_to_jis_x_0208,\n+ 'iso-2022-jp': _encode_to_jis_x_0208\n+}\n+\n+\n def decode_string(value, encodings, delimiters):\n \"\"\"Convert a raw byte string into a unicode string using the given\n list of encodings.\n@@ -281,9 +458,14 @@ def encode_string(value, encodings):\n \"\"\"\n for i, encoding in enumerate(encodings):\n try:\n- encoded = value.encode(encoding)\n+ encoded = _encode_string_impl(value, encoding)\n+\n if i > 0 and encoding not in handled_encodings:\n- return ENCODINGS_TO_CODES.get(encoding, b'') + encoded\n+ escape_sequence = _get_escape_sequence_for_encoding(\n+ encoding, encoded=encoded)\n+ encoded = escape_sequence + encoded\n+ if encoding in need_tail_escape_sequence_encodings:\n+ encoded += _get_escape_sequence_for_encoding(encodings[0])\n return encoded\n except UnicodeError:\n continue\n@@ -304,7 +486,7 @@ def encode_string(value, encodings):\n warnings.warn(\"Failed to encode value with encodings: {} - using \"\n \"replacement characters in encoded string\"\n .format(', '.join(encodings)))\n- return value.encode(encodings[0], errors='replace')\n+ return _encode_string_impl(value, encodings[0], errors='replace')\n \n \n def _encode_string_parts(value, encodings):\n@@ -337,14 +519,14 @@ def _encode_string_parts(value, encodings):\n \"\"\"\n encoded = bytearray()\n unencoded_part = value\n+ best_encoding = None\n while unencoded_part:\n # find the encoding that can encode the longest part of the rest\n # of the string still to be encoded\n max_index = 0\n- best_encoding = None\n for encoding in encodings:\n try:\n- unencoded_part.encode(encoding)\n+ _encode_string_impl(unencoded_part, encoding)\n # if we get here, the whole rest of the value can be encoded\n best_encoding = encoding\n max_index = len(unencoded_part)\n@@ -355,20 +537,36 @@ def _encode_string_parts(value, encodings):\n max_index = e.start\n best_encoding = encoding\n # none of the given encodings can encode the first character - give up\n- if best_encoding is None:\n- raise ValueError()\n+ if max_index == 0:\n+ raise ValueError(\"None of the given encodings can encode the \"\n+ \"first character\")\n \n # encode the part that can be encoded with the found encoding\n- encoded_part = unencoded_part[:max_index].encode(best_encoding)\n+ encoded_part = _encode_string_impl(unencoded_part[:max_index],\n+ best_encoding)\n if best_encoding not in handled_encodings:\n- encoded += ENCODINGS_TO_CODES.get(best_encoding, b'')\n+ encoded += _get_escape_sequence_for_encoding(\n+ best_encoding, encoded=encoded_part)\n encoded += encoded_part\n # set remaining unencoded part of the string and handle that\n unencoded_part = unencoded_part[max_index:]\n # unencoded_part is empty - we are done, return the encoded string\n+ if best_encoding in need_tail_escape_sequence_encodings:\n+ encoded += _get_escape_sequence_for_encoding(encodings[0])\n return encoded\n \n \n+def _encode_string_impl(value, encoding, errors='strict'):\n+ \"\"\"Convert a unicode string into a byte string. If given encoding is in\n+ custom_encoders, use a corresponding custom_encoder. If given encoding\n+ is not in custom_encoders, use a corresponding python handled encoder.\n+ \"\"\"\n+ if encoding in custom_encoders:\n+ return custom_encoders[encoding](value, errors=errors)\n+ else:\n+ return value.encode(encoding, errors=errors)\n+\n+\n # DICOM PS3.5-2008 6.1.1 (p 18) says:\n # default is ISO-IR 6 G0, equiv to common chr set of ISO 8859 (PS3.5 6.1.2.1)\n # (0008,0005) value 1 can *replace* the default encoding...\n", "test_patch": "diff --git a/pydicom/tests/test_charset.py b/pydicom/tests/test_charset.py\n--- a/pydicom/tests/test_charset.py\n+++ b/pydicom/tests/test_charset.py\n@@ -404,3 +404,36 @@ def test_invalid_second_encoding(self):\n u\"- using default encoding instead\"):\n pydicom.charset.decode(\n elem, ['ISO 2022 IR 100', 'ISO 2022 IR 146'])\n+\n+ def test_japanese_multi_byte_personname(self):\n+ \"\"\"Test japanese person name which has multi byte strings are\n+ correctly encoded.\"\"\"\n+ file_path = get_charset_files('chrH32.dcm')[0]\n+ ds = dcmread(file_path)\n+ ds.decode()\n+\n+ if hasattr(ds.PatientName, 'original_string'):\n+ original_string = ds.PatientName.original_string\n+ ds.PatientName.original_string = None\n+ fp = DicomBytesIO()\n+ fp.is_implicit_VR = False\n+ fp.is_little_endian = True\n+ ds.save_as(fp, write_like_original=False)\n+ fp.seek(0)\n+ ds_out = dcmread(fp)\n+ assert original_string == ds_out.PatientName.original_string\n+\n+ def test_japanese_multi_byte_encoding(self):\n+ \"\"\"Test japanese multi byte strings are correctly encoded.\"\"\"\n+ encoded = pydicom.charset.encode_string(u'\u3042a\uff71\u30a2',\n+ ['shift_jis', 'iso2022_jp'])\n+ assert b'\\x1b$B$\"\\x1b(Ja\\x1b)I\\xb1\\x1b$B%\"\\x1b(J' == encoded\n+\n+ def test_bad_japanese_encoding(self):\n+ \"\"\"Test japanese multi byte strings are not correctly encoded.\"\"\"\n+ with pytest.warns(UserWarning,\n+ match=u\"Failed to encode value with encodings\"\n+ u\": shift_jis - using replacement character\"\n+ u\"s in encoded string\"):\n+ encoded = pydicom.charset.encode_string(u'\u3042a\uff71\u30a2', ['shift_jis'])\n+ assert b'?a??' == encoded\n", "problem_statement": "Wrong encoding occurs if the value 1 of SpecificCharacterSets is ISO 2022 IR 13.\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\nAll Japanese characters are encoded into shift_jis if the value 1 of SpecificCharacterSets (0x0008, 0x0005) is ISO 2022 IR 13.\r\n\r\n#### Steps/Code to Reproduce\r\nThe japanese_pn and expect_encoded in the following code came from \r\n[H.3.2 Value 1 of Attribute Specific Character Set (0008,0005) is ISO 2022 IR 13.](http://dicom.nema.org/medical/dicom/2015b/output/chtml/part05/sect_H.3.2.html)\r\n\r\n```py\r\nimport pydicom\r\n\r\njapanese_pn = u\"\uff94\uff8f\uff80\uff9e^\uff80\uff9b\uff73=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046\"\r\nspecific_character_sets = [\"ISO 2022 IR 13\", \"ISO 2022 IR 87\"]\r\nexpect_encoded = (\r\n b\"\\xd4\\xcf\\xc0\\xde\\x5e\\xc0\\xdb\\xb3\\x3d\\x1b\\x24\\x42\\x3b\\x33\"\r\n b\"\\x45\\x44\\x1b\\x28\\x4a\\x5e\\x1b\\x24\\x42\\x42\\x40\\x4f\\x3a\\x1b\"\r\n b\"\\x28\\x4a\\x3d\\x1b\\x24\\x42\\x24\\x64\\x24\\x5e\\x24\\x40\\x1b\\x28\"\r\n b\"\\x4a\\x5e\\x1b\\x24\\x42\\x24\\x3f\\x24\\x6d\\x24\\x26\\x1b\\x28\\x4a\"\r\n)\r\n\r\npython_encodings = pydicom.charset.convert_encodings(specific_character_sets)\r\nactual_encoded = pydicom.charset.encode_string(japanese_pn, python_encodings)\r\n\r\nprint(\"actual:{}\".format(actual_encoded))\r\nprint(\"expect:{}\".format(expect_encoded))\r\n```\r\n<!--\r\nExample:\r\n```py\r\nfrom io import BytesIO\r\nfrom pydicom import dcmread\r\n\r\nbytestream = b'\\x02\\x00\\x02\\x00\\x55\\x49\\x16\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31' \\\r\n b'\\x30\\x30\\x30\\x38\\x2e\\x35\\x2e\\x31\\x2e\\x31\\x2e\\x39\\x00\\x02\\x00\\x10\\x00' \\\r\n b'\\x55\\x49\\x12\\x00\\x31\\x2e\\x32\\x2e\\x38\\x34\\x30\\x2e\\x31\\x30\\x30\\x30\\x38' \\\r\n b'\\x2e\\x31\\x2e\\x32\\x00\\x20\\x20\\x10\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x20\\x20' \\\r\n b'\\x20\\x00\\x06\\x00\\x00\\x00\\x4e\\x4f\\x52\\x4d\\x41\\x4c'\r\n\r\nfp = BytesIO(bytestream)\r\nds = dcmread(fp, force=True)\r\n\r\nprint(ds.PatientID)\r\n```\r\nIf the code is too long, feel free to put it in a public gist and link\r\nit in the issue: https://gist.github.com\r\n\r\nWhen possible use pydicom testing examples to reproduce the errors. Otherwise, provide\r\nan anonymous version of the data in order to replicate the errors.\r\n-->\r\n\r\n#### Expected Results\r\n<!-- Please paste or describe the expected results.\r\nExample: No error is thrown and the name of the patient is printed.-->\r\n```\r\nb'\\xd4\\xcf\\xc0\\xde^\\xc0\\xdb\\xb3=\\x1b$B;3ED\\x1b(J^\\x1b$BB@O:\\x1b(J=\\x1b$B$d$^$@\\x1b(J^\\x1b$B$?$m$&\\x1b(J'\r\n```\r\n\r\n#### Actual Results\r\n<!-- Please paste or specifically describe the actual output or traceback.\r\n(Use %xmode to deactivate ipython's trace beautifier)\r\nExample: ```AttributeError: 'FileDataset' object has no attribute 'PatientID'```\r\n-->\r\n```\r\nb'\\xd4\\xcf\\xc0\\xde^\\xc0\\xdb\\xb3=\\x8eR\\x93c^\\x91\\xbe\\x98Y=\\x82\\xe2\\x82\\xdc\\x82\\xbe^\\x82\\xbd\\x82\\xeb\\x82\\xa4'\r\n```\r\n\r\n#### Versions\r\n<!--\r\nPlease run the following snippet and paste the output below.\r\nimport platform; print(platform.platform())\r\nimport sys; print(\"Python\", sys.version)\r\nimport pydicom; print(\"pydicom\", pydicom.__version__)\r\n-->\r\n```\r\nLinux-4.15.0-50-generic-x86_64-with-debian-buster-sid\r\nPython 3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34)\r\n[GCC 7.3.0]\r\npydicom 1.2.2\r\n```\r\n\r\n<!-- Thanks for contributing! -->\r\n\n", "hints_text": "In my opinion, this issue is caused by encoding to shift_jis doesn't raise UnicodeError when characters which are out of JIS X 0201 are given. So I guess that this is fixed by encoding to jis correctly.\r\n\r\nIf you don't mind, please assign this issue to me. I will make a PR for this issue.\nThanks for the report - of course you can make a PR for this, please go ahead! \nDear all.\r\nI'm trying to solve this issue. And I want some advice about the scope of this issue and the way of implementation.\r\nMay I discuss them in this issue thread? Or should I create a PR and add W.I.P to its title?\nWhatever suits you better - if you want to discuss concrete code, it may be easier to add a PR to be able to comment on specific lines, but that's completely up to you!\n@mrbean-bremen \r\n\r\nThank for your quick reply. I got it. First, I will write some concrete codes. And then I'll make a PR and want to discuss there. ", "created_at": "2019-06-15T15:09:57Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_japanese_multi_byte_personname", "pydicom/tests/test_charset.py::TestCharset::test_japanese_multi_byte_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_japanese_encoding"], "PASS_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_encodings", "pydicom/tests/test_charset.py::TestCharset::test_nested_character_sets", "pydicom/tests/test_charset.py::TestCharset::test_inherited_character_set_in_sequence", "pydicom/tests/test_charset.py::TestCharset::test_standard_file", "pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set", "pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set_enforce_valid", "pydicom/tests/test_charset.py::TestCharset::test_decoding_with_specific_tags", "pydicom/tests/test_charset.py::TestCharset::test_bad_charset", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_code_extensions_not_allowed", "pydicom/tests/test_charset.py::TestCharset::test_convert_encodings_warnings", "pydicom/tests/test_charset.py::TestCharset::test_convert_python_encodings", "pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_patched_charset", "pydicom/tests/test_charset.py::TestCharset::test_patched_code_extension_charset", "pydicom/tests/test_charset.py::TestCharset::test_multi_charset_default_value", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_personname", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_text", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_code_extensions[ISO", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrArab-\\u0642\\u0628\\u0627\\u0646\\u064a^\\u0644\\u0646\\u0632\\u0627\\u0631]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFren-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFrenMulti-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGerm-\\xc4neas^R\\xfcdiger]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGreek-\\u0394\\u03b9\\u03bf\\u03bd\\u03c5\\u03c3\\u03b9\\u03bf\\u03c2]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH31-Yamada^Tarou=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH32-\\uff94\\uff8f\\uff80\\uff9e^\\uff80\\uff9b\\uff73=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrHbrw-\\u05e9\\u05e8\\u05d5\\u05df^\\u05d3\\u05d1\\u05d5\\u05e8\\u05d4]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrI2-Hong^Gildong=\\u6d2a^\\u5409\\u6d1e=\\ud64d^\\uae38\\ub3d9]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMulti-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMultiExplicitIR6-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrKoreanMulti-\\uae40\\ud76c\\uc911]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrRuss-\\u041b\\u044e\\u043ace\\u043c\\u0431yp\\u0433]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX1-Wang^XiaoDong=\\u738b^\\u5c0f\\u6771]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX2-Wang^XiaoDong=\\u738b^\\u5c0f\\u4e1c]", "pydicom/tests/test_charset.py::TestCharset::test_changed_character_set", "pydicom/tests/test_charset.py::TestCharset::test_invalid_second_encoding"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1694", "base_commit": "f8cf45b6c121e5a4bf4a43f71aba3bc64af3db9c", "patch": "diff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -2492,8 +2492,8 @@ def to_json_dict(\n json_dataset = {}\n for key in self.keys():\n json_key = '{:08X}'.format(key)\n- data_element = self[key]\n try:\n+ data_element = self[key]\n json_dataset[json_key] = data_element.to_json_dict(\n bulk_data_element_handler=bulk_data_element_handler,\n bulk_data_threshold=bulk_data_threshold\n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -7,7 +7,7 @@\n \n from pydicom import dcmread\n from pydicom.data import get_testdata_file\n-from pydicom.dataelem import DataElement\n+from pydicom.dataelem import DataElement, RawDataElement\n from pydicom.dataset import Dataset\n from pydicom.tag import Tag, BaseTag\n from pydicom.valuerep import PersonName\n@@ -284,7 +284,23 @@ def test_suppress_invalid_tags(self, _):\n \n ds_json = ds.to_json_dict(suppress_invalid_tags=True)\n \n- assert ds_json.get(\"00100010\") is None\n+ assert \"00100010\" not in ds_json\n+\n+ def test_suppress_invalid_tags_with_failed_dataelement(self):\n+ \"\"\"Test tags that raise exceptions don't if suppress_invalid_tags True.\n+ \"\"\"\n+ ds = Dataset()\n+ # we have to add a RawDataElement as creating a DataElement would\n+ # already raise an exception\n+ ds[0x00082128] = RawDataElement(\n+ Tag(0x00082128), 'IS', 4, b'5.25', 0, True, True)\n+\n+ with pytest.raises(TypeError):\n+ ds.to_json_dict()\n+\n+ ds_json = ds.to_json_dict(suppress_invalid_tags=True)\n+\n+ assert \"00082128\" not in ds_json\n \n \n class TestSequence:\n", "problem_statement": "Dataset.to_json_dict can still generate exceptions when suppress_invalid_tags=True\n**Describe the bug**\r\nI'm using `Dataset.to_json_dict(suppress_invalid_tags=True)` and can live with losing invalid tags. Unfortunately, I can still trigger an exception with something like `2.0` in an `IS` field.\r\n\r\n**Expected behavior**\r\nto_json_dict shouldn't throw an error about an invalid tag when `suppress_invalid_tags` is enabled.\r\n\r\nMy thought was simply to move the `data_element = self[key]` into the try/catch block that's right after it.\r\n\r\n**Steps To Reproduce**\r\n\r\nTraceback:\r\n```\r\n File \"dicom.py\", line 143, in create_dict\r\n json_ds = ds.to_json_dict(suppress_invalid_tags=True)\r\n File \"/usr/lib/python3/dist-packages/pydicom/dataset.py\", line 2495, in to_json_dict\r\n data_element = self[key]\r\n File \"/usr/lib/python3/dist-packages/pydicom/dataset.py\", line 939, in __getitem__\r\n self[tag] = DataElement_from_raw(elem, character_set, self)\r\n File \"/usr/lib/python3/dist-packages/pydicom/dataelem.py\", line 859, in DataElement_from_raw\r\n value = convert_value(vr, raw, encoding)\r\n File \"/usr/lib/python3/dist-packages/pydicom/values.py\", line 771, in convert_value\r\n return converter(byte_string, is_little_endian, num_format)\r\n File \"/usr/lib/python3/dist-packages/pydicom/values.py\", line 348, in convert_IS_string\r\n return MultiString(num_string, valtype=pydicom.valuerep.IS)\r\n File \"/usr/lib/python3/dist-packages/pydicom/valuerep.py\", line 1213, in MultiString\r\n return valtype(splitup[0])\r\n File \"/usr/lib/python3/dist-packages/pydicom/valuerep.py\", line 1131, in __new__\r\n raise TypeError(\"Could not convert value to integer without loss\")\r\nTypeError: Could not convert value to integer without loss\r\n```\r\n\r\n**Your environment**\r\npython 3.7, pydicom 2.3\r\n\r\n\n", "hints_text": "", "created_at": "2022-09-20T18:52:53Z", "version": "2.3", "FAIL_TO_PASS": ["pydicom/tests/test_json.py::TestDataSetToJson::test_suppress_invalid_tags_with_failed_dataelement"], "PASS_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestDataSetToJson::test_suppress_invalid_tags", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_2", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_within_SQ", "pydicom/tests/test_json.py::TestNumeric::test_numeric_values", "pydicom/tests/test_json.py::TestNumeric::test_numeric_types"], "environment_setup_commit": "a8be738418dee0a2b93c241fbd5e0bc82f4b8680"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1562", "base_commit": "e1a035a88fe36d466579b2f3940bde5b8b1bc84d", "patch": "diff --git a/pydicom/datadict.py b/pydicom/datadict.py\n--- a/pydicom/datadict.py\n+++ b/pydicom/datadict.py\n@@ -249,9 +249,10 @@ def get_entry(tag: TagType) -> Tuple[str, str, str, str, str]:\n \n Parameters\n ----------\n- tag : int\n- The tag for the element whose entry is to be retrieved. Only entries\n- in the official DICOM dictionary will be checked, not entries in the\n+ tag : int or str or Tuple[int, int]\n+ The tag for the element whose entry is to be retrieved, in any of the\n+ forms accepted by :func:`~pydicom.tag.Tag`. Only entries in the\n+ official DICOM dictionary will be checked, not entries in the\n private dictionary.\n \n Returns\n@@ -292,8 +293,9 @@ def dictionary_is_retired(tag: TagType) -> bool:\n \n Parameters\n ----------\n- tag : int\n- The tag for the element whose retirement status is being checked.\n+ tag : int or str or Tuple[int, int]\n+ The tag for the element whose retirement status is being checked, in\n+ any of the forms accepted by :func:`~pydicom.tag.Tag`.\n \n Returns\n -------\n@@ -306,9 +308,7 @@ def dictionary_is_retired(tag: TagType) -> bool:\n KeyError\n If the tag is not present in the DICOM data dictionary.\n \"\"\"\n- if 'retired' in get_entry(tag)[3].lower():\n- return True\n- return False\n+ return 'retired' in get_entry(tag)[3].lower()\n \n \n def dictionary_VR(tag: TagType) -> str:\n@@ -318,9 +318,9 @@ def dictionary_VR(tag: TagType) -> str:\n \n Parameters\n ----------\n- tag : int\n+ tag : int or str or Tuple[int, int]\n The tag for the element whose value representation (VR) is being\n- retrieved.\n+ retrieved, in any of the forms accepted by :func:`~pydicom.tag.Tag`.\n \n Returns\n -------\n@@ -342,9 +342,9 @@ def dictionary_VM(tag: TagType) -> str:\n \n Parameters\n ----------\n- tag : int\n+ tag : int or str or Tuple[int, int]\n The tag for the element whose value multiplicity (VM) is being\n- retrieved.\n+ retrieved, in any of the forms accepted by :func:`~pydicom.tag.Tag`.\n \n Returns\n -------\n@@ -366,8 +366,9 @@ def dictionary_description(tag: TagType) -> str:\n \n Parameters\n ----------\n- tag : int\n- The tag for the element whose description is being retrieved.\n+ tag : int or str or Tuple[int, int]\n+ The tag for the element whose description is being retrieved, in any\n+ of the forms accepted by :func:`~pydicom.tag.Tag`.\n \n Returns\n -------\n@@ -389,8 +390,9 @@ def dictionary_keyword(tag: TagType) -> str:\n \n Parameters\n ----------\n- tag : int\n- The tag for the element whose keyword is being retrieved.\n+ tag : int or str or Tuple[int, int]\n+ The tag for the element whose keyword is being retrieved, in any of\n+ the forms accepted by :func:`~pydicom.tag.Tag`.\n \n Returns\n -------\n@@ -410,8 +412,9 @@ def dictionary_has_tag(tag: TagType) -> bool:\n \n Parameters\n ----------\n- tag : int\n- The tag to check.\n+ tag : int or str or Tuple[int, int]\n+ The tag to check, in any of the forms accepted by\n+ :func:`~pydicom.tag.Tag`.\n \n Returns\n -------\n@@ -419,7 +422,10 @@ def dictionary_has_tag(tag: TagType) -> bool:\n ``True`` if the tag corresponds to an element present in the official\n DICOM data dictionary, ``False`` otherwise.\n \"\"\"\n- return (tag in DicomDictionary)\n+ try:\n+ return Tag(tag) in DicomDictionary\n+ except Exception:\n+ return False\n \n \n def keyword_for_tag(tag: TagType) -> str:\n@@ -427,8 +433,9 @@ def keyword_for_tag(tag: TagType) -> str:\n \n Parameters\n ----------\n- tag : int\n- The tag for the element whose keyword is being retrieved.\n+ tag : int or str or Tuple[int, int]\n+ The tag for the element whose keyword is being retrieved, in any of\n+ the forms accepted by :func:`~pydicom.tag.Tag`.\n \n Returns\n -------\n@@ -514,9 +521,10 @@ def get_private_entry(\n \n Parameters\n ----------\n- tag : int\n- The tag for the element whose entry is to be retrieved. Only entries\n- in the private dictionary will be checked.\n+ tag : int or str or Tuple[int, int]\n+ The tag for the element whose entry is to be retrieved, in any of the\n+ forms accepted by :func:`~pydicom.tag.Tag`. Only entries in the\n+ private dictionary will be checked.\n private_creator : str\n The name of the private creator.\n \n@@ -574,9 +582,9 @@ def private_dictionary_VR(tag: TagType, private_creator: str) -> str:\n \n Parameters\n ----------\n- tag : int\n+ tag : int or str or Tuple[int, int]\n The tag for the element whose value representation (VR) is being\n- retrieved.\n+ retrieved, in any of the forms accepted by :func:`~pydicom.tag.Tag`.\n private_creator : str\n The name of the private creator.\n \n@@ -598,9 +606,9 @@ def private_dictionary_VM(tag: TagType, private_creator: str) -> str:\n \n Parameters\n ----------\n- tag : int\n+ tag : int or str or Tuple[int, int]\n The tag for the element whose value multiplicity (VM) is being\n- retrieved.\n+ retrieved, in any of the forms accepted by :func:`~pydicom.tag.Tag`.\n private_creator : str\n The name of the private creator.\n \n@@ -622,8 +630,9 @@ def private_dictionary_description(tag: TagType, private_creator: str) -> str:\n \n Parameters\n ----------\n- tag : int\n- The tag for the element whose description is being retrieved.\n+ tag : int or str or Tuple[int, int]\n+ The tag for the element whose description is being retrieved, in any\n+ of the forms accepted by :func:`~pydicom.tag.Tag`.\n private_creator : str\n The name of the private createor.\n \n", "test_patch": "diff --git a/pydicom/tests/test_dictionary.py b/pydicom/tests/test_dictionary.py\n--- a/pydicom/tests/test_dictionary.py\n+++ b/pydicom/tests/test_dictionary.py\n@@ -30,6 +30,8 @@ def test_dict_has_tag(self):\n \"\"\"Test dictionary_has_tag\"\"\"\n assert dictionary_has_tag(0x00100010)\n assert not dictionary_has_tag(0x11110010)\n+ assert dictionary_has_tag(\"PatientName\")\n+ assert not dictionary_has_tag(\"PatientMane\")\n \n def test_repeater_has_tag(self):\n \"\"\"Test repeater_has_tag\"\"\"\n", "problem_statement": "Revise the type annotation for pydicom.datadict.dictionary_has_tag()\n**Describe the bug**\r\n\r\nThe documentation of [`pydicom.datadict.dictionary_has_tag()`](https://pydicom.github.io/pydicom/dev/reference/generated/pydicom.datadict.dictionary_has_tag.html#pydicom.datadict.dictionary_has_tag) suggests that a query using keywords (instead of a tag integer) would work:\r\n\r\n```python\r\npydicom.datadict.dictionary_has_tag(tag: Union[int, str, Tuple[int, int], pydicom.tag.BaseTag]) -> bool\r\n```\r\n\r\nHowever, the function only accepts integer arguments.\r\n\r\n```python\r\nfrom pydicom.datadict import dictionary_has_tag, keyword_dict\r\ndictionary_has_tag(\"PixelData\")\r\n# Returns False\r\n\r\ndictionary_has_tag(keyword_dict[\"PixelData\"])\r\n# Returns True\r\n```\r\n\r\n(The problem may apply to other functions as well...)\r\n\r\n**Expected behavior**\r\nFollowing the docs, `dictionary_has_tag(\"PixelData\")` should return True. \r\n\r\nIt would be nice, if the flexible conversion of tags from names or hex-tuples (as the type annotation suggests) would also be possible for this function.\r\n\r\n**Your environment**\r\n```text\r\nmodule | version\r\n------ | -------\r\nplatform | macOS-10.14.6-x86_64-i386-64bit\r\nPython | 3.9.0 (v3.9.0:9cf6752276, Oct 5 2020, 11:29:23) [Clang 6.0 (clang-600.0.57)]\r\npydicom | 2.2.2\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.20.1\r\nPIL | 8.0.1\r\npylibjpeg | _module not found_\r\nopenjpeg | _module not found_\r\nlibjpeg | _module not found_\r\n```\r\n\r\n\n", "hints_text": "Yeah, it should be plain old `int`. Not sure how I missed that one...\r\n\r\nThe keyword to tag conversion is actually kind of (relatively) expensive, and this function is used in our initial dataset parsing so we want it to be fast.", "created_at": "2021-12-30T20:52:59Z", "version": "2.2", "FAIL_TO_PASS": ["pydicom/tests/test_dictionary.py::TestDict::test_dict_has_tag"], "PASS_TO_PASS": ["pydicom/tests/test_dictionary.py::TestDict::test_tag_not_found", "pydicom/tests/test_dictionary.py::TestDict::test_repeaters", "pydicom/tests/test_dictionary.py::TestDict::test_repeater_has_tag", "pydicom/tests/test_dictionary.py::TestDict::test_repeater_has_keyword", "pydicom/tests/test_dictionary.py::TestDict::test_get_private_entry", "pydicom/tests/test_dictionary.py::TestDict::test_add_entry", "pydicom/tests/test_dictionary.py::TestDict::test_add_entry_raises_for_private_tag", "pydicom/tests/test_dictionary.py::TestDict::test_add_entries", "pydicom/tests/test_dictionary.py::TestDict::test_add_entries_raises_for_private_tags", "pydicom/tests/test_dictionary.py::TestDict::test_add_private_entry", "pydicom/tests/test_dictionary.py::TestDict::test_add_private_entry_raises_for_non_private_tag", "pydicom/tests/test_dictionary.py::TestDict::test_add_private_entries", "pydicom/tests/test_dictionary.py::TestDict::test_add_private_entries_raises_for_non_private_tags", "pydicom/tests/test_dictionary.py::TestDict::test_dictionary_VM", "pydicom/tests/test_dictionary.py::TestDict::test_private_dict_VR", "pydicom/tests/test_dictionary.py::TestDict::test_private_dict_VM"], "environment_setup_commit": "0fa18d2a2179c92efc22200ed6b3689e66cecf92"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1413", "base_commit": "f909c76e31f759246cec3708dadd173c5d6e84b1", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -433,13 +433,24 @@ def value(self) -> Any:\n @value.setter\n def value(self, val: Any) -> None:\n \"\"\"Convert (if necessary) and set the value of the element.\"\"\"\n+ # Ignore backslash characters in these VRs, based on:\n+ # * Which str VRs can have backslashes in Part 5, Section 6.2\n+ # * All byte VRs\n+ exclusions = [\n+ 'LT', 'OB', 'OD', 'OF', 'OL', 'OV', 'OW', 'ST', 'UN', 'UT',\n+ 'OB/OW', 'OW/OB', 'OB or OW', 'OW or OB',\n+ # Probably not needed\n+ 'AT', 'FD', 'FL', 'SQ', 'SS', 'SL', 'UL',\n+ ]\n+\n # Check if is a string with multiple values separated by '\\'\n # If so, turn them into a list of separate strings\n # Last condition covers 'US or SS' etc\n- if isinstance(val, (str, bytes)) and self.VR not in \\\n- ['UT', 'ST', 'LT', 'FL', 'FD', 'AT', 'OB', 'OW', 'OF', 'SL',\n- 'SQ', 'SS', 'UL', 'OB/OW', 'OW/OB', 'OB or OW',\n- 'OW or OB', 'UN'] and 'US' not in self.VR:\n+ if (\n+ isinstance(val, (str, bytes))\n+ and self.VR not in exclusions\n+ and 'US' not in self.VR\n+ ):\n try:\n if _backslash_str in val:\n val = cast(str, val).split(_backslash_str)\n", "test_patch": "diff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -1546,3 +1546,16 @@ def test_set_value(vr, pytype, vm0, vmN, keyword):\n elem = ds[keyword]\n assert elem.value == list(vmN)\n assert list(vmN) == elem.value\n+\n+\[email protected](\"vr, pytype, vm0, vmN, keyword\", VALUE_REFERENCE)\n+def test_assigning_bytes(vr, pytype, vm0, vmN, keyword):\n+ \"\"\"Test that byte VRs are excluded from the backslash check.\"\"\"\n+ if pytype == bytes:\n+ ds = Dataset()\n+ value = b\"\\x00\\x01\" + b\"\\\\\" + b\"\\x02\\x03\"\n+ setattr(ds, keyword, value)\n+ elem = ds[keyword]\n+ assert elem.VR == vr\n+ assert elem.value == value\n+ assert elem.VM == 1\n", "problem_statement": "Error : a bytes-like object is required, not 'MultiValue'\nHello,\r\n\r\nI am getting following error while updating the tag LongTrianglePointIndexList (0066,0040),\r\n**TypeError: a bytes-like object is required, not 'MultiValue'**\r\n\r\nI noticed that the error gets produced only when the VR is given as \"OL\" , works fine with \"OB\", \"OF\" etc.\r\n\r\nsample code (assume 'lineSeq' is the dicom dataset sequence):\r\n```python\r\nimport pydicom\r\nimport array\r\ndata=list(range(1,10))\r\ndata=array.array('H', indexData).tostring() # to convert to unsigned short\r\nlineSeq.add_new(0x00660040, 'OL', data) \r\nds.save_as(\"mydicom\")\r\n```\r\noutcome: **TypeError: a bytes-like object is required, not 'MultiValue'**\r\n\r\nusing version - 2.0.0.0\r\n\r\nAny help is appreciated.\r\n\r\nThank you\n", "hints_text": "Also tried following code to get the byte string, but same error.\r\n1. data=array.array('L', indexData).tostring() # to convert to long -> same error\r\n2. data=array.array('Q', indexData).tostring() # to convert to long long -> same error\r\n\r\n\nO* VRs should be `bytes`. Use `array.tobytes()` instead of `tostring()`?\r\n\r\nAlso, in the future if have an issue it's much more helpful if you post the full traceback rather than the error since we can look at it to figure out where in the code the exception is occurring.\r\n\r\nIt would also help if you posted the version of Python you're using. \r\n\r\nThis works fine for me with Python 3.9 and pydicom 2.1.2:\r\n```python\r\nfrom pydicom import Dataset\r\nimport array\r\n\r\narr = array.array('H', range(10))\r\nds = Dataset()\r\nds.is_little_endian = True\r\nds.is_implicit_VR = False\r\nds.LongTrianglePointIndexList = arr.tobytes()\r\nprint(ds[\"LongTrianglePointIndexList\"].VR) # 'OL'\r\nds.save_as('temp.dcm')\r\n```\r\nThis also works fine:\r\n```python\r\nds = Dataset()\r\nds.add_new(0x00660040, 'OL', arr.tobytes())\r\n```\nThank you for the answer.\r\nUnfortunately the error still persists with above code.\r\nPlease find the attached detailed error.\r\n[error.txt](https://github.com/pydicom/pydicom/files/6661451/error.txt)\r\n\r\nOne more information is that the 'ds' is actually read from a file in the disk (ds=pydicom.read_file(filename)). \r\nand this byte array is stored under the following sequence\r\nds[0x0066,0x0002][0][0x0066,0x0013][0][0x0066,0x0028][0][0x0066,0x0040] = arr.tobytes()\r\n\r\npydicom - 2.0.0.0\r\npython - 3.6.4\r\n\r\nThank you.\nCould you post a minimal code sample that reproduces the issue please?\r\n\r\nIf you're using something like this:\r\n`ds[0x0066,0x0002][0][0x0066,0x0013][0][0x0066,0x0028][0][0x0066,0x0040] = arr.tobytes()`\r\n\r\nThen you're missing the `.value` assignment:\r\n`ds[0x0066,0x0002][0][0x0066,0x0013][0][0x0066,0x0028][0][0x0066,0x0040].value = arr.tobytes()`\nHello,\r\nabove code line I just mentioned to give an idea where the actual data is stored (tree level).\r\n\r\nPlease find the actual code used below,\r\n```python\r\nimport pydicom\r\nfrom pydicom.sequence import Sequence\r\nfrom pydicom.dataelem import DataElement\r\nfrom pydicom.dataset import Dataset\r\n\r\nds = pydicom.read_file(filename)\r\nsurfaceSeq= ds[0x0066,0x0002]\r\n\r\n#// read existing sequence items in the dataset\r\nseqlist=[]\r\nfor n in surfaceSeq:\r\n seqlist.append(n)\r\n\r\nnewDs = Dataset()\r\n \r\nsurfaceMeshPrimitiveSq = Dataset()\r\nlineSeq = Dataset()\r\nindexData = list(range(1,100))\r\nindexData = array.array('H', indexData)\r\nindexData = indexData.tobytes()\r\nlineSeq.add_new(0x00660040, 'OL', indexData) \r\nsurfaceMeshPrimitiveSq.add_new(0x00660028, 'SQ', [lineSeq])\r\nnewDs.add_new(0x00660013, 'SQ', [surfaceMeshPrimitiveSq])\r\n\r\n#add the new sequnce item to the list\r\nseqlist.append(newDs)\r\nds[0x0066,0x0002] = DataElement(0x00660002,\"SQ\",seqlist)\r\nds.save_as(filename)\r\n```\nOK, I can reproduce with:\r\n```python\r\n\r\nimport array\r\n\r\nfrom pydicom import Dataset\r\nfrom pydicom.uid import ExplicitVRLittleEndian\r\n\r\nds = Dataset()\r\nds.file_meta = Dataset()\r\nds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian\r\n\r\nb = array.array('H', range(100)).tobytes()\r\n\r\nds.LongPrimitivePointIndexList = b\r\nds.save_as('1421.dcm')\r\n```\r\nAnd `print(ds)` gives:\r\n```\r\n(0066, 0040) Long Primitive Point Index List OL: [b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00\\x04\\x00\\x05\\x00\\x06\\x00\\x07\\x00\\x08\\x00\\t\\x00\\n\\x00\\x0b\\x00\\x0c\\x00\\r\\x00\\x0e\\x00\\x0f\\x00\\x10\\x00\\x11\\x00\\x12\\x00\\x13\\x00\\x14\\x00\\x15\\x00\\x16\\x00\\x17\\x00\\x18\\x00\\x19\\x00\\x1a\\x00\\x1b\\x00\\x1c\\x00\\x1d\\x00\\x1e\\x00\\x1f\\x00 \\x00!\\x00\"\\x00#\\x00$\\x00%\\x00&\\x00\\'\\x00(\\x00)\\x00*\\x00+\\x00,\\x00-\\x00.\\x00/\\x000\\x001\\x002\\x003\\x004\\x005\\x006\\x007\\x008\\x009\\x00:\\x00;\\x00<\\x00=\\x00>\\x00?\\x00@\\x00A\\x00B\\x00C\\x00D\\x00E\\x00F\\x00G\\x00H\\x00I\\x00J\\x00K\\x00L\\x00M\\x00N\\x00O\\x00P\\x00Q\\x00R\\x00S\\x00T\\x00U\\x00V\\x00W\\x00X\\x00Y\\x00Z\\x00[\\x00', b'\\x00]\\x00^\\x00_\\x00`\\x00a\\x00b\\x00c\\x00']\r\n```\r\nI think this is because the byte value is hitting the hex for the backslash character during assignment. Ouch, that's kinda nasty.", "created_at": "2021-06-16T09:47:08Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::test_assigning_bytes[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OV-bytes-vm020-vmN20-SelectorOVValue]"], "PASS_TO_PASS": ["pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestTM::test_pickling_tm_from_time", "pydicom/tests/test_valuerep.py::TestTM::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestTM::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_comparison", "pydicom/tests/test_valuerep.py::TestTM::test_time_behavior", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDT::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDT::test_comparison", "pydicom/tests/test_valuerep.py::TestDT::test_datetime_behavior", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDA::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDA::test_comparison", "pydicom/tests/test_valuerep.py::TestDA::test_date_behavior", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[3.14159265358979]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[-1234.456e78]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E-5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E+5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[+1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[42", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[nan]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[3.141592653589793]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1,000]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[127.0.0.1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1.e]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.0-1.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.0-0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.0--0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.123-0.123]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.321--0.321]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1e-05-1e-05]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[3.141592653589793-3.14159265358979]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-3.141592653589793--3.1415926535898]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[5.385940192876374e-07-5.3859401929e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-5.385940192876374e-07--5.385940193e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[12342534378.125532-12342534378.1255]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[64070869985876.78-64070869985876.8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.7976931348623157e+308-1.797693135e+308]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_wrong_type", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling", "pydicom/tests/test_valuerep.py::TestDSfloat::test_new_empty", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str_value", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_length", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat_auto_format", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-nan]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan2]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSfloat::test_hash", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_new_empty", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_str_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_repr", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val4]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val5]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val6]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val7]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal_auto_format", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_hash", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_str_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestIS::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestIS::test_hash", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains", "pydicom/tests/test_valuerep.py::TestPersonName::test_length", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_veterinary", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator_from_bytes", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time", "pydicom/tests/test_valuerep.py::test_person_name_unicode_warns", "pydicom/tests/test_valuerep.py::test_set_value[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_set_value[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_set_value[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_set_value[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_set_value[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_set_value[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_set_value[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_set_value[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_set_value[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_set_value[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_set_value[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_set_value[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_set_value[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_set_value[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[OV-bytes-vm020-vmN20-SelectorOVValue]", "pydicom/tests/test_valuerep.py::test_set_value[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_set_value[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_set_value[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_set_value[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_set_value[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_set_value[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_set_value[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_set_value[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_set_value[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_set_value[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_set_value[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_set_value[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_set_value[UV-int-vm037-vmN37-SelectorUVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UV-int-vm037-vmN37-SelectorUVValue]"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1090", "base_commit": "5098c9147fadcb3e5918487036867931435adeb8", "patch": "diff --git a/pydicom/filereader.py b/pydicom/filereader.py\n--- a/pydicom/filereader.py\n+++ b/pydicom/filereader.py\n@@ -710,7 +710,7 @@ def read_partial(fileobj, stop_when=None, defer_size=None,\n is_implicit_VR = False\n is_little_endian = False\n elif transfer_syntax == pydicom.uid.DeflatedExplicitVRLittleEndian:\n- # See PS3.6-2008 A.5 (p 71)\n+ # See PS3.5 section A.5\n # when written, the entire dataset following\n # the file metadata was prepared the normal way,\n # then \"deflate\" compression applied.\ndiff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -3,6 +3,7 @@\n \n \n import warnings\n+import zlib\n from struct import pack\n \n from pydicom.charset import (\n@@ -15,7 +16,8 @@\n from pydicom.multival import MultiValue\n from pydicom.tag import (Tag, ItemTag, ItemDelimiterTag, SequenceDelimiterTag,\n tag_in_exception)\n-from pydicom.uid import UncompressedPixelTransferSyntaxes\n+from pydicom.uid import (UncompressedPixelTransferSyntaxes,\n+ DeflatedExplicitVRLittleEndian)\n from pydicom.valuerep import extra_length_VRs\n from pydicom.values import convert_numbers\n \n@@ -727,6 +729,42 @@ def write_file_meta_info(fp, file_meta, enforce_standard=True):\n fp.write(buffer.getvalue())\n \n \n+def _write_dataset(fp, dataset, write_like_original):\n+ \"\"\"Write the Data Set to a file-like. Assumes the file meta information,\n+ if any, has been written.\n+ \"\"\"\n+\n+ # if we want to write with the same endianess and VR handling as\n+ # the read dataset we want to preserve raw data elements for\n+ # performance reasons (which is done by get_item);\n+ # otherwise we use the default converting item getter\n+ if dataset.is_original_encoding:\n+ get_item = Dataset.get_item\n+ else:\n+ get_item = Dataset.__getitem__\n+\n+ # WRITE DATASET\n+ # The transfer syntax used to encode the dataset can't be changed\n+ # within the dataset.\n+ # Write any Command Set elements now as elements must be in tag order\n+ # Mixing Command Set with other elements is non-conformant so we\n+ # require `write_like_original` to be True\n+ command_set = get_item(dataset, slice(0x00000000, 0x00010000))\n+ if command_set and write_like_original:\n+ fp.is_implicit_VR = True\n+ fp.is_little_endian = True\n+ write_dataset(fp, command_set)\n+\n+ # Set file VR and endianness. MUST BE AFTER writing META INFO (which\n+ # requires Explicit VR Little Endian) and COMMAND SET (which requires\n+ # Implicit VR Little Endian)\n+ fp.is_implicit_VR = dataset.is_implicit_VR\n+ fp.is_little_endian = dataset.is_little_endian\n+\n+ # Write non-Command Set elements now\n+ write_dataset(fp, get_item(dataset, slice(0x00010000, None)))\n+\n+\n def dcmwrite(filename, dataset, write_like_original=True):\n \"\"\"Write `dataset` to the `filename` specified.\n \n@@ -938,15 +976,6 @@ def dcmwrite(filename, dataset, write_like_original=True):\n else:\n fp = DicomFileLike(filename)\n \n- # if we want to write with the same endianess and VR handling as\n- # the read dataset we want to preserve raw data elements for\n- # performance reasons (which is done by get_item);\n- # otherwise we use the default converting item getter\n- if dataset.is_original_encoding:\n- get_item = Dataset.get_item\n- else:\n- get_item = Dataset.__getitem__\n-\n try:\n # WRITE FILE META INFORMATION\n if preamble:\n@@ -954,31 +983,32 @@ def dcmwrite(filename, dataset, write_like_original=True):\n fp.write(preamble)\n fp.write(b'DICM')\n \n+ tsyntax = None\n if dataset.file_meta: # May be an empty Dataset\n # If we want to `write_like_original`, don't enforce_standard\n write_file_meta_info(fp, dataset.file_meta,\n enforce_standard=not write_like_original)\n+ tsyntax = getattr(dataset.file_meta, \"TransferSyntaxUID\", None)\n+\n+ if (tsyntax == DeflatedExplicitVRLittleEndian):\n+ # See PS3.5 section A.5\n+ # when writing, the entire dataset following\n+ # the file metadata is prepared the normal way,\n+ # then \"deflate\" compression applied.\n+ buffer = DicomBytesIO()\n+ _write_dataset(buffer, dataset, write_like_original)\n+\n+ # Compress the encoded data and write to file\n+ compressor = zlib.compressobj(wbits=-zlib.MAX_WBITS)\n+ deflated = compressor.compress(buffer.parent.getvalue())\n+ deflated += compressor.flush()\n+ if len(deflated) % 2:\n+ deflated += b'\\x00'\n+\n+ fp.write(deflated)\n+ else:\n+ _write_dataset(fp, dataset, write_like_original)\n \n- # WRITE DATASET\n- # The transfer syntax used to encode the dataset can't be changed\n- # within the dataset.\n- # Write any Command Set elements now as elements must be in tag order\n- # Mixing Command Set with other elements is non-conformant so we\n- # require `write_like_original` to be True\n- command_set = get_item(dataset, slice(0x00000000, 0x00010000))\n- if command_set and write_like_original:\n- fp.is_implicit_VR = True\n- fp.is_little_endian = True\n- write_dataset(fp, command_set)\n-\n- # Set file VR and endianness. MUST BE AFTER writing META INFO (which\n- # requires Explicit VR Little Endian) and COMMAND SET (which requires\n- # Implicit VR Little Endian)\n- fp.is_implicit_VR = dataset.is_implicit_VR\n- fp.is_little_endian = dataset.is_little_endian\n-\n- # Write non-Command Set elements now\n- write_dataset(fp, get_item(dataset, slice(0x00010000, None)))\n finally:\n if not caller_owns_file:\n fp.close()\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -11,6 +11,7 @@\n \n from struct import unpack\n from tempfile import TemporaryFile\n+import zlib\n \n import pytest\n \n@@ -49,6 +50,7 @@\n \n unicode_name = get_charset_files(\"chrH31.dcm\")[0]\n multiPN_name = get_charset_files(\"chrFrenMulti.dcm\")[0]\n+deflate_name = get_testdata_file(\"image_dfl.dcm\")\n \n base_version = '.'.join(str(i) for i in __version_info__)\n \n@@ -77,6 +79,18 @@ def bytes_identical(a_bytes, b_bytes):\n return False, pos # False if not identical, position of 1st diff\n \n \n+def as_assertable(dataset):\n+ \"\"\"Copy the elements in a Dataset (including the file_meta, if any)\n+ to a set that can be safely compared using pytest's assert.\n+ (Datasets can't be so compared because DataElements are not\n+ hashable.)\"\"\"\n+ safe_dict = dict((str(elem.tag) + \" \" + elem.keyword, elem.value)\n+ for elem in dataset)\n+ if hasattr(dataset, \"file_meta\"):\n+ safe_dict.update(as_assertable(dataset.file_meta))\n+ return safe_dict\n+\n+\n class TestWriteFile(object):\n def setup(self):\n self.file_out = TemporaryFile('w+b')\n@@ -222,6 +236,41 @@ def test_write_empty_sequence(self):\n ds = read_file(self.file_out)\n assert ds.PerformedProcedureCodeSequence == []\n \n+ def test_write_deflated_retains_elements(self):\n+ \"\"\"Read a Deflated Explicit VR Little Endian file, write it,\n+ and then read the output, to verify that the written file\n+ contains the same data.\n+ \"\"\"\n+ original = read_file(deflate_name)\n+ original.save_as(self.file_out)\n+\n+ self.file_out.seek(0)\n+ rewritten = read_file(self.file_out)\n+\n+ assert as_assertable(rewritten) == as_assertable(original)\n+\n+ def test_write_deflated_deflates_post_file_meta(self):\n+ \"\"\"Read a Deflated Explicit VR Little Endian file, write it,\n+ and then check the bytes in the output, to verify that the\n+ written file is deflated past the file meta information.\n+ \"\"\"\n+ original = read_file(deflate_name)\n+ original.save_as(self.file_out)\n+\n+ first_byte_past_file_meta = 0x14e\n+ with open(deflate_name, \"rb\") as original_file:\n+ original_file.seek(first_byte_past_file_meta)\n+ original_post_meta_file_bytes = original_file.read()\n+ unzipped_original = zlib.decompress(original_post_meta_file_bytes,\n+ -zlib.MAX_WBITS)\n+\n+ self.file_out.seek(first_byte_past_file_meta)\n+ rewritten_post_meta_file_bytes = self.file_out.read()\n+ unzipped_rewritten = zlib.decompress(rewritten_post_meta_file_bytes,\n+ -zlib.MAX_WBITS)\n+\n+ assert unzipped_rewritten == unzipped_original\n+\n \n class TestScratchWriteDateTime(TestWriteFile):\n \"\"\"Write and reread simple or multi-value DA/DT/TM data elements\"\"\"\n", "problem_statement": "Write deflated content when called Transfer Syntax is Deflated Explicit VR Little Endian\n**Describe the bug**\r\nAfter using `dcmread` to read a deflated .dcm file created from pydicom's [CT_small.dcm sample](https://github.com/pydicom/pydicom/blob/v1.4.2/pydicom/data/test_files/CT_small.dcm), with the following file meta information\r\n```\r\n(0002, 0000) File Meta Information Group Length UL: 178\r\n(0002, 0001) File Meta Information Version OB: b'\\x00\\x01'\r\n(0002, 0002) Media Storage SOP Class UID UI: CT Image Storage\r\n(0002, 0003) Media Storage SOP Instance UID UI: 1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322\r\n(0002, 0010) Transfer Syntax UID UI: Deflated Explicit VR Little Endian\r\n(0002, 0012) Implementation Class UID UI: 1.2.40.0.13.1.1\r\n(0002, 0013) Implementation Version Name SH: 'dcm4che-2.0'\r\n```\r\n\r\nI use `save_as` to save the file. The output file has an unaltered file meta information section, but the group 8 elements and beyond are not written in deflated format, instead appearing to be LEE. In particular, the specific character set element is easily readable from a hex representation of the file, rather than appearing as gobbledygook like one would expect from a deflated stream.\r\n\r\n**Expected behavior**\r\nThe bulk of the DCM to be written as Deflated Explicit VR Little Endian or the Transfer Syntax UID to be saved with a value that reflects the actual format of the DCM\r\n\r\n**Steps To Reproduce**\r\n```python\r\n\u276f py\r\n>>> # CT_small_deflated.dcm is CT_small.dcm, deflated using dcm2dcm\r\n>>> ds = pydicom.dcmread(\"CT_small_deflated.dcm\")\r\n\r\n>>> ds.save_as(\"ds_like_orig.dcm\", write_like_original=True)\r\n>>> pydicom.dcmread(\"ds_like_orig.dcm\")\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"C:\\Users\\blairyat\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\pydicom\\filereader.py\", line 869, in dcmread\r\n dataset = read_partial(fp, stop_when, defer_size=defer_size,\r\n File \"C:\\Users\\blairyat\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\pydicom\\filereader.py\", line 729, in read_partial\r\n unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS)\r\nzlib.error: Error -3 while decompressing data: invalid stored block lengths\r\n\r\n>>> ds.save_as(\"ds_not_like_orig.dcm\", write_like_original=False)\r\n>>> pydicom.dcmread(\"ds_not_like_orig.dcm\")\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"C:\\Users\\blairyat\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\pydicom\\filereader.py\", line 869, in dcmread\r\n dataset = read_partial(fp, stop_when, defer_size=defer_size,\r\n File \"C:\\Users\\blairyat\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\pydicom\\filereader.py\", line 729, in read_partial\r\n unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS)\r\nzlib.error: Error -3 while decompressing data: invalid stored block lengths\r\n```\r\n\r\n**Your environment**\r\nPlease run the following and paste the output.\r\n```powershell\r\n\u276f py -c \"import platform; print(platform.platform())\"\r\nWindows-10-10.0.18362-SP0\r\n\r\n\u276f py -c \"import sys; print('Python ', sys.version)\"\r\nPython 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)]\r\n\r\n\u276f py -c \"import pydicom; print('pydicom ', pydicom.__version__)\"\r\npydicom 1.4.2\r\n```\r\n\n", "hints_text": "Of course, it's entirely possible I'm just not using the library properly.\r\nRegardless, here are my original and generated files, as well as the reproduction steps:\r\n[write_deflated_file.zip](https://github.com/pydicom/pydicom/files/4557981/write_deflated_file.zip)\r\n\r\nThanks for your attention in this. Assuming it's deemed to be a valid bug, I'd be happy to contribute to the development of a solution. (My initial thought is that the Transfer Syntax should be respected and that the file should be written deflated, but I've not investigated deeply.)\nTry setting `ds.is_explicit_VR = True` before saving. Changing the Transfer Syntax isn't enough to control the encoding of the written dataset.\r\n\r\nWe should probably add a warning for when the transfer syntax doesn't match `is_implicit_VR` and `is_little_endian`...\r\n\r\nI'm not sure about deflated off hand, I'll need to check\nThanks, @scaramallion. That had no effect. The output is exactly the same.\r\n\r\nI fear I may not have been clear. I never did change the Transfer Syntax. It stayed at Deflated Explicit VR Little Endian, just as it was in the source\u2026\nWe don't have anything out-of-the-box for writing deflated, this should work:\r\n```python\r\nimport zlib\r\n\r\nfrom pydicom import dcmread\r\nfrom pydicom.data import get_testdata_file\r\nfrom pydicom.filebase import DicomBytesIO\r\nfrom pydicom.filewriter import write_file_meta_info, write_dataset\r\nfrom pydicom.uid import DeflatedExplicitVRLittleEndian\r\n\r\nds = dcmread(get_testdata_file(\"CT_small.dcm\"))\r\nds.file_meta.TransferSyntaxUID = DeflatedExplicitVRLittleEndian\r\n\r\nwith open('deflated.dcm', 'wb') as f:\r\n # Write preamble and DICM marker\r\n f.write(b'\\x00' * 128)\r\n f.write(b'DICM')\r\n # Write file meta information elements\r\n write_file_meta_info(f, ds.file_meta)\r\n\r\n # Encode the dataset\r\n bytesio = DicomBytesIO()\r\n bytesio.is_little_endian = True\r\n bytesio.is_implicit_VR = False\r\n write_dataset(bytesio, ds)\r\n\r\n # Compress the encoded data and write to file\r\n compressor = zlib.compressobj(wbits=-zlib.MAX_WBITS)\r\n deflated = compressor.compress(bytesio.parent.getvalue())\r\n deflated += compressor.flush()\r\n if len(deflated) %2:\r\n deflated += b'\\x00'\r\n\r\n f.write(deflated)\r\n\r\nds = dcmread('deflated.dcm')\r\nprint(ds)\r\n```\nThanks, @scaramallion. Are you looking for a contribution, or are you thinking the design would be would be too complicated for an enthusiastic experienced programmer but first-time pydicomer?\r\n(I'm assuming this would eventually just become automatic behaviour whenever saving something with the matching Transfer Syntax\u2026)\nI think this is definitely a contribution a first-timer could make, take a look at `filewriter.dcmwrite()`, if you add a check for the deflated transfer syntax around [line 968](https://github.com/pydicom/pydicom/blob/master/pydicom/filewriter.py#L968) then encode and deflate accordingly.\n> this is definitely a contribution a first-timer could make\r\n\r\nThen sign me up! Assuming you don't need it by tomorrow. (I won't be super slow. It's just that it's nearly bedtime and I have a day job.)\r\n\nThere's no rush, we (nearly) all have day jobs ", "created_at": "2020-05-01T16:10:56Z", "version": "1.4", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_deflates_post_file_meta"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of_dataset", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "5098c9147fadcb3e5918487036867931435adeb8"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-800", "base_commit": "2f3586b6f67383b1ec0c24c4772e65119c3f5261", "patch": "diff --git a/pydicom/uid.py b/pydicom/uid.py\n--- a/pydicom/uid.py\n+++ b/pydicom/uid.py\n@@ -250,19 +250,19 @@ def generate_uid(prefix=PYDICOM_ROOT_UID, entropy_srcs=None):\n ----------\n prefix : str or None\n The UID prefix to use when creating the UID. Default is the pydicom\n- root UID '1.2.826.0.1.3680043.8.498.'. If None then a value of '2.25.'\n- will be used (as described on `David Clunie's website\n- <http://www.dclunie.com/medical-image-faq/html/part2.html#UID>`_).\n+ root UID '1.2.826.0.1.3680043.8.498.'. If None then a prefix of '2.25.'\n+ will be used with the integer form of a UUID generated using the\n+ UUID4 algorithm.\n entropy_srcs : list of str or None\n- If a list of str, the prefix will be appended with a SHA512 hash of the\n- list which means the result is deterministic and should make the\n- original data unrecoverable. If None random data will be used\n- (default).\n+ If `prefix` is not None, then the prefix will be appended with a\n+ SHA512 hash of the list which means the result is deterministic and\n+ should make the original data unrecoverable. If None random data will\n+ be used (default).\n \n Returns\n -------\n pydicom.uid.UID\n- A 64 character DICOM UID.\n+ A DICOM UID of up to 64 characters.\n \n Raises\n ------\n@@ -275,17 +275,17 @@ def generate_uid(prefix=PYDICOM_ROOT_UID, entropy_srcs=None):\n >>> generate_uid()\n 1.2.826.0.1.3680043.8.498.22463838056059845879389038257786771680\n >>> generate_uid(prefix=None)\n- 2.25.12586835699909622925962004639368649121731805922235633382942\n+ 2.25.167161297070865690102504091919570542144\n >>> generate_uid(entropy_srcs=['lorem', 'ipsum'])\n 1.2.826.0.1.3680043.8.498.87507166259346337659265156363895084463\n >>> generate_uid(entropy_srcs=['lorem', 'ipsum'])\n 1.2.826.0.1.3680043.8.498.87507166259346337659265156363895084463\n \"\"\"\n- max_uid_len = 64\n-\n if prefix is None:\n- prefix = '2.25.'\n+ # UUID -> as 128-bit int -> max 39 characters long\n+ return UID('2.25.{}'.format(uuid.uuid4().int))\n \n+ max_uid_len = 64\n if len(prefix) > max_uid_len - 1:\n raise ValueError(\"The prefix must be less than 63 chars\")\n if not re.match(RE_VALID_UID_PREFIX, prefix):\n", "test_patch": "diff --git a/pydicom/tests/test_uid.py b/pydicom/tests/test_uid.py\n--- a/pydicom/tests/test_uid.py\n+++ b/pydicom/tests/test_uid.py\n@@ -1,6 +1,8 @@\n # Copyright 2008-2018 pydicom authors. See LICENSE file for details.\n \"\"\"Test suite for uid.py\"\"\"\n \n+import uuid\n+\n import pytest\n \n from pydicom.uid import UID, generate_uid, PYDICOM_ROOT_UID, JPEGLSLossy\n@@ -57,6 +59,24 @@ def test_entropy_src_custom(self):\n assert uid == rf\n assert len(uid) == 64\n \n+ def test_none(self):\n+ \"\"\"Test generate_uid(None).\"\"\"\n+ uid = generate_uid(prefix=None)\n+ # Check prefix\n+ assert '2.25.' == uid[:5]\n+ # Check UUID suffix\n+ as_uuid = uuid.UUID(int=int(uid[5:]))\n+ assert isinstance(as_uuid, uuid.UUID)\n+ assert as_uuid.version == 4\n+ assert as_uuid.variant == uuid.RFC_4122\n+\n+ def test_none_iterate(self):\n+ \"\"\"Test generate_uid(None) generates valid UIDs.\"\"\"\n+ # Generate random UIDs, if a bad method then should eventually fail\n+ for ii in range(100000):\n+ uid = generate_uid(None)\n+ assert uid.is_valid\n+\n \n class TestUID(object):\n \"\"\"Test DICOM UIDs\"\"\"\n", "problem_statement": "The function generate_uid() generates non-conforming \u201c2.25 .\u201d DICOM UIDs\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\nIt seems there was already a discussion about this function in the past (#125), but the current implementation generates non-conforming DICOM UIDs when called with prefix \u2018none\u2019 to trigger that the function generate_uid() should generate a UUID derived UID.\r\n\r\nThe DICOM Standard requires (see DICOM PS 3.5, B.2 that when a UUID derived UID is constructed it should be in the format \u201c2.25.\u201d + uuid(in its decimal representation string representation)\r\nFor example a UUID of f81d4fae-7dec-11d0-a765-00a0c91e6bf6 should become 2.25.329800735698586629295641978511506172918\r\n\r\nThe current implementation extends the uuid part to the remaining 59 characters. By not following the DICOM formatting rule, receiving systems that are processing DICOM instances created with this library are not capable of converting the generated \u201c2.25\u201d UID back to a UUID. Due to the extra sha512 operation on the UUID, the variant and version info of the UUID are also lost.\r\n\r\n#### Steps/Code to Reproduce\r\n- call generate_uid() to generate a \"2.25.\" DICOM UID\r\n\r\n#### Expected Results\r\nA conforming unique DICOM UID is returned.\r\n\r\n#### Actual Results\r\nNon conforming UID is returned.\n", "hints_text": "Thanks for pointing this out - I wasn't aware of that section of the standard. Do you know of a solution that respects the privacy issues pointed out in #125? \r\n\r\n> By not following the DICOM formatting rule, receiving systems that are processing DICOM instances created with this library are not capable of converting the generated \u201c2.25\u201d UID back to a UUID\r\n\r\nWhy would it be necessary for the receiving software to generate a \"real UUID\" from this (and therefore the variant and the version)? Just curious, as if we want to be standard compliant it doesn't really matter.\r\n\r\n\r\n\nI think the solution proposed by @cancan101 in #125 to use the uuid v4 algorithm is fine. The uuid v1 algorithm leaks the MAC address. The open source dcm4che (Java) implementation for example also uses the uuid v4 algorithm, the two C# implementation I known of use the .NET Guid.NewGuid() method, which will also returns v4 uuids. \r\n\r\nDICOM is all about interoperability, there may be receiving systems that (implicitly) depend on it. A Level 2 (Full) C-STORE SCP may, (but is not required) validate the attributes of an incoming SOP instance. Personally, I have never encountered a DICOM system that had trouble with it, most systems just threat a UID as 64 bytes and are happy with it as long as it is unique.\r\n\r\nPossible (performance) scenario\r\nLarge DICOM archives need to maintain a relational database to maintain which images are stored in the system. To ensure data integrity, these systems put often a constraint on the uniqueness of the SOP Instance UID column. Most DBMS systems will create a non-cluster index to ensure that this constraint can be met. A uuid is only 16 bytes, compared to a UID that is 64 bytes, which can make the difference of keeping the index in memory or not. Some DBMS systems have a native data type to support uuid columns. The complication is of course that these systems also need to support images with \u201cOrganizationally Derived\u201d UIDs and this optimization only makes sense if a majority of UIDs are uuid derived UIDs.", "created_at": "2019-02-01T07:12:27Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_uid.py::TestGenerateUID::test_none"], "PASS_TO_PASS": ["pydicom/tests/test_uid.py::TestGenerateUID::test_generate_uid", "pydicom/tests/test_uid.py::TestGenerateUID::test_entropy_src", "pydicom/tests/test_uid.py::TestGenerateUID::test_entropy_src_custom", "pydicom/tests/test_uid.py::TestGenerateUID::test_none_iterate", "pydicom/tests/test_uid.py::TestUID::test_equality", "pydicom/tests/test_uid.py::TestUID::test_inequality", "pydicom/tests/test_uid.py::TestUID::test_hash", "pydicom/tests/test_uid.py::TestUID::test_str", "pydicom/tests/test_uid.py::TestUID::test_is_implicit_vr", "pydicom/tests/test_uid.py::TestUID::test_is_little_endian", "pydicom/tests/test_uid.py::TestUID::test_is_deflated", "pydicom/tests/test_uid.py::TestUID::test_is_transfer_syntax", "pydicom/tests/test_uid.py::TestUID::test_is_compressed", "pydicom/tests/test_uid.py::TestUID::test_is_encapsulated", "pydicom/tests/test_uid.py::TestUID::test_name", "pydicom/tests/test_uid.py::TestUID::test_name_with_equal_hash", "pydicom/tests/test_uid.py::TestUID::test_type", "pydicom/tests/test_uid.py::TestUID::test_info", "pydicom/tests/test_uid.py::TestUID::test_is_retired", "pydicom/tests/test_uid.py::TestUID::test_is_valid", "pydicom/tests/test_uid.py::TestUID::test_is_private", "pydicom/tests/test_uid.py::TestUID::test_raises", "pydicom/tests/test_uid.py::TestUID::test_transitive", "pydicom/tests/test_uid.py::TestUIDPrivate::test_equality", "pydicom/tests/test_uid.py::TestUIDPrivate::test_inequality", "pydicom/tests/test_uid.py::TestUIDPrivate::test_hash", "pydicom/tests/test_uid.py::TestUIDPrivate::test_str", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_implicit_vr", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_little_endian", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_deflated", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_transfer_syntax", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_compressed", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_encapsulated", "pydicom/tests/test_uid.py::TestUIDPrivate::test_name", "pydicom/tests/test_uid.py::TestUIDPrivate::test_type", "pydicom/tests/test_uid.py::TestUIDPrivate::test_info", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_retired", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_valid", "pydicom/tests/test_uid.py::TestUIDPrivate::test_is_private"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-938", "base_commit": "6d8ef0bfcec983e5f8bd8a2e359ff318fe9fcf65", "patch": "diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -346,11 +346,12 @@ def __init__(self, val):\n def __str__(self):\n if hasattr(self, 'original_string'):\n return self.original_string\n- else:\n- return super(DSfloat, self).__str__()\n+\n+ # Issue #937 (Python 3.8 compatibility)\n+ return repr(self)[1:-1]\n \n def __repr__(self):\n- return \"\\\"\" + str(self) + \"\\\"\"\n+ return '\"{}\"'.format(super(DSfloat, self).__repr__())\n \n \n class DSdecimal(Decimal):\n@@ -513,11 +514,15 @@ def __init__(self, val):\n elif isinstance(val, IS) and hasattr(val, 'original_string'):\n self.original_string = val.original_string\n \n- def __repr__(self):\n+ def __str__(self):\n if hasattr(self, 'original_string'):\n- return \"\\\"\" + self.original_string + \"\\\"\"\n- else:\n- return \"\\\"\" + int.__str__(self) + \"\\\"\"\n+ return self.original_string\n+\n+ # Issue #937 (Python 3.8 compatibility)\n+ return repr(self)[1:-1]\n+\n+ def __repr__(self):\n+ return '\"{}\"'.format(super(IS, self).__repr__())\n \n \n def MultiString(val, valtype=str):\n", "test_patch": "diff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -90,7 +90,6 @@ def test_pickling(self):\n \n class TestDS(object):\n \"\"\"Unit tests for DS values\"\"\"\n-\n def test_empty_value(self):\n assert DS(None) is None\n assert '' == DS('')\n@@ -106,7 +105,6 @@ def test_float_values(self):\n \n class TestDSfloat(object):\n \"\"\"Unit tests for pickling DSfloat\"\"\"\n-\n def test_pickling(self):\n # Check that a pickled DSFloat is read back properly\n x = pydicom.valuerep.DSfloat(9.0)\n@@ -116,10 +114,25 @@ def test_pickling(self):\n assert x.real == x2.real\n assert x.original_string == x2.original_string\n \n+ def test_str(self):\n+ \"\"\"Test DSfloat.__str__().\"\"\"\n+ val = pydicom.valuerep.DSfloat(1.1)\n+ assert '1.1' == str(val)\n+\n+ val = pydicom.valuerep.DSfloat('1.1')\n+ assert '1.1' == str(val)\n+\n+ def test_repr(self):\n+ \"\"\"Test DSfloat.__repr__().\"\"\"\n+ val = pydicom.valuerep.DSfloat(1.1)\n+ assert '\"1.1\"' == repr(val)\n+\n+ val = pydicom.valuerep.DSfloat('1.1')\n+ assert '\"1.1\"' == repr(val)\n+\n \n class TestDSdecimal(object):\n \"\"\"Unit tests for pickling DSdecimal\"\"\"\n-\n def test_pickling(self):\n # Check that a pickled DSdecimal is read back properly\n # DSdecimal actually prefers original_string when\n@@ -142,7 +155,6 @@ def test_float_value(self):\n \n class TestIS(object):\n \"\"\"Unit tests for IS\"\"\"\n-\n def test_empty_value(self):\n assert IS(None) is None\n assert '' == IS('')\n@@ -182,6 +194,22 @@ def test_overflow(self):\n pydicom.valuerep.IS(3103050000)\n config.enforce_valid_values = original_flag\n \n+ def test_str(self):\n+ \"\"\"Test IS.__str__().\"\"\"\n+ val = pydicom.valuerep.IS(1)\n+ assert '1' == str(val)\n+\n+ val = pydicom.valuerep.IS('1')\n+ assert '1' == str(val)\n+\n+ def test_repr(self):\n+ \"\"\"Test IS.__repr__().\"\"\"\n+ val = pydicom.valuerep.IS(1)\n+ assert '\"1\"' == repr(val)\n+\n+ val = pydicom.valuerep.IS('1')\n+ assert '\"1\"' == repr(val)\n+\n \n class TestBadValueRead(object):\n \"\"\"Unit tests for handling a bad value for a VR\n", "problem_statement": "[python 3.8] failing tests: various issues but \"max recursion depth reached\" seems to be one\n#### Description\r\nFedora is beginning to test python packages against python 3.8. Pydicom builds but tests fail with errors.\r\n\r\n#### Steps/Code to Reproduce\r\n\r\n```\r\npython setup.py build\r\npython setup.py install\r\npytest\r\n```\r\n\r\nThe complete build log is attached. It includes the complete build process. The root log is also attached. These are the versions of other python libraries that are in use:\r\n\r\n```\r\npython3-dateutil-1:2.8.0-5.fc32.noarch\r\npython3-devel-3.8.0~b3-4.fc32.x86_64\r\npython3-numpy-1:1.17.0-3.fc32.x86_64\r\npython3-numpydoc-0.9.1-3.fc32.noarch\r\npython3-pytest-4.6.5-3.fc32.noarch\r\npython3-setuptools-41.0.1-8.fc32.noarch\r\npython3-six-1.12.0-5.fc32.noarch\r\n```\r\n\r\n[build-log.txt](https://github.com/pydicom/pydicom/files/3527558/build-log.txt)\r\n[root-log.txt](https://github.com/pydicom/pydicom/files/3527559/root-log.txt)\r\n\n", "hints_text": "Thanks, @sanjayankur31, we'll look into it.\nLooks like the [culprit](https://docs.python.org/3.8/whatsnew/3.8.html#changes-in-python-behavior) might be:\r\n\r\n> Removed `__str__` implementations from builtin types bool, int, float, complex and few classes from the standard library. They now inherit `__str__()` from object. As result, defining the `__repr__()` method in the subclass of these classes will affect they string representation.\r\n\r\nThe unit test results in the build log shows issues with `DSfloat.__str__()/DSfloat.__repr__()` and `IS.__repr__()` on lines [350](https://github.com/pydicom/pydicom/blob/6d8ef0bfcec983e5f8bd8a2e359ff318fe9fcf65/pydicom/valuerep.py#L353)/353 and [520](https://github.com/pydicom/pydicom/blob/6d8ef0bfcec983e5f8bd8a2e359ff318fe9fcf65/pydicom/valuerep.py#L520) of current master.\r\n", "created_at": "2019-08-22T05:03:01Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::TestDSfloat::test_str", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr"], "PASS_TO_PASS": ["pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1194", "base_commit": "5e70c1dfe09820023fec519dac4c51bebcb7f60d", "patch": "diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -87,6 +87,9 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):\n elem.VR = 'SS'\n byte_type = 'h'\n \n+ if elem.VM == 0:\n+ return elem\n+\n # Need to handle type check for elements with VM > 1\n elem_value = elem.value if elem.VM == 1 else elem.value[0]\n if not isinstance(elem_value, int):\n@@ -115,6 +118,9 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):\n # As per PS3.3 C.11.1.1.1\n if ds.LUTDescriptor[0] == 1:\n elem.VR = 'US'\n+ if elem.VM == 0:\n+ return elem\n+\n elem_value = elem.value if elem.VM == 1 else elem.value[0]\n if not isinstance(elem_value, int):\n elem.value = convert_numbers(elem.value, is_little_endian, 'H')\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -1054,7 +1054,7 @@ def test_not_ambiguous_raw_data_element(self):\n elem = RawDataElement(0x60003000, 'OB', 1, b'\\x00', 0, True, True)\n out = correct_ambiguous_vr_element(elem, Dataset(), True)\n assert out == elem\n- assert type(out) == RawDataElement\n+ assert isinstance(out, RawDataElement)\n \n def test_correct_ambiguous_data_element(self):\n \"\"\"Test correct ambiguous US/SS element\"\"\"\n@@ -1086,10 +1086,28 @@ def test_correct_ambiguous_raw_data_element(self):\n ds[0x00280120] = elem\n ds.PixelRepresentation = 0\n out = correct_ambiguous_vr_element(elem, ds, True)\n- assert type(out) == DataElement\n+ assert isinstance(out, DataElement)\n assert out.VR == 'US'\n assert out.value == 0xfffe\n \n+ def test_empty_value(self):\n+ \"\"\"Regression test for #1193: empty value raises exception.\"\"\"\n+ ds = Dataset()\n+ elem = RawDataElement(0x00280106, 'US or SS', 0, None, 0, True, True)\n+ ds[0x00280106] = elem\n+ out = correct_ambiguous_vr_element(elem, ds, True)\n+ assert isinstance(out, DataElement)\n+ assert out.VR == 'US'\n+\n+ ds.LUTDescriptor = [1, 1, 1]\n+ elem = RawDataElement(0x00283006, 'US or SS', 0, None, 0, True, True)\n+ assert out.value is None\n+ ds[0x00283006] = elem\n+ out = correct_ambiguous_vr_element(elem, ds, True)\n+ assert isinstance(out, DataElement)\n+ assert out.VR == 'US'\n+ assert out.value is None\n+\n \n class TestWriteAmbiguousVR:\n \"\"\"Attempt to write data elements with ambiguous VR.\"\"\"\n", "problem_statement": "Error decoding dataset with ambiguous VR element when the value is None\nHi all,\r\n I used the storescu in pynetdicom 1.5.3 to send the dicom ct files(both on mac and ubuntu): \r\n**python storescu.py 192.168.1.120 9002 ~/Downloads/test/**\r\n(I also tried https://pydicom.github.io/pynetdicom/stable/examples/storage.html#storage-scu)\r\nbut it throwed errors: \r\n\r\n_E: Failed to encode the supplied Dataset\r\nE: Store failed: /Users/me/Downloads/test/CT_S1_118.dcm\r\nE: Failed to encode the supplied Dataset\r\nTraceback (most recent call last):\r\n File \"storescu.py\", line 283, in main\r\n status = assoc.send_c_store(ds, ii)\r\n File \"/Users/me/.pyenv/versions/3.8.2/lib/python3.8/site-packages/pynetdicom/association.py\", line 1736, in send_c_store\r\n raise ValueError('Failed to encode the supplied Dataset')\r\nValueError: Failed to encode the supplied Dataset_\r\n\r\nBut I used to send same files with storescu in dcm4che successfully.\r\nFile attached.\r\n\r\n[test.zip](https://github.com/pydicom/pynetdicom/files/5258867/test.zip)\r\n\n", "hints_text": "```python\r\n>>> from pydicom import dcmread\r\n>>> dcmread(\"CT_S1_001.dcm\")\r\nTraceback (most recent call last):\r\n File \".../pydicom/tag.py\", line 30, in tag_in_exception\r\n yield\r\n File \".../pydicom/filewriter.py\", line 555, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \".../pydicom/dataset.py\", line 1060, in get_item\r\n return self[key]\r\n File \".../pydicom/dataset.py\", line 878, in __getitem__\r\n self[tag] = correct_ambiguous_vr_element(\r\n File \".../pydicom/filewriter.py\", line 160, in correct_ambiguous_vr_element\r\n _correct_ambiguous_vr_element(elem, ds, is_little_endian)\r\n File \".../pydicom/filewriter.py\", line 86, in _correct_ambiguous_vr_element\r\n elem_value = elem.value if elem.VM == 1 else elem.value[0]\r\nTypeError: 'NoneType' object is not subscriptable\r\n```\r\nIssue occurs because the dataset is Implicit VR and the *Smallest Image Pixel Value* is ambiguous but empty,", "created_at": "2020-09-22T03:16:19Z", "version": "2.0", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_empty_value"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_filename", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of_dataset", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "9d69811e539774f296c2f289839147e741251716"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-997", "base_commit": "41e984c8df5533805ae13cbcf419e6c5f63da30c", "patch": "diff --git a/pydicom/encaps.py b/pydicom/encaps.py\n--- a/pydicom/encaps.py\n+++ b/pydicom/encaps.py\n@@ -2,6 +2,7 @@\n \"\"\"Functions for working with encapsulated (compressed) pixel data.\"\"\"\n \n from struct import pack\n+import warnings\n \n import pydicom.config\n from pydicom.filebase import DicomBytesIO\n@@ -50,9 +51,10 @@ def get_frame_offsets(fp):\n \n Returns\n -------\n- list of int\n- The byte offsets to the first fragment of each frame, as measured from\n- the start of the first item following the Basic Offset Table item.\n+ bool, list of int\n+ Whether or not the BOT is empty, and a list of the byte offsets\n+ to the first fragment of each frame, as measured from the start of the\n+ first item following the Basic Offset Table item.\n \n Raises\n ------\n@@ -86,7 +88,41 @@ def get_frame_offsets(fp):\n for ii in range(length // 4):\n offsets.append(fp.read_UL())\n \n- return offsets\n+ return bool(length), offsets\n+\n+\n+def get_nr_fragments(fp):\n+ \"\"\"Return the number of fragments in `fp`.\"\"\"\n+ if not fp.is_little_endian:\n+ raise ValueError(\"'fp.is_little_endian' must be True\")\n+\n+ nr_fragments = 0\n+ start = fp.tell()\n+ while True:\n+ try:\n+ tag = Tag(fp.read_tag())\n+ except EOFError:\n+ break\n+\n+ if tag == 0xFFFEE000:\n+ # Item\n+ length = fp.read_UL()\n+ if length == 0xFFFFFFFF:\n+ raise ValueError(\"Undefined item length at offset {} when \"\n+ \"parsing the encapsulated pixel data \"\n+ \"fragments.\".format(fp.tell() - 4))\n+ fp.seek(length, 1)\n+ nr_fragments += 1\n+ elif tag == 0xFFFEE0DD:\n+ # Sequence Delimiter\n+ break\n+ else:\n+ raise ValueError(\"Unexpected tag '{}' at offset {} when parsing \"\n+ \"the encapsulated pixel data fragment items.\"\n+ .format(tag, fp.tell() - 4))\n+\n+ fp.seek(start)\n+ return nr_fragments\n \n \n def generate_pixel_data_fragment(fp):\n@@ -175,7 +211,7 @@ def generate_pixel_data_fragment(fp):\n .format(tag, fp.tell() - 4))\n \n \n-def generate_pixel_data_frame(bytestream):\n+def generate_pixel_data_frame(bytestream, nr_frames=None):\n \"\"\"Yield an encapsulated pixel data frame.\n \n Parameters\n@@ -184,6 +220,10 @@ def generate_pixel_data_frame(bytestream):\n The value of the (7fe0, 0010) *Pixel Data* element from an encapsulated\n dataset. The Basic Offset Table item should be present and the\n Sequence Delimiter item may or may not be present.\n+ nr_frames : int, optional\n+ Required for multi-frame data when the Basic Offset Table is empty\n+ and there are multiple frames. This should be the value of (0028,0008)\n+ *Number of Frames*.\n \n Yields\n ------\n@@ -194,11 +234,11 @@ def generate_pixel_data_frame(bytestream):\n ----------\n DICOM Standard Part 5, :dcm:`Annex A <part05/chapter_A.html>`\n \"\"\"\n- for fragmented_frame in generate_pixel_data(bytestream):\n+ for fragmented_frame in generate_pixel_data(bytestream, nr_frames):\n yield b''.join(fragmented_frame)\n \n \n-def generate_pixel_data(bytestream):\n+def generate_pixel_data(bytestream, nr_frames=None):\n \"\"\"Yield an encapsulated pixel data frame.\n \n For the following transfer syntaxes, a fragment may not contain encoded\n@@ -230,6 +270,10 @@ def generate_pixel_data(bytestream):\n The value of the (7fe0, 0010) *Pixel Data* element from an encapsulated\n dataset. The Basic Offset Table item should be present and the\n Sequence Delimiter item may or may not be present.\n+ nr_frames : int, optional\n+ Required for multi-frame data when the Basic Offset Table is empty\n+ and there are multiple frames. This should be the value of (0028,0008)\n+ *Number of Frames*.\n \n Yields\n -------\n@@ -237,6 +281,14 @@ def generate_pixel_data(bytestream):\n An encapsulated pixel data frame, with the contents of the\n :class:`tuple` the frame's fragmented data.\n \n+ Notes\n+ -----\n+ If the Basic Offset Table is empty and there are multiple fragments per\n+ frame then an attempt will be made to locate the frame boundaries by\n+ searching for the JPEG/JPEG-LS/JPEG2000 EOI/EOC marker (``0xFFD9``). If the\n+ marker is not present or the pixel data hasn't been compressed using one of\n+ the JPEG standards then the generated pixel data may be incorrect.\n+\n References\n ----------\n DICOM Standard Part 5, :dcm:`Annex A <part05/chapter_A.html>`\n@@ -245,28 +297,90 @@ def generate_pixel_data(bytestream):\n fp.is_little_endian = True\n \n # `offsets` is a list of the offsets to the first fragment in each frame\n- offsets = get_frame_offsets(fp)\n+ has_bot, offsets = get_frame_offsets(fp)\n # Doesn't actually matter what the last offset value is, as long as its\n # greater than the total number of bytes in the fragments\n offsets.append(len(bytestream))\n \n- frame = []\n- frame_length = 0\n- frame_number = 0\n- for fragment in generate_pixel_data_fragment(fp):\n- if frame_length < offsets[frame_number + 1]:\n- frame.append(fragment)\n+ if has_bot:\n+ # Use the BOT to determine the frame boundaries\n+ frame = []\n+ frame_length = 0\n+ frame_number = 0\n+ for fragment in generate_pixel_data_fragment(fp):\n+ if frame_length < offsets[frame_number + 1]:\n+ frame.append(fragment)\n+ else:\n+ yield tuple(frame)\n+ frame = [fragment]\n+ frame_number += 1\n+\n+ frame_length += len(fragment) + 8\n+\n+ # Yield the final frame - required here because the frame_length will\n+ # never be greater than offsets[-1] and thus never trigger the final\n+ # yield within the for block\n+ yield tuple(frame)\n+ else:\n+ nr_fragments = get_nr_fragments(fp)\n+ if nr_fragments == 1:\n+ # Single fragment: 1 frame\n+ for fragment in generate_pixel_data_fragment(fp):\n+ yield tuple([fragment])\n+ elif nr_frames:\n+ # Multiple fragments: 1 or more frames\n+ if nr_fragments == nr_frames:\n+ # 1 fragment per frame\n+ # Covers RLE and others if 1:1 ratio\n+ for fragment in generate_pixel_data_fragment(fp):\n+ yield tuple([fragment])\n+ elif nr_frames == 1:\n+ # Multiple fragments: 1 frame\n+ frame = []\n+ for fragment in generate_pixel_data_fragment(fp):\n+ frame.append(fragment)\n+ yield tuple(frame)\n+ elif nr_fragments > nr_frames:\n+ # More fragments then frames\n+ # Search for JPEG/JPEG-LS/JPEG2K EOI/EOC marker\n+ # Should be the last two bytes of a frame\n+ # May fail if no EOI/EOC marker or not JPEG\n+ eoi_marker = b'\\xff\\xd9'\n+ frame = []\n+ frame_nr = 0\n+ for fragment in generate_pixel_data_fragment(fp):\n+ frame.append(fragment)\n+ if eoi_marker in fragment[-10:]:\n+ yield tuple(frame)\n+ frame_nr += 1\n+ frame = []\n+\n+ if frame or frame_nr != nr_frames:\n+ # If data in `frame` or fewer frames yielded then we\n+ # must've missed a frame boundary\n+ warnings.warn(\n+ \"The end of the encapsulated pixel data has been \"\n+ \"reached but one or more frame boundaries may have \"\n+ \"been missed; please confirm that the generated frame \"\n+ \"data is correct\"\n+ )\n+ if frame:\n+ yield tuple(frame)\n+\n+ else:\n+ # Fewer fragments than frames\n+ raise ValueError(\n+ \"Unable to parse encapsulated pixel data as the Basic \"\n+ \"Offset Table is empty and there are fewer fragments then \"\n+ \"frames; the dataset may be corrupt\"\n+ )\n else:\n- yield tuple(frame)\n- frame = [fragment]\n- frame_number += 1\n-\n- frame_length += len(fragment) + 8\n-\n- # Yield the final frame - required here because the frame_length will\n- # never be greater than offsets[-1] and thus never trigger the final yield\n- # within the for block\n- yield tuple(frame)\n+ # Multiple fragments but unknown number of frames\n+ raise ValueError(\n+ \"Unable to determine the frame boundaries for the \"\n+ \"encapsulated pixel data as the Basic Offset Table is empty \"\n+ \"and `nr_frames` parameter is None\"\n+ )\n \n \n def decode_data_sequence(data):\n", "test_patch": "diff --git a/pydicom/tests/test_encaps.py b/pydicom/tests/test_encaps.py\n--- a/pydicom/tests/test_encaps.py\n+++ b/pydicom/tests/test_encaps.py\n@@ -4,10 +4,11 @@\n import pytest\n \n from pydicom import dcmread\n-from pydicom.data import get_testdata_files\n+from pydicom.data import get_testdata_file\n from pydicom.encaps import (\n generate_pixel_data_fragment,\n get_frame_offsets,\n+ get_nr_fragments,\n generate_pixel_data_frame,\n generate_pixel_data,\n decode_data_sequence,\n@@ -20,7 +21,7 @@\n from pydicom.filebase import DicomBytesIO\n \n \n-JP2K_10FRAME_NOBOT = get_testdata_files('emri_small_jpeg_2k_lossless.dcm')[0]\n+JP2K_10FRAME_NOBOT = get_testdata_file('emri_small_jpeg_2k_lossless.dcm')\n \n \n class TestGetFrameOffsets(object):\n@@ -57,7 +58,7 @@ def test_zero_length(self):\n b'\\x00\\x00\\x00\\x00'\n fp = DicomBytesIO(bytestream)\n fp.is_little_endian = True\n- assert [0] == get_frame_offsets(fp)\n+ assert (False, [0]) == get_frame_offsets(fp)\n \n def test_multi_frame(self):\n \"\"\"Test reading multi-frame BOT item\"\"\"\n@@ -69,7 +70,7 @@ def test_multi_frame(self):\n b'\\xFE\\x37\\x00\\x00'\n fp = DicomBytesIO(bytestream)\n fp.is_little_endian = True\n- assert [0, 4966, 9716, 14334] == get_frame_offsets(fp)\n+ assert (True, [0, 4966, 9716, 14334]) == get_frame_offsets(fp)\n \n def test_single_frame(self):\n \"\"\"Test reading single-frame BOT item\"\"\"\n@@ -78,7 +79,7 @@ def test_single_frame(self):\n b'\\x00\\x00\\x00\\x00'\n fp = DicomBytesIO(bytestream)\n fp.is_little_endian = True\n- assert [0] == get_frame_offsets(fp)\n+ assert (True, [0]) == get_frame_offsets(fp)\n \n def test_not_little_endian(self):\n \"\"\"Test reading big endian raises exception\"\"\"\n@@ -91,6 +92,113 @@ def test_not_little_endian(self):\n get_frame_offsets(fp)\n \n \n+class TestGetNrFragments(object):\n+ \"\"\"Test encaps.get_nr_fragments\"\"\"\n+ def test_item_undefined_length(self):\n+ \"\"\"Test exception raised if item length undefined.\"\"\"\n+ bytestream = (\n+ b'\\xFE\\xFF\\x00\\xE0'\n+ b'\\xFF\\xFF\\xFF\\xFF'\n+ b'\\x00\\x00\\x00\\x01'\n+ )\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = True\n+ with pytest.raises(ValueError):\n+ get_nr_fragments(fp)\n+\n+ def test_item_sequence_delimiter(self):\n+ \"\"\"Test that the fragments are returned if seq delimiter hit.\"\"\"\n+ bytestream = (\n+ b'\\xFE\\xFF\\x00\\xE0'\n+ b'\\x04\\x00\\x00\\x00'\n+ b'\\x01\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\xDD\\xE0'\n+ b'\\x00\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0'\n+ b'\\x04\\x00\\x00\\x00'\n+ b'\\x02\\x00\\x00\\x00'\n+ )\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = True\n+ assert 1 == get_nr_fragments(fp)\n+\n+ def test_item_bad_tag(self):\n+ \"\"\"Test exception raised if item has unexpected tag\"\"\"\n+ bytestream = (\n+ b'\\xFE\\xFF\\x00\\xE0'\n+ b'\\x04\\x00\\x00\\x00'\n+ b'\\x01\\x00\\x00\\x00'\n+ b'\\x10\\x00\\x10\\x00'\n+ b'\\x00\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0'\n+ b'\\x04\\x00\\x00\\x00'\n+ b'\\x02\\x00\\x00\\x00'\n+ )\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = True\n+ msg = (\n+ r\"Unexpected tag '\\(0010, 0010\\)' at offset 12 when parsing the \"\n+ r\"encapsulated pixel data fragment items.\"\n+ )\n+ with pytest.raises(ValueError, match=msg):\n+ get_nr_fragments(fp)\n+\n+ def test_single_fragment_no_delimiter(self):\n+ \"\"\"Test single fragment is returned OK\"\"\"\n+ bytestream = b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x01\\x00\\x00\\x00'\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = True\n+ assert 1 == get_nr_fragments(fp)\n+\n+ def test_multi_fragments_no_delimiter(self):\n+ \"\"\"Test multi fragments are returned OK\"\"\"\n+ bytestream = b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x01\\x00\\x00\\x00' \\\n+ b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x06\\x00\\x00\\x00' \\\n+ b'\\x01\\x02\\x03\\x04\\x05\\x06'\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = True\n+ assert 2 == get_nr_fragments(fp)\n+\n+ def test_single_fragment_delimiter(self):\n+ \"\"\"Test single fragment is returned OK with sequence delimiter item\"\"\"\n+ bytestream = b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x01\\x00\\x00\\x00' \\\n+ b'\\xFE\\xFF\\xDD\\xE0'\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = True\n+ assert 1 == get_nr_fragments(fp)\n+\n+ def test_multi_fragments_delimiter(self):\n+ \"\"\"Test multi fragments are returned OK with sequence delimiter item\"\"\"\n+ bytestream = b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x01\\x00\\x00\\x00' \\\n+ b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x06\\x00\\x00\\x00' \\\n+ b'\\x01\\x02\\x03\\x04\\x05\\x06' \\\n+ b'\\xFE\\xFF\\xDD\\xE0'\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = True\n+ assert 2 == get_nr_fragments(fp)\n+\n+ def test_not_little_endian(self):\n+ \"\"\"Test reading big endian raises exception\"\"\"\n+ bytestream = b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x01\\x00\\x00\\x00'\n+ fp = DicomBytesIO(bytestream)\n+ fp.is_little_endian = False\n+ with pytest.raises(ValueError,\n+ match=\"'fp.is_little_endian' must be True\"):\n+ get_nr_fragments(fp)\n+\n+\n class TestGeneratePixelDataFragment(object):\n \"\"\"Test encaps.generate_pixel_data_fragment\"\"\"\n def test_item_undefined_length(self):\n@@ -242,7 +350,7 @@ def test_empty_bot_triple_fragment_single_frame(self):\n b'\\xFE\\xFF\\x00\\xE0' \\\n b'\\x04\\x00\\x00\\x00' \\\n b'\\x03\\x00\\x00\\x00'\n- frames = generate_pixel_data_frame(bytestream)\n+ frames = generate_pixel_data_frame(bytestream, 1)\n assert next(frames) == (\n b'\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00'\n )\n@@ -362,6 +470,18 @@ def test_multi_frame_varied_ratio(self):\n assert next(frames) == b'\\x03\\x00\\x00\\x00\\x02\\x04'\n pytest.raises(StopIteration, next, frames)\n \n+ def test_empty_bot_multi_fragments_per_frame(self):\n+ \"\"\"Test multi-frame where multiple frags per frame and no BOT.\"\"\"\n+ # Regression test for #685\n+ ds = dcmread(JP2K_10FRAME_NOBOT)\n+ assert 10 == ds.NumberOfFrames\n+ frame_gen = generate_pixel_data_frame(ds.PixelData, ds.NumberOfFrames)\n+ for ii in range(10):\n+ next(frame_gen)\n+\n+ with pytest.raises(StopIteration):\n+ next(frame_gen)\n+\n \n class TestGeneratePixelData(object):\n \"\"\"Test encaps.generate_pixel_data\"\"\"\n@@ -391,12 +511,122 @@ def test_empty_bot_triple_fragment_single_frame(self):\n b'\\xFE\\xFF\\x00\\xE0' \\\n b'\\x04\\x00\\x00\\x00' \\\n b'\\x03\\x00\\x00\\x00'\n- frames = generate_pixel_data(bytestream)\n+ frames = generate_pixel_data(bytestream, 1)\n assert next(frames) == (b'\\x01\\x00\\x00\\x00',\n b'\\x02\\x00\\x00\\x00',\n b'\\x03\\x00\\x00\\x00')\n pytest.raises(StopIteration, next, frames)\n \n+ def test_empty_bot_no_nr_frames_raises(self):\n+ \"\"\"Test parsing raises if not BOT and no nr_frames.\"\"\"\n+ # 1 frame, 3 fragments long\n+ bytestream = b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x00\\x00\\x00\\x00' \\\n+ b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x01\\x00\\x00\\x00' \\\n+ b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x02\\x00\\x00\\x00' \\\n+ b'\\xFE\\xFF\\x00\\xE0' \\\n+ b'\\x04\\x00\\x00\\x00' \\\n+ b'\\x03\\x00\\x00\\x00'\n+ msg = (\n+ r\"Unable to determine the frame boundaries for the \"\n+ r\"encapsulated pixel data as the Basic Offset Table is empty \"\n+ r\"and `nr_frames` parameter is None\"\n+ )\n+ with pytest.raises(ValueError, match=msg):\n+ next(generate_pixel_data(bytestream))\n+\n+ def test_empty_bot_too_few_fragments(self):\n+ \"\"\"Test parsing with too few fragments.\"\"\"\n+ ds = dcmread(JP2K_10FRAME_NOBOT)\n+ assert 10 == ds.NumberOfFrames\n+\n+ msg = (\n+ r\"Unable to parse encapsulated pixel data as the Basic \"\n+ r\"Offset Table is empty and there are fewer fragments then \"\n+ r\"frames; the dataset may be corrupt\"\n+ )\n+ with pytest.raises(ValueError, match=msg):\n+ next(generate_pixel_data_frame(ds.PixelData, 20))\n+\n+ def test_empty_bot_multi_fragments_per_frame(self):\n+ \"\"\"Test parsing with multiple fragments per frame.\"\"\"\n+ # 4 frames in 6 fragments with JPEG EOI marker\n+ bytestream = (\n+ b'\\xFE\\xFF\\x00\\xE0\\x00\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xD9\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\x00\\xFF\\xD9'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xD9\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xD9\\x00'\n+ )\n+\n+ frames = generate_pixel_data(bytestream, 4)\n+ for ii in range(4):\n+ next(frames)\n+\n+ with pytest.raises(StopIteration):\n+ next(frames)\n+\n+ def test_empty_bot_no_marker(self):\n+ \"\"\"Test parsing not BOT and no final marker with multi fragments.\"\"\"\n+ # 4 frames in 6 fragments with JPEG EOI marker (1 missing EOI)\n+ bytestream = (\n+ b'\\xFE\\xFF\\x00\\xE0\\x00\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xD9\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xD9\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xFF\\xD9'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\x00\\x00'\n+ )\n+\n+ frames = generate_pixel_data(bytestream, 4)\n+ for ii in range(3):\n+ next(frames)\n+\n+ msg = (\n+ r\"The end of the encapsulated pixel data has been \"\n+ r\"reached but one or more frame boundaries may have \"\n+ r\"been missed; please confirm that the generated frame \"\n+ r\"data is correct\"\n+ )\n+ with pytest.warns(UserWarning, match=msg):\n+ next(frames)\n+\n+ with pytest.raises(StopIteration):\n+ next(frames)\n+\n+ def test_empty_bot_missing_marker(self):\n+ \"\"\"Test parsing not BOT and missing marker with multi fragments.\"\"\"\n+ # 4 frames in 6 fragments with JPEG EOI marker (1 missing EOI)\n+ bytestream = (\n+ b'\\xFE\\xFF\\x00\\xE0\\x00\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xD9\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\x00\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\x00\\x00'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xFF\\xD9'\n+ b'\\xFE\\xFF\\x00\\xE0\\x04\\x00\\x00\\x00\\x01\\xFF\\xD9\\x00'\n+ )\n+\n+ msg = (\n+ r\"The end of the encapsulated pixel data has been \"\n+ r\"reached but one or more frame boundaries may have \"\n+ r\"been missed; please confirm that the generated frame \"\n+ r\"data is correct\"\n+ )\n+ with pytest.warns(UserWarning, match=msg):\n+ ii = 0\n+ for frames in generate_pixel_data(bytestream, 4):\n+ ii += 1\n+\n+ assert 3 == ii\n+\n def test_bot_single_fragment(self):\n \"\"\"Test a single-frame image where the frame is one fragment\"\"\"\n # 1 frame, 1 fragment long\n@@ -932,7 +1162,7 @@ def test_encapsulate_single_fragment_per_frame_bot(self):\n \n fp = DicomBytesIO(data)\n fp.is_little_endian = True\n- offsets = get_frame_offsets(fp)\n+ length, offsets = get_frame_offsets(fp)\n assert offsets == [\n 0x0000, # 0\n 0x0eee, # 3822\n", "problem_statement": "Generators in encaps don't handle single fragment per frame correctly with no BOT value\n#### Description\r\nGenerators in `encaps.py` handling of encapsulated pixel data incorrect when the Basic Offset Table has no value and each frame is a single fragment.\r\n\r\n#### Steps/Code to Reproduce\r\n```python\r\nfrom pydicom import dcmread\r\nfrom pydicom.encaps import generate_pixel_data_frame\r\n\r\nfpath = 'pydicom/data/test_files/emri_small_jpeg_2k_lossless.dcm'\r\nds = dcmread(fpath)\r\nds.NumberOfFrames # 10\r\nframe_generator = generate_pixel_data_frame(ds.PixelData)\r\nnext(frame_generator)\r\nnext(frame_generator) # StopIteration raised\r\n```\r\n\r\n#### Expected Results\r\nAll 10 frames of the pixel data should be accessible.\r\n\r\n#### Actual Results\r\nOnly the first frame is accessible.\n[MRG] Some pixel handlers will not decode multiple fragments per frame\n\r\n\r\nAdded test cases to demonstrate failures for jpeg ls with multiple fragments per frame. The test files were created with dcmtk 3.6.1 using dcmcjpls +fs 1. One file has an offset table, the other does not.\r\n\r\n#### Reference Issue\r\nSee #685 \r\n\r\n\r\n#### What does this implement/fix? Explain your changes.\r\nThese test cases show that the pixel decoders (jpeg and jpeg_ls most likely) will not handle multiple fragments per frame.\r\n\r\nNo fix yet...\r\n\r\nAny suggestions?\n", "hints_text": "The problem is that as far as I can tell there's no unambiguous way to determine the difference between one frame with multiple fragments and multiple frames of 1 fragment each when the Basic Offset Table (Part 5, Annex A.4 and Section 8.2) has no value. You can look at the NumberOfFrames value but that won't help if the number of fragments is larger than the number of frames (indicating one or more frames has multiple fragments).\r\n\r\nI could add a parser that determines the number of Items in the Pixel Data, and if the BOT has no value then compare that against the number of frames and use that to determine the generator yields. It seems clunky though.\r\n\r\nAnyone have a better idea?\r\n\r\n\nAs long as you are not speaking about arbitrary access to single frames, it shall be possible to ignore the offset table completely and just decode fragments sequentially, checking for the decoded frame size as you go along, and yield the next frame as soon as it has the correct frame size (or larger in case of padding). \r\n\r\nThis is in case I didn't miss something here, and only valid for the generator as opposed to arbitrary frame access.\nOk, I did miss something here - the frame is not decoded by the generator, but only later by the pixel data handler, so we won't know the decoded fragment size at that point. \r\nWe could change the logic respectively (hand over each fragment to the pixel handler for decoding), but that would change the behavior, and also may be slower (or not, not sure).\r\n\r\nYou could at least check if the number of frames is the same as the number of fragments (which is probably the most common case) and handle that case, and also the case where the number of fragment is a multiple of the number of frames (which is less sure), but for other cases, you really need to decode the data to be on the sure side. \nAs I recall when I first did this some time ago, I had an awful time trying to deal with frames and fragments. I ended up just focusing on getting it to work with the EMRI images I had for test cases and not really worrying about individual frame boundaries. I am pretty sure where the pixel handler code says \"for frame in CompressedPixelDataSeq\", it is actually looping over each fragment...\r\n\r\nI am pretty sure the handlers will fail when there is more than one fragment per frame...\r\n\n> I am pretty sure the handlers will fail when there is more than one fragment per frame..\r\n\r\nIn this case maybe it makes sense to restructure the code to use the handlers to decode each fragment. Not sure if this would be a compatibility issue for existing code, though. \nThe test cases I added for jpeg_ls have a different number of fragments per frame in the sequence. I have to imagine that if the the offset table is empty for a muiltframe image, then the best you can do is assume one fragment per frame (that is what the code currently does). Reading the standard, it is unclear to me that having an empty offset table with more than one fragment per frame is valid. \r\n\r\nI would welcome a more expert opinion on this. \r\n\r\n\nAs far as I can see, the standard does not enforce a value for the offset table in any case, so this would be valid. I have no idea if this is used in the real world, but I wouldn't exclude the possibility.\nI just added some changes to #688 that change the jpeg_ls handler to more properly use generate_pixel_data_frame rather than decode_data_sequence. This fixes the test case of multiple fragments per frame with an offset table. \r\n\r\nFor the case of no offset table, then maybe we can just go fragment by fragment with:\r\n\r\n```\r\nfor fragment in data:\r\n frame.append(fragment)\r\n try:\r\n decompress(frame)\r\n print \"yea! this is a valid frame\"\r\n except:\r\n print \"not quite done yet\"\r\n\r\n```\nLooks promising! I'm off to my day job now, may have another look in the evening.\nI was thinking of modifying the frame generator so the following logic applies:\r\n```\r\nif no BOT value:\r\n if NumberOfFrames == (number of pixel data items):\r\n # Multiple fragments, one frame each\r\n elif NumberOfFrames == 1:\r\n # One or more fragments, one frame\r\n elif (number of pixel data items) == 1:\r\n # One fragment, one frame\r\n else:\r\n # Multiple fragments, but no way to tell what fragments are what frame\r\n raise exception, tell user they should use the \r\n fragment generator and their own judgement?\r\n```\r\nIn the last case I think the only way to generate the frame correctly is if the BOT has a value.\r\n\r\nEdit - Or to try to decompress? But not all encapsulated data has to be compressed...\nIs it guaranteed that decompressing a frame will fail if the frame isn't complete? What's the performance penalty for a failed decompress?\n> I was thinking of modifying the frame generator so the following logic applies\r\n\r\nI think this sounds good. The last case is the real problem, of course. I have been thinking about decompressing it, too, but I'm not sure how decompressing/decoding separate fragments behaves. \r\nA working but probably slow solution would be to try to decompress a fragment as proposed, and if that fails, or if the resulting image is too small for a frame, try again with another fragment appended (the decoder itself could do this incrementally, but we don't have control over that). I don't know if there is the possibility to decode fragments independently - that would be easier (e.g. no need to append fragments), but I doubt that.\r\nAnyway, that would basically mean either to transfer a part of the generator logic to the pixel handlers, or make the generator dependend on the pixel handlers.\r\nIt would be good if we had some test data with multiple fragments per frame to check this... I may have to think a bit more about this, having no real experience in this field.\nFor all the JPEG syntaxes (Jpeg200, Jpeg-LS, jpeg), a single frame always ends with a End-of-Image (EOI in JPEG/JPEG-LS, EOC in JPEG2K) that is \"FF D9\". If there are N frames, there should always be exactly N of those markers in the fragments. \r\n\r\nSo, for JPEG family, we could loop over the fragments:\r\n\r\n```\r\n\r\nframe = bytearray()\r\nfor fragment in data:\r\n frame.extend(fragment)\r\n if \"FFD9\" in frame[-10:]:\r\n print \"Hooray! The frame is done\"\r\n break\r\n else:\r\n print \"Still more to do\"\r\n\r\n```\r\n\r\nAlthough the try decompress ... except should work with jpeg syntaxes, there is no requirement that a decoder fail on an incomplete frame (it could just return decompressed data and wait for more input) (the current api we use will fail on incomplete images - but no guarantees). \r\n\r\nFor the RLE syntaxes, there is only one fragment per frame.\r\n\r\nFor uncompressed syntaxes, the size of each frame may be determined by BitsStored x Rows x Cols.\r\n\r\n\nThat is much better! As we don't support any other compressed syntaxes apart from JPEG and RLE syntaxes, this should be sufficient to handle these cases. This also makes it possible to get some kind of indexed access for the worst case by building up the missing offset table ourselves if needed.\r\nThat logic has to be in the handlers though, or at some intermediate level, as it is the same for all JPEG syntaxes.\nIs it possible to hit FF D9 because that's the value at that offset, not because we're at the end of the frame? Or is this only in the JPEG pixel data handlers?\r\n\r\nI keep getting confused whether were talking about the pixel data handlers or the generator functions in encaps.\nThis is only for JPEG handlers. FF D9 is guaranteed to not be in the encoded data. It is a reserved JPEG marker.\n> I keep getting confused whether were talking about the pixel data handlers or the generator functions in encaps.\r\n\r\nThis is currently a bit mixed up. The current implementation of the generator functions does not know about specific transfer syntaxes - with the proposed PR this would change. Maybe the generator could ask the pixel handler about a fragment being the last in a frame in case it doesn't know that, and the JPEG pixel handlers implement the logic (which should be in some common place for all JPEG handlers)?\r\n\n@rhaxton @scaramallion - this would be a good candidate for 1.2, in my opinion. Is this doable? Do you need help for the conflict resolving?\n@rhaxton, @scaramallion, pinging on this issue again ... was this ever resolved completely? I'll assign to v1.4 milestone for now, perhaps we can try to look at this in the coming months?\nHello @rhaxton! Thanks for updating the PR.\n\n\n\n\n\n\n\n\n\n\n\nCheers ! There are no PEP8 issues in this Pull Request. :beers: \n\n##### Comment last updated on August 06, 2018 at 18:28 Hours UTC\n@mrbean-bremen If you could take a quick look at this particularly why there are issues with python 3, that would be a great help...\r\n\nThis will still fail for uncompressed frames with no BoT value.\r\n\r\nAlso the docstrings need updating.\nI've been thinking it might be better to change `get_frame_offsets` to return an empty list if the BoT has no value rather than trying to be clever about it since the two cases (BoT has no value and BoT has single 0 offset) may represent different things. Then the functions that rely on it should be updated accordingly.\nCan someone come up with a test case for an encapsulated uncompressed PixelData image? I can't figure out how to create one with dcmtk...\r\nAlso, the standard explicitly calls out RLE syntax as having one fragment per frame, and calls out JPEG as possibly having more than one fragment per frame, but I couldn't find any statement about the fragments per frame for uncompressed syntax. Any ideas on that one?\nI have some code I'm working on that should at least return mixed fragments/frame native data in a single blob while still following your approach for JPEG data.\r\n\r\n```python\r\n# N fragments, M frames; without BOT values there's no generic\r\n# way to determine where a frame ends so we try our best\r\nframe = []\r\nframe_number = 0\r\nfor fragment in generate_pixel_data_fragment(fp):\r\n # For JPEG transfer syntaxes try to locate the EOC marker\r\n if b'\\xFF\\xD9' in fragment[-10:]:\r\n yield tuple(frame)\r\n frame_number += 1\r\n frame = []\r\n else:\r\n frame.append(fragment)\r\n\r\n# If we failed to locate the EOC marker then either nothing will\r\n# have been yielded and/or one or more frames will have been\r\n# skipped. This will be the case with native transfer syntaxes\r\nif frame_number != no_frames:\r\n yield tuple(frame)\r\n```\r\n\r\n[Here](https://github.com/pydicom/pydicom/files/2252088/encap_jpeg.zip) is some JPEG 2x2 11 frame encapsulated data with and without BOT (1 fragment per frame and 2 fragments per frame).\r\n\r\n[Here](https://github.com/pydicom/pydicom/files/2252147/encap_native.zip) is some native 2x2 11 frame encapsulated data with and without BOT (1 fragment per frame and 2 fragments per frame).\r\n\r\nImage pattern is black upper left, white upper right, white lower left, black lower right and the black pixels shade to white over the frames. Maybe just double check the encapsulation has been performed correctly. \r\n\r\nWith the code above the no BOT/native/2 fragments per frame returns a blob of the entire pixel data, but I'd expect that in that case the numpy pixel handler should be able to rearrange the data into frames correctly, provided the blob is the right length. The no BOT/jpeg/2 fragments per frame returns the frames correctly.\nI'm a bit confused by this. When I read [this section](http://dicom.nema.org/dicom/2013/output/chtml/part05/sect_8.2.html) of DICOM, it seems to imply that Uncompressed and Encapsulated are mutually exclusive? I don't know if I have ever seen a DICOM uncompressed image with encapsulated pixel data. Has anyone else?\r\n\nWhoops, obviously I've gotten confused about this somewhere. Nevermind me then...\r\n\r\n[This is what I've done.](https://github.com/scaramallion/pydicom/blob/dev-encaps/pydicom/encaps.py#L247)\n@rhaxton , @scaramallion - what is the state of this PR (apart from having conflicts) - can it make it into the 1.4 release?", "created_at": "2019-12-19T01:02:16Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_bad_tag", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_bad_length_multiple", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_zero_length", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_multi_frame", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_single_frame", "pydicom/tests/test_encaps.py::TestGetFrameOffsets::test_not_little_endian", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_item_undefined_length", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_item_sequence_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_item_bad_tag", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_single_fragment_no_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_multi_fragments_no_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_single_fragment_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_multi_fragments_delimiter", "pydicom/tests/test_encaps.py::TestGetNrFragments::test_not_little_endian", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_item_undefined_length", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_item_sequence_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_item_bad_tag", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_single_fragment_no_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_multi_fragments_no_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_single_fragment_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_multi_fragments_delimiter", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFragment::test_not_little_endian", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_empty_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_empty_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_multi_frame_one_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_multi_frame_three_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_multi_frame_varied_ratio", "pydicom/tests/test_encaps.py::TestGeneratePixelDataFrames::test_empty_bot_multi_fragments_per_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_no_nr_frames_raises", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_too_few_fragments", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_multi_fragments_per_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_no_marker", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_empty_bot_missing_marker", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_bot_single_fragment", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_multi_frame_one_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_multi_frame_three_to_one", "pydicom/tests/test_encaps.py::TestGeneratePixelData::test_multi_frame_varied_ratio", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_empty_bot_single_fragment", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_empty_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_bot_single_fragment", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_bot_triple_fragment_single_frame", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_multi_frame_one_to_one", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_multi_frame_three_to_one", "pydicom/tests/test_encaps.py::TestDecodeDataSequence::test_multi_frame_varied_ratio", "pydicom/tests/test_encaps.py::TestDefragmentData::test_defragment", "pydicom/tests/test_encaps.py::TestReadItem::test_item_undefined_length", "pydicom/tests/test_encaps.py::TestReadItem::test_item_sequence_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_item_sequence_delimiter_zero_length", "pydicom/tests/test_encaps.py::TestReadItem::test_item_bad_tag", "pydicom/tests/test_encaps.py::TestReadItem::test_single_fragment_no_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_multi_fragments_no_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_single_fragment_delimiter", "pydicom/tests/test_encaps.py::TestReadItem::test_multi_fragments_delimiter", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_single_fragment_even_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_single_fragment_odd_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_even_fragment_even_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_even_fragment_odd_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_odd_fragments_even_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_odd_fragments_odd_data", "pydicom/tests/test_encaps.py::TestFragmentFrame::test_too_many_fragments_raises", "pydicom/tests/test_encaps.py::TestEncapsulateFrame::test_single_item", "pydicom/tests/test_encaps.py::TestEncapsulateFrame::test_two_items", "pydicom/tests/test_encaps.py::TestEncapsulate::test_encapsulate_single_fragment_per_frame_no_bot", "pydicom/tests/test_encaps.py::TestEncapsulate::test_encapsulate_single_fragment_per_frame_bot", "pydicom/tests/test_encaps.py::TestEncapsulate::test_encapsulate_bot"], "PASS_TO_PASS": [], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-811", "base_commit": "7d0889e7143f5d4773fa74606efa816ed4e54c9f", "patch": "diff --git a/pydicom/filereader.py b/pydicom/filereader.py\n--- a/pydicom/filereader.py\n+++ b/pydicom/filereader.py\n@@ -689,7 +689,8 @@ def read_partial(fileobj, stop_when=None, defer_size=None,\n \n # Check to see if there's anything left to read\n peek = fileobj.read(1)\n- fileobj.seek(-1, 1)\n+ if peek != b'':\n+ fileobj.seek(-1, 1)\n \n # `filobj` should be positioned at the start of the dataset by this point.\n # Ensure we have appropriate values for `is_implicit_VR` and\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -672,6 +672,14 @@ def test_no_dataset(self):\n self.assertEqual(ds.file_meta, Dataset())\n self.assertEqual(ds[:], Dataset())\n \n+ def test_empty_file(self):\n+ \"\"\"Test reading no elements from file produces empty Dataset\"\"\"\n+ with tempfile.NamedTemporaryFile() as f:\n+ ds = dcmread(f, force=True)\n+ self.assertTrue(ds.preamble is None)\n+ self.assertEqual(ds.file_meta, Dataset())\n+ self.assertEqual(ds[:], Dataset())\n+\n def test_dcmread_does_not_raise(self):\n \"\"\"Test that reading from DicomBytesIO does not raise on EOF.\n Regression test for #358.\"\"\"\n", "problem_statement": "0 byte file causes traceback on dcmreader\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\nTrying to open a 0 byte file with dcmreader causes a traceback originating in the read_partial method. The problem is line 692 in filereader.py (GitHub):\r\n` fileobj.seek(-1, 1)`\r\nChanging this to:\r\n` if peek != b'':\r\n fileobj.seek(-1, 1)`\r\nAppears to solve the problem, but I don't have the experience to test thoroughly.\r\n\r\n#### Steps/Code to Reproduce\r\nCreate a 0 byte file\r\n$ touch mysillyfile.dcm\r\nStart python, import pydicom and read the the file\r\n$ python3\r\nPython 3.6.8 (default, Jan 3 2019, 16:11:14) \r\n[GCC 8.2.1 20181215 (Red Hat 8.2.1-6)] on linux\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n>>> import pydicom\r\n>>> image = pydicom.dcmread('mysillyfile.dcm',force=True)\r\n\r\n#### Expected Results\r\nShould either warn that the file is not DICOM or exit gracefully\r\n\r\n#### Actual Results\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/usr/local/lib/python3.6/site-packages/pydicom/filereader.py\", line 880, in dcmread\r\n force=force, specific_tags=specific_tags)\r\n File \"/usr/local/lib/python3.6/site-packages/pydicom/filereader.py\", line 693, in read_partial\r\n fileobj.seek(-1, 1)\r\nOSError: [Errno 22] Invalid argument\r\n\r\n#### Versions\r\n>>> import platform; print(platform.platform())\r\nLinux-4.19.16-200.fc28.x86_64-x86_64-with-fedora-28-Twenty_Eight\r\n>>> import sys; print(\"Python\", sys.version)\r\nPython 3.6.8 (default, Jan 3 2019, 16:11:14) \r\n[GCC 8.2.1 20181215 (Red Hat 8.2.1-6)]\r\n>>> import numpy; print(\"numpy\", numpy.__version__)\r\nnumpy 1.16.1\r\n>>> import pydicom; print(\"pydicom\", pydicom.__version__)\r\npydicom 1.2.2\r\n>>> \r\n\r\nRegards\r\nAlan\r\n\r\n<!-- Thanks for contributing! -->\r\n\n", "hints_text": "Good catch! There is actually a test for this, but it tests a byte stream instead of a file, and seeking back past begin in a byte stream seems not to be a problem.", "created_at": "2019-03-05T20:48:34Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::ReaderTests::test_empty_file"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::ReaderTests::testCT", "pydicom/tests/test_filereader.py::ReaderTests::testCTPixelData", "pydicom/tests/test_filereader.py::ReaderTests::testDeflate", "pydicom/tests/test_filereader.py::ReaderTests::testDir", "pydicom/tests/test_filereader.py::ReaderTests::testEmptyNumbersTag", "pydicom/tests/test_filereader.py::ReaderTests::testExplicitVRBigEndianNoMeta", "pydicom/tests/test_filereader.py::ReaderTests::testExplicitVRLittleEndianNoMeta", "pydicom/tests/test_filereader.py::ReaderTests::testMR", "pydicom/tests/test_filereader.py::ReaderTests::testNestedPrivateSQ", "pydicom/tests/test_filereader.py::ReaderTests::testNoForce", "pydicom/tests/test_filereader.py::ReaderTests::testNoMetaGroupLength", "pydicom/tests/test_filereader.py::ReaderTests::testNoPixelsRead", "pydicom/tests/test_filereader.py::ReaderTests::testNoTransferSyntaxInMeta", "pydicom/tests/test_filereader.py::ReaderTests::testPlanarConfig", "pydicom/tests/test_filereader.py::ReaderTests::testPrivateSQ", "pydicom/tests/test_filereader.py::ReaderTests::testRTDose", "pydicom/tests/test_filereader.py::ReaderTests::testRTPlan", "pydicom/tests/test_filereader.py::ReaderTests::testRTstruct", "pydicom/tests/test_filereader.py::ReaderTests::testSpecificTags", "pydicom/tests/test_filereader.py::ReaderTests::testSpecificTagsWithUnknownLengthSQ", "pydicom/tests/test_filereader.py::ReaderTests::testSpecificTagsWithUnknownLengthTag", "pydicom/tests/test_filereader.py::ReaderTests::testUTF8FileName", "pydicom/tests/test_filereader.py::ReaderTests::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::ReaderTests::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::ReaderTests::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::ReaderTests::test_group_length_wrong", "pydicom/tests/test_filereader.py::ReaderTests::test_long_specific_char_set", "pydicom/tests/test_filereader.py::ReaderTests::test_meta_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_AE", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::DeferredReadTests::testFileExists", "pydicom/tests/test_filereader.py::DeferredReadTests::testTimeCheck", "pydicom/tests/test_filereader.py::DeferredReadTests::testValuesIdentical", "pydicom/tests/test_filereader.py::DeferredReadTests::testZippedDeferred", "pydicom/tests/test_filereader.py::ReadTruncatedFileTests::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::FileLikeTests::testReadFileGivenFileLikeObject", "pydicom/tests/test_filereader.py::FileLikeTests::testReadFileGivenFileObject", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1539", "base_commit": "a125a02132c2db5ff5cad445e4722802dd5a8d55", "patch": "diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -272,7 +272,12 @@ def write_numbers(fp: DicomIO, elem: DataElement, struct_format: str) -> None:\n \n def write_OBvalue(fp: DicomIO, elem: DataElement) -> None:\n \"\"\"Write a data_element with VR of 'other byte' (OB).\"\"\"\n- fp.write(cast(bytes, elem.value))\n+ if len(elem.value) % 2:\n+ # Pad odd length values\n+ fp.write(cast(bytes, elem.value))\n+ fp.write(b'\\x00')\n+ else:\n+ fp.write(cast(bytes, elem.value))\n \n \n def write_OWvalue(fp: DicomIO, elem: DataElement) -> None:\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -474,6 +474,20 @@ def test_write_ascii_vr_with_padding(self):\n data_elem = DataElement(0x00080060, 'CS', b'REG')\n self.check_data_element(data_elem, expected)\n \n+ def test_write_OB_odd(self):\n+ \"\"\"Test an odd-length OB element is padded during write\"\"\"\n+ value = b'\\x00\\x01\\x02'\n+ elem = DataElement(0x7FE00010, 'OB', value)\n+ encoded_elem = self.encode_element(elem)\n+ ref_bytes = b'\\xe0\\x7f\\x10\\x00\\x04\\x00\\x00\\x00' + value + b\"\\x00\"\n+ assert ref_bytes == encoded_elem\n+\n+ # Empty data\n+ elem.value = b''\n+ encoded_elem = self.encode_element(elem)\n+ ref_bytes = b'\\xe0\\x7f\\x10\\x00\\x00\\x00\\x00\\x00'\n+ assert ref_bytes == encoded_elem\n+\n def test_write_OD_implicit_little(self):\n \"\"\"Test writing elements with VR of OD works correctly.\"\"\"\n # VolumetricCurvePoints\n", "problem_statement": "pydicom produces invalid DICOM files if ds.EncapsulatedDocument contains byte array of odd length\n**Bug Description**\r\nWhen inserting a byte array of odd length into the ds.EncapsulatedDocument field, and saving this as a DICOM file, the DICOM file produced is not valid. This happens because the resulting file produced also have an odd number of bytes in the (0042,0011) OB Encapsulated Document DICOM tag which is not allowed according to the DICOM sepcification for Value Fields, http://dicom.nema.org/dicom/2013/output/chtml/part05/chapter_7.html\r\n\r\n**Expected behavior**\r\nEither pydicom could through and error specifying that the ds.EncapsulatedDocument field should contain an array of even length, or it could fix the problem by add and extra zero byte to the end of the ds.EncapsulatedDocument byte array when the length is odd.\r\n\r\n**Steps To Reproduce**\r\nI have written the following pdf2dcm.py command line utility to mimic the behaviour of pdf2dcm in the dcmtk suite:\r\n\r\n```python\r\n# inspired by: https://github.com/rohithkumar31/pdf2dicom\r\n\r\nimport argparse\r\nimport pydicom\r\n\r\nEncapsulatedPDFStorage = '1.2.840.10008.5.1.4.1.1.104.1'\r\n\r\n\r\ndef generate_dicom_from_pdf(input_file, output_file, zero_pad=True):\r\n file_meta = pydicom.dataset.Dataset()\r\n\r\n # FileMetaInformationGroupLength only gets rewritten when saved if present\r\n file_meta.FileMetaInformationGroupLength = 206\r\n\r\n file_meta.MediaStorageSOPClassUID = EncapsulatedPDFStorage\r\n\r\n file_meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid(pydicom.uid.PYDICOM_ROOT_UID)\r\n\r\n # from: https://pydicom.github.io/pydicom/dev/reference/uid.html\r\n file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian\r\n\r\n pydicom.dataset.validate_file_meta(file_meta, enforce_standard=True)\r\n\r\n # see: http://dicom.nema.org/dicom/2013/output/chtml/part10/chapter_7.html\r\n preamble = b\"\\0\" * 128\r\n\r\n ds = pydicom.dataset.FileDataset(output_file, {}, file_meta=file_meta, preamble=preamble)\r\n # ds.fix_meta_info()\r\n\r\n ds.is_little_endian = True\r\n ds.is_implicit_VR = False\r\n\r\n ds.SpecificCharacterSet = 'ISO_IR 100'\r\n\r\n import datetime\r\n dt = datetime.datetime.now()\r\n ds.InstanceCreationDate = dt.strftime('%Y%m%d')\r\n ds.InstanceCreationTime = dt.strftime('%H%M%S') # ('%H%M%S.%f')\r\n\r\n ds.SOPClassUID = EncapsulatedPDFStorage\r\n ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID\r\n ds.StudyDate = None\r\n ds.AcquisitionDateTime = None\r\n ds.StudyTime = None\r\n ds.ContentTime = None\r\n ds.ContentDate = None\r\n ds.AccessionNumber = None\r\n ds.Modality = 'DOC' # document\r\n ds.ConversionType = 'WSD' # workstation\r\n ds.Manufacturer = None\r\n ds.ReferringPhysicianName = None\r\n ds.PatientName = None\r\n ds.PatientID = None\r\n ds.PatientBirthDate = None\r\n ds.PatientSex = None\r\n ds.StudyInstanceUID = pydicom.uid.generate_uid()\r\n ds.SeriesInstanceUID = pydicom.uid.generate_uid()\r\n ds.StudyID = None\r\n ds.SeriesNumber = 1\r\n ds.InstanceNumber = 1\r\n ds.BurnedInAnnotation = 'YES'\r\n ds.ConceptNameCodeSequence = None\r\n # ConceptNameCodeSequence also sets: ds.SequenceDelimitationItem\r\n ds.DocumentTitle = None\r\n\r\n with open(input_file, 'rb') as f:\r\n pdf_file_as_bytes = f.read()\r\n\r\n # DICOM Value Fields must according to the\r\n # specification be an even number of bytes, see:\r\n # http://dicom.nema.org/dicom/2013/output/chtml/part05/chapter_7.html\r\n if zero_pad and len(pdf_file_as_bytes) % 2 != 0:\r\n pdf_file_as_bytes += b\"\\0\"\r\n\r\n ds.EncapsulatedDocument = pdf_file_as_bytes\r\n ds.MIMETypeOfEncapsulatedDocument = 'application/pdf'\r\n\r\n ds.save_as(output_file)\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--disable-zero-padding', action='store_false')\r\n parser.add_argument('-i', '--input-file')\r\n parser.add_argument('-o', '--output-file')\r\n args = parser.parse_args()\r\n\r\n generate_dicom_from_pdf(args.input_file, args.output_file, args.disable_zero_padding)\r\n```\r\n\r\nTo reproduce the problem the --disable-zero-padding parameter can be added, and a pdf file of odd number of bytes in length can be used as input to the program, this will then product an output DICOM file containing an odd number of bytes in the (0042,0011) OB Encapsulated Document DICOM tag, which can be checked using the dciodvfy validation tool from the dicom3tools package:\r\n\r\n```bash\r\nwget http://dicom.nema.org/medical/dicom/current/output/pdf/part05.pdf\r\nls -l part05.pdf # should be odd number of bytes, currently 4676213 for this file\r\npython pdf2dcm.py --disable-zero-padding -i part05.pdf -o part05.dcm\r\n\r\n(0x0042,0x0011) OB Encapsulated Document - Error - Bad Value Length - not a multiple of 2 - VL is 0x475a75 should be 0x475a76\r\nError - Dicom dataset read failed\r\n```\r\n\r\n**Environment**\r\n\r\n```bash\r\n$ python -m pydicom.env_info\r\n\r\nmodule | version\r\n------ | -------\r\nplatform | Linux-5.13.0-7614-generic-x86_64-with-glibc2.31\r\nPython | 3.9.5 (default, Jun 4 2021, 12:28:51) [GCC 7.5.0]\r\npydicom | 2.2.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.21.2\r\nPIL | _module not found_\r\npylibjpeg | _module not found_\r\nopenjpeg | _module not found_\r\nlibjpeg | _module not found_\r\n```\r\n\n", "hints_text": "", "created_at": "2021-11-26T06:22:47Z", "version": "2.2", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OB_odd"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_pathlib_path_filename", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_retains_elements", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_deflated_deflates_post_file_meta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_dataset_without_encoding", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_empty_value", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_filename", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of", "pydicom/tests/test_filewriter.py::TestWriteOtherVRs::test_write_of_dataset", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "0fa18d2a2179c92efc22200ed6b3689e66cecf92"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-901", "base_commit": "3746878d8edf1cbda6fbcf35eec69f9ba79301ca", "patch": "diff --git a/pydicom/config.py b/pydicom/config.py\n--- a/pydicom/config.py\n+++ b/pydicom/config.py\n@@ -62,10 +62,7 @@ def DS_decimal(use_Decimal_boolean=True):\n \n # Logging system and debug function to change logging level\n logger = logging.getLogger('pydicom')\n-handler = logging.StreamHandler()\n-formatter = logging.Formatter(\"%(message)s\")\n-handler.setFormatter(formatter)\n-logger.addHandler(handler)\n+logger.addHandler(logging.NullHandler())\n \n \n import pydicom.pixel_data_handlers.numpy_handler as np_handler # noqa\n@@ -110,16 +107,29 @@ def get_pixeldata(ds):\n \"\"\"\n \n \n-def debug(debug_on=True):\n- \"\"\"Turn debugging of DICOM file reading and writing on or off.\n+def debug(debug_on=True, default_handler=True):\n+ \"\"\"Turn on/off debugging of DICOM file reading and writing.\n+\n When debugging is on, file location and details about the\n elements read at that location are logged to the 'pydicom'\n logger using python's logging module.\n \n- :param debug_on: True (default) to turn on debugging,\n- False to turn off.\n+ Parameters\n+ ----------\n+ debug_on : bool, optional\n+ If True (default) then turn on debugging, False to turn off.\n+ default_handler : bool, optional\n+ If True (default) then use ``logging.StreamHandler()`` as the handler\n+ for log messages.\n \"\"\"\n global logger, debugging\n+\n+ if default_handler:\n+ handler = logging.StreamHandler()\n+ formatter = logging.Formatter(\"%(message)s\")\n+ handler.setFormatter(formatter)\n+ logger.addHandler(handler)\n+\n if debug_on:\n logger.setLevel(logging.DEBUG)\n debugging = True\n@@ -129,4 +139,4 @@ def debug(debug_on=True):\n \n \n # force level=WARNING, in case logging default is set differently (issue 103)\n-debug(False)\n+debug(False, False)\n", "test_patch": "diff --git a/pydicom/tests/test_config.py b/pydicom/tests/test_config.py\nnew file mode 100644\n--- /dev/null\n+++ b/pydicom/tests/test_config.py\n@@ -0,0 +1,107 @@\n+# Copyright 2008-2019 pydicom authors. See LICENSE file for details.\n+\"\"\"Unit tests for the pydicom.config module.\"\"\"\n+\n+import logging\n+import sys\n+\n+import pytest\n+\n+from pydicom import dcmread\n+from pydicom.config import debug\n+from pydicom.data import get_testdata_files\n+\n+\n+DS_PATH = get_testdata_files(\"CT_small.dcm\")[0]\n+PYTEST = [int(x) for x in pytest.__version__.split('.')]\n+\n+\[email protected](PYTEST[:2] < [3, 4], reason='no caplog')\n+class TestDebug(object):\n+ \"\"\"Tests for config.debug().\"\"\"\n+ def setup(self):\n+ self.logger = logging.getLogger('pydicom')\n+\n+ def teardown(self):\n+ # Reset to just NullHandler\n+ self.logger.handlers = [self.logger.handlers[0]]\n+\n+ def test_default(self, caplog):\n+ \"\"\"Test that the default logging handler is a NullHandler.\"\"\"\n+ assert 1 == len(self.logger.handlers)\n+ assert isinstance(self.logger.handlers[0], logging.NullHandler)\n+\n+ with caplog.at_level(logging.DEBUG, logger='pydicom'):\n+ ds = dcmread(DS_PATH)\n+\n+ assert \"Call to dcmread()\" not in caplog.text\n+ assert \"Reading File Meta Information preamble...\" in caplog.text\n+ assert \"Reading File Meta Information prefix...\" in caplog.text\n+ assert \"00000080: 'DICM' prefix found\" in caplog.text\n+\n+ def test_debug_on_handler_null(self, caplog):\n+ \"\"\"Test debug(True, False).\"\"\"\n+ debug(True, False)\n+ assert 1 == len(self.logger.handlers)\n+ assert isinstance(self.logger.handlers[0], logging.NullHandler)\n+\n+ with caplog.at_level(logging.DEBUG, logger='pydicom'):\n+ ds = dcmread(DS_PATH)\n+\n+ assert \"Call to dcmread()\" in caplog.text\n+ assert \"Reading File Meta Information preamble...\" in caplog.text\n+ assert \"Reading File Meta Information prefix...\" in caplog.text\n+ assert \"00000080: 'DICM' prefix found\" in caplog.text\n+ msg = (\n+ \"00009848: fc ff fc ff 4f 42 00 00 7e 00 00 00 \"\n+ \"(fffc, fffc) OB Length: 126\"\n+ )\n+ assert msg in caplog.text\n+\n+ def test_debug_off_handler_null(self, caplog):\n+ \"\"\"Test debug(False, False).\"\"\"\n+ debug(False, False)\n+ assert 1 == len(self.logger.handlers)\n+ assert isinstance(self.logger.handlers[0], logging.NullHandler)\n+\n+ with caplog.at_level(logging.DEBUG, logger='pydicom'):\n+ ds = dcmread(DS_PATH)\n+\n+ assert \"Call to dcmread()\" not in caplog.text\n+ assert \"Reading File Meta Information preamble...\" in caplog.text\n+ assert \"Reading File Meta Information prefix...\" in caplog.text\n+ assert \"00000080: 'DICM' prefix found\" in caplog.text\n+\n+ def test_debug_on_handler_stream(self, caplog):\n+ \"\"\"Test debug(True, True).\"\"\"\n+ debug(True, True)\n+ assert 2 == len(self.logger.handlers)\n+ assert isinstance(self.logger.handlers[0], logging.NullHandler)\n+ assert isinstance(self.logger.handlers[1], logging.StreamHandler)\n+\n+ with caplog.at_level(logging.DEBUG, logger='pydicom'):\n+ ds = dcmread(DS_PATH)\n+\n+ assert \"Call to dcmread()\" in caplog.text\n+ assert \"Reading File Meta Information preamble...\" in caplog.text\n+ assert \"Reading File Meta Information prefix...\" in caplog.text\n+ assert \"00000080: 'DICM' prefix found\" in caplog.text\n+ msg = (\n+ \"00009848: fc ff fc ff 4f 42 00 00 7e 00 00 00 \"\n+ \"(fffc, fffc) OB Length: 126\"\n+ )\n+ assert msg in caplog.text\n+\n+ def test_debug_off_handler_stream(self, caplog):\n+ \"\"\"Test debug(False, True).\"\"\"\n+ debug(False, True)\n+ assert 2 == len(self.logger.handlers)\n+ assert isinstance(self.logger.handlers[0], logging.NullHandler)\n+ assert isinstance(self.logger.handlers[1], logging.StreamHandler)\n+\n+ with caplog.at_level(logging.DEBUG, logger='pydicom'):\n+ ds = dcmread(DS_PATH)\n+\n+ assert \"Call to dcmread()\" not in caplog.text\n+ assert \"Reading File Meta Information preamble...\" in caplog.text\n+ assert \"Reading File Meta Information prefix...\" in caplog.text\n+ assert \"00000080: 'DICM' prefix found\" in caplog.text\n", "problem_statement": "pydicom should not define handler, formatter and log level.\nThe `config` module (imported when pydicom is imported) defines a handler and set the log level for the pydicom logger. This should not be the case IMO. It should be the responsibility of the client code of pydicom to configure the logging module to its convenience. Otherwise one end up having multiple logs record as soon as pydicom is imported:\r\n\r\nExample:\r\n```\r\nCould not import pillow\r\n2018-03-25 15:27:29,744 :: DEBUG :: pydicom \r\n Could not import pillow\r\nCould not import jpeg_ls\r\n2018-03-25 15:27:29,745 :: DEBUG :: pydicom \r\n Could not import jpeg_ls\r\nCould not import gdcm\r\n2018-03-25 15:27:29,745 :: DEBUG :: pydicom \r\n Could not import gdcm\r\n``` \r\nOr am I missing something?\n", "hints_text": "In addition, I don't understand what the purpose of the `config.debug` function since the default behavor of the logging module in absence of configuartion seems to already be the one you want.\r\n\r\nFrom https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library:\r\n\r\n> If the using application does not use logging, and library code makes logging calls, then (as described in the previous section) events of severity WARNING and greater will be printed to sys.stderr. This is regarded as the best default behaviour.\r\n\r\nand\r\n\r\n>**It is strongly advised that you do not add any handlers other than NullHandler to your library\u2019s loggers.** This is because the configuration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers \u2018under the hood\u2019, you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements. \r\n\nI think you make good points here. I support changing the logging to comply with python's suggested behavior.\r\n\r\n> In addition, I don't understand what the purpose of the config.debug function\r\n\r\nOne reason is that the core loop in pydicom (data_element_generator in filereader.py) is extremely optimized for speed - it checks the `debugging` flag set by config.debug, to avoid composing messages and doing function calls to logger when not needed.", "created_at": "2019-07-27T00:18:11Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_config.py::TestDebug::test_default", "pydicom/tests/test_config.py::TestDebug::test_debug_on_handler_null", "pydicom/tests/test_config.py::TestDebug::test_debug_off_handler_null", "pydicom/tests/test_config.py::TestDebug::test_debug_on_handler_stream", "pydicom/tests/test_config.py::TestDebug::test_debug_off_handler_stream"], "PASS_TO_PASS": [], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1598", "base_commit": "e9fc645cd8e75d71f7835c0d6e3c0b94b22c2808", "patch": "diff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -393,6 +393,9 @@ def __init__(self, *args: _DatasetType, **kwargs: Any) -> None:\n self.is_little_endian: Optional[bool] = None\n self.is_implicit_VR: Optional[bool] = None\n \n+ # True if the dataset is a sequence item with undefined length\n+ self.is_undefined_length_sequence_item = False\n+\n # the parent data set, if this dataset is a sequence item\n self.parent: \"Optional[weakref.ReferenceType[Dataset]]\" = None\n \ndiff --git a/pydicom/fileset.py b/pydicom/fileset.py\n--- a/pydicom/fileset.py\n+++ b/pydicom/fileset.py\n@@ -1717,6 +1717,7 @@ def load(\n f\"{cast(Path, self.path) / file_id}\"\n )\n continue\n+\n # If the instance's existing directory structure doesn't match\n # the pydicom semantics then stage for movement\n if instance.for_moving:\n@@ -2255,6 +2256,10 @@ def _write_dicomdir(\n offset += 8 # a sequence item's (tag + length)\n # Copy safe - only modifies RecordNode._offset\n offset += node._encode_record(force_implicit)\n+ # If the sequence item has undefined length then it uses a\n+ # sequence item delimiter item\n+ if node._record.is_undefined_length_sequence_item:\n+ offset += 8\n \n # Step 2: Update the records and add to *Directory Record Sequence*\n ds.DirectoryRecordSequence = []\n", "test_patch": "diff --git a/pydicom/tests/test_fileset.py b/pydicom/tests/test_fileset.py\n--- a/pydicom/tests/test_fileset.py\n+++ b/pydicom/tests/test_fileset.py\n@@ -2450,6 +2450,21 @@ def test_add_bad_one_level(self, dummy):\n with pytest.raises(ValueError, match=msg):\n fs.add(ds)\n \n+ def test_write_undefined_length(self, dicomdir_copy):\n+ \"\"\"Test writing with undefined length items\"\"\"\n+ t, ds = dicomdir_copy\n+ elem = ds[\"DirectoryRecordSequence\"]\n+ ds[\"DirectoryRecordSequence\"].is_undefined_length = True\n+ for item in ds.DirectoryRecordSequence:\n+ item.is_undefined_length_sequence_item = True\n+\n+ fs = FileSet(ds)\n+ fs.write(use_existing=True)\n+\n+ ds = dcmread(Path(t.name) / \"DICOMDIR\")\n+ item = ds.DirectoryRecordSequence[-1]\n+ assert item.ReferencedFileID == ['98892003', 'MR700', '4648']\n+\n \n @pytest.mark.filterwarnings(\"ignore:The 'DicomDir'\")\n class TestFileSet_Copy:\n", "problem_statement": "KeyError when saving a FileSet\n**Describe the bug**\r\nSaving a fileset that was loaded using DICOMDIR returns a Key Error.\r\n\r\n**Expected behavior**\r\nFileset is saved without error\r\n\r\n**Steps To Reproduce**\r\nCode:\r\n```python\r\nfrom pydicom.fileset import FileSet\r\n\r\nfpath=\"DICOMDIR\"\r\ndata=FileSet(fpath)\r\n\r\nprint(data)\r\n\r\ndata.write(use_existing=True)\r\n```\r\n\r\n```\r\nTraceback:\r\nKeyError \r\n\r\nTraceback (most recent call last) \r\n\\<ipython-input-183-effc2d1f6bc9\\> in \\<module\\>\r\n 6 print(data)\r\n 7 \r\n----> 8 data.write(use_existing=True)\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/fileset.py in write(self, path, use_existing, force_implicit)\r\n 2146 self._write_dicomdir(f, force_implicit=force_implicit)\r\n 2147 \r\n-> 2148 self.load(p, raise_orphans=True)\r\n 2149 \r\n 2150 return\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/fileset.py in load(self, ds_or_path, include_orphans, raise_orphans)\r\n 1641 ds = ds_or_path\r\n 1642 else:\r\n-> 1643 ds = dcmread(ds_or_path)\r\n 1644 \r\n 1645 sop_class = ds.file_meta.get(\"MediaStorageSOPClassUID\", None)\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py in dcmread(fp, defer_size, stop_before_pixels, force, specific_tags)\r\n 1032 defer_size=size_in_bytes(defer_size),\r\n 1033 force=force,\r\n-> 1034 specific_tags=specific_tags,\r\n 1035 )\r\n 1036 finally:\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py in read_partial(fileobj, stop_when, defer_size, force, specific_tags)\r\n 885 file_meta_dataset,\r\n 886 is_implicit_VR,\r\n--> 887 is_little_endian,\r\n 888 )\r\n 889 else:\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/dicomdir.py in __init__(self, filename_or_obj, dataset, preamble, file_meta, is_implicit_VR, is_little_endian)\r\n 94 \r\n 95 self.patient_records: List[Dataset] = []\r\n---> 96 self.parse_records()\r\n 97 \r\n 98 def parse_records(self) -> None:\r\n\r\n~/anaconda3/lib/python3.7/site-packages/pydicom/dicomdir.py in parse_records(self)\r\n 143 )\r\n 144 if child_offset:\r\n--> 145 child = map_offset_to_record[child_offset]\r\n 146 record.children = get_siblings(child, map_offset_to_record)\r\n 147 \r\n\r\nKeyError: 572\r\n```\r\n\r\n**Your environment**\r\n\r\nmodule | version\r\n------ | -------\r\nplatform | Linux-4.15.0-142-generic-x86_64-with-debian-stretch-sid\r\nPython | 3.7.10 (default, Feb 26 2021, 18:47:35) [GCC 7.3.0]\r\npydicom | 2.2.2\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.19.2\r\nPIL | 8.2.0\r\npylibjpeg | _module not found_\r\nopenjpeg | _module not found_\r\nlibjpeg | _module not found_\r\n\n", "hints_text": "This is going to be difficult to troubleshoot without the original DICOMDIR dataset. Could you create an anonymised version of it using the following and attach it please?\r\n\r\n```python\r\nfrom pydicom import dcmread\r\n\r\nds = dcmread(\"DICOMDIR\")\r\nfor item in ds.DirectoryRecordSequence:\r\n if item.DirectoryRecordType == \"PATIENT\":\r\n item.PatientName = \"X\" * len(item.PatientName)\r\n item.PatientID = \"X\" * len(item.PatientID)\r\n\r\nds.save_as(\"DICOMDIR_anon\", write_like_original=True)\r\n```\r\nIf there are any other identifying elements in the DICOMDIR then just anonymise them using the same method of overwriting with a value of the same length.\nI can't reproduce with:\r\n```python\r\nfrom tempfile import TemporaryDirectory\r\nfrom pathlib import Path\r\nimport shutil\r\n\r\nfrom pydicom.data import get_testdata_file\r\nfrom pydicom.fileset import FileSet\r\n\r\n\r\n# Copy test file set to temporary directory\r\nt = TemporaryDirectory()\r\nsrc = Path(get_testdata_file(\"DICOMDIR\")).parent\r\ndst = Path(t.name)\r\n\r\nshutil.copyfile(src / 'DICOMDIR', dst / 'DICOMDIR')\r\nshutil.copytree(src / \"77654033\", dst / \"77654033\")\r\nshutil.copytree(src / \"98892003\", dst / \"98892003\")\r\nshutil.copytree(src / \"98892001\", dst / \"98892001\")\r\n\r\n# Load\r\nfs = FileSet(dst / \"DICOMDIR\")\r\n# Write without changes\r\nfs.write(use_existing=True)\r\n```\r\nI strongly suspect there's a bad offset being written in your DICOMDIR for some reason, but without seeing the original I can't really do much.", "created_at": "2022-02-11T01:14:16Z", "version": "2.2", "FAIL_TO_PASS": ["pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_undefined_length"], "PASS_TO_PASS": ["pydicom/tests/test_fileset.py::test_is_conformant_file_id", "pydicom/tests/test_fileset.py::test_prefixes", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_numeric", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_numeric_prefix", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_numeric_start", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_alphanumeric", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_alphanumeric_prefix", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_alphanumeric_start", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_long_prefix_raises", "pydicom/tests/test_fileset.py::TestRecordNode::test_root", "pydicom/tests/test_fileset.py::TestRecordNode::test_leaf", "pydicom/tests/test_fileset.py::TestRecordNode::test_add", "pydicom/tests/test_fileset.py::TestRecordNode::test_key", "pydicom/tests/test_fileset.py::TestRecordNode::test_key_raises", "pydicom/tests/test_fileset.py::TestRecordNode::test_bad_record", "pydicom/tests/test_fileset.py::TestRecordNode::test_bad_record_missing_req", "pydicom/tests/test_fileset.py::TestRecordNode::test_encoding", "pydicom/tests/test_fileset.py::TestRecordNode::test_remove_raises", "pydicom/tests/test_fileset.py::TestRecordNode::test_file_id_singleton", "pydicom/tests/test_fileset.py::TestRecordNode::test_file_id_missing", "pydicom/tests/test_fileset.py::TestFileInstance::test_getattr", "pydicom/tests/test_fileset.py::TestFileInstance::test_getattr_order", "pydicom/tests/test_fileset.py::TestFileInstance::test_getitem", "pydicom/tests/test_fileset.py::TestFileInstance::test_getitem_special", "pydicom/tests/test_fileset.py::TestFileInstance::test_getitem_order", "pydicom/tests/test_fileset.py::TestFileInstance::test_contains", "pydicom/tests/test_fileset.py::TestFileInstance::test_is_private", "pydicom/tests/test_fileset.py::TestFileInstance::test_properties", "pydicom/tests/test_fileset.py::TestFileInstance::test_path", "pydicom/tests/test_fileset.py::TestFileInstance::test_path_add", "pydicom/tests/test_fileset.py::TestFileInstance::test_path_move", "pydicom/tests/test_fileset.py::TestFileInstance::test_path_removal", "pydicom/tests/test_fileset.py::TestFileInstance::test_load", "pydicom/tests/test_fileset.py::TestFileInstance::test_load_staged_add", "pydicom/tests/test_fileset.py::TestFileInstance::test_load_staged_move", "pydicom/tests/test_fileset.py::TestFileInstance::test_load_staged_removal", "pydicom/tests/test_fileset.py::TestFileInstance::test_for_moving", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid_add", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid_move", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid_removal", "pydicom/tests/test_fileset.py::TestFileInstance::test_private", "pydicom/tests/test_fileset.py::TestFileSet::test_empty", "pydicom/tests/test_fileset.py::TestFileSet::test_id", "pydicom/tests/test_fileset.py::TestFileSet::test_uid", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_and_charset_written", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_dicomdir", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_charset", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_charset_dicomdir", "pydicom/tests/test_fileset.py::TestFileSet::test_path", "pydicom/tests/test_fileset.py::TestFileSet::test_empty_write", "pydicom/tests/test_fileset.py::TestFileSet::test_add_dataset", "pydicom/tests/test_fileset.py::TestFileSet::test_add_bad_dataset", "pydicom/tests/test_fileset.py::TestFileSet::test_add_path", "pydicom/tests/test_fileset.py::TestFileSet::test_add_add", "pydicom/tests/test_fileset.py::TestFileSet::test_remove", "pydicom/tests/test_fileset.py::TestFileSet::test_remove_iter", "pydicom/tests/test_fileset.py::TestFileSet::test_remove_remove", "pydicom/tests/test_fileset.py::TestFileSet::test_remove_add", "pydicom/tests/test_fileset.py::TestFileSet::test_add_remove", "pydicom/tests/test_fileset.py::TestFileSet::test_file_ids_unique", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_path", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_private", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_too_deep", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_bad_leaf", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_add_add", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_remove_add", "pydicom/tests/test_fileset.py::TestFileSet::test_clear", "pydicom/tests/test_fileset.py::TestFileSet::test_str_empty", "pydicom/tests/test_fileset.py::TestFileSet::test_str", "pydicom/tests/test_fileset.py::TestFileSet::test_str_update_structure", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_write_dicomdir", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_write_new_path", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_sop_class_raises", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_filename_raises", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_filename_type_raises", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_find", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_find_load", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_find_values", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_find_values_load", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_empty_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_raise", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_exclude", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_no_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_private", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_big_endian", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_implicit", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_reordered", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_no_offset", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_no_uid", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_dicomdir_fs_changes", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_dicomdir_use_existing", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_dicomdir_use_existing_raises", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_remove_addition_bad_path", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_missing_removal", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_removal_addition_collision", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_implicit", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_use_existing", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_use_existing_raises", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_instance_missing", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_instance_missing_required_value", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_rt_dose", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_rt_structure_set", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_rt_plan", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_remove_list", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_bad_one_level", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_copy", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_copy_raises", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_copy_implicit", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_additions", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_removals", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_additions_removals", "pydicom/tests/test_fileset.py::test_one_level_record[HANGING", "pydicom/tests/test_fileset.py::test_one_level_record[IMPLANT-1.2.840.10008.5.1.4.43.1]", "pydicom/tests/test_fileset.py::test_one_level_record[IMPLANT", "pydicom/tests/test_fileset.py::test_one_level_record[PALETTE-1.2.840.10008.5.1.4.39.1]", "pydicom/tests/test_fileset.py::test_four_level_record[IMAGE-1.2.840.10008.5.1.4.1.1.2-CT-None]", "pydicom/tests/test_fileset.py::test_four_level_record[RT", "pydicom/tests/test_fileset.py::test_four_level_record[PRESENTATION-1.2.840.10008.5.1.4.1.1.11.1-PR-None]", "pydicom/tests/test_fileset.py::test_four_level_record[WAVEFORM-1.2.840.10008.5.1.4.1.1.9.1.1-ECG-None]", "pydicom/tests/test_fileset.py::test_four_level_record[SR", "pydicom/tests/test_fileset.py::test_four_level_record[KEY", "pydicom/tests/test_fileset.py::test_four_level_record[SPECTROSCOPY-1.2.840.10008.5.1.4.1.1.4.2-MS-None]", "pydicom/tests/test_fileset.py::test_four_level_record[RAW", "pydicom/tests/test_fileset.py::test_four_level_record[REGISTRATION-1.2.840.10008.5.1.4.1.1.66.1-REG-None]", "pydicom/tests/test_fileset.py::test_four_level_record[FIDUCIAL-1.2.840.10008.5.1.4.1.1.66.2-FID-None]", "pydicom/tests/test_fileset.py::test_four_level_record[ENCAP", "pydicom/tests/test_fileset.py::test_four_level_record[VALUE", "pydicom/tests/test_fileset.py::test_four_level_record[STEREOMETRIC-1.2.840.10008.5.1.4.1.1.77.1.5.3-SMR-None]", "pydicom/tests/test_fileset.py::test_four_level_record[PLAN-1.2.840.10008.5.1.4.34.7-PLAN-None]", "pydicom/tests/test_fileset.py::test_four_level_record[MEASUREMENT-1.2.840.10008.5.1.4.1.1.78.1-LEN-None]", "pydicom/tests/test_fileset.py::test_four_level_record[SURFACE-1.2.840.10008.5.1.4.1.1.66.5-LS-None]", "pydicom/tests/test_fileset.py::test_four_level_record[SURFACE", "pydicom/tests/test_fileset.py::test_four_level_record[TRACT-1.2.840.10008.5.1.4.1.1.66.6-NONE-None]", "pydicom/tests/test_fileset.py::test_four_level_record[ASSESSMENT-1.2.840.10008.5.1.4.1.1.90.1-ASMT-None]", "pydicom/tests/test_fileset.py::test_four_level_record[RADIOTHERAPY-1.2.840.10008.5.1.4.1.1.481.13-RTRAD-None]"], "environment_setup_commit": "0fa18d2a2179c92efc22200ed6b3689e66cecf92"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1139", "base_commit": "b9fb05c177b685bf683f7f57b2d57374eb7d882d", "patch": "diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -1,6 +1,5 @@\n # Copyright 2008-2018 pydicom authors. See LICENSE file for details.\n \"\"\"Special classes for DICOM value representations (VR)\"\"\"\n-from copy import deepcopy\n from decimal import Decimal\n import re\n \n@@ -750,6 +749,25 @@ def __ne__(self, other):\n def __str__(self):\n return '='.join(self.components).__str__()\n \n+ def __next__(self):\n+ # Get next character or stop iteration\n+ if self._i < self._rep_len:\n+ c = self._str_rep[self._i]\n+ self._i += 1\n+ return c\n+ else:\n+ raise StopIteration\n+\n+ def __iter__(self):\n+ # Get string rep. and length, initialize index counter\n+ self._str_rep = self.__str__()\n+ self._rep_len = len(self._str_rep)\n+ self._i = 0\n+ return self\n+\n+ def __contains__(self, x):\n+ return x in self.__str__()\n+\n def __repr__(self):\n return '='.join(self.components).__repr__()\n \n", "test_patch": "diff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -427,6 +427,62 @@ def test_hash(self):\n )\n assert hash(pn1) == hash(pn2)\n \n+ def test_next(self):\n+ \"\"\"Test that the next function works on it's own\"\"\"\n+ # Test getting the first character\n+ pn1 = PersonName(\"John^Doe^^Dr\", encodings=default_encoding)\n+ pn1_itr = iter(pn1)\n+ assert next(pn1_itr) == \"J\"\n+\n+ # Test getting multiple characters\n+ pn2 = PersonName(\n+ \"Yamada^Tarou=\u5c71\u7530^\u592a\u90ce=\u3084\u307e\u3060^\u305f\u308d\u3046\", [default_encoding, \"iso2022_jp\"]\n+ )\n+ pn2_itr = iter(pn2)\n+ assert next(pn2_itr) == \"Y\"\n+ assert next(pn2_itr) == \"a\"\n+\n+ # Test getting all characters\n+ pn3 = PersonName(\"SomeName\")\n+ pn3_itr = iter(pn3)\n+ assert next(pn3_itr) == \"S\"\n+ assert next(pn3_itr) == \"o\"\n+ assert next(pn3_itr) == \"m\"\n+ assert next(pn3_itr) == \"e\"\n+ assert next(pn3_itr) == \"N\"\n+ assert next(pn3_itr) == \"a\"\n+ assert next(pn3_itr) == \"m\"\n+ assert next(pn3_itr) == \"e\"\n+\n+ # Attempting to get next characeter should stop the iteration\n+ # I.e. next can only start once\n+ with pytest.raises(StopIteration):\n+ next(pn3_itr)\n+\n+ # Test that next() doesn't work without instantiating an iterator\n+ pn4 = PersonName(\"SomeName\")\n+ with pytest.raises(AttributeError):\n+ next(pn4)\n+\n+ def test_iterator(self):\n+ \"\"\"Test that iterators can be corretly constructed\"\"\"\n+ name_str = \"John^Doe^^Dr\"\n+ pn1 = PersonName(name_str)\n+ \n+ for i, c in enumerate(pn1):\n+ assert name_str[i] == c\n+\n+ # Ensure that multiple iterators can be created on the same variable\n+ for i, c in enumerate(pn1):\n+ assert name_str[i] == c\n+\n+ def test_contains(self):\n+ \"\"\"Test that characters can be check if they are within the name\"\"\"\n+ pn1 = PersonName(\"John^Doe\")\n+ assert (\"J\" in pn1) == True\n+ assert (\"o\" in pn1) == True\n+ assert (\"x\" in pn1) == False\n+\n \n class TestDateTime:\n \"\"\"Unit tests for DA, DT, TM conversion to datetime objects\"\"\"\n", "problem_statement": "Make PersonName3 iterable\n```python\r\nfrom pydicom import Dataset\r\n\r\nds = Dataset()\r\nds.PatientName = 'SomeName'\r\n\r\n'S' in ds.PatientName\r\n```\r\n```\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\nTypeError: argument of type 'PersonName3' is not iterable\r\n```\r\n\r\nI'm not really sure if this is intentional or if PN elements should support `str` methods. And yes I know I can `str(ds.PatientName)` but it's a bit silly, especially when I keep having to write exceptions to my element iterators just for PN elements.\n", "hints_text": "I think it is reasonable to support at least some `str` methods (definitely `__contains__` for the example above), but there are many that don't make a lot of sense in this context though - e.g. `join`, `ljust`, `maketrans`, `splitlines` just to name a few, but I suppose each would either never be actually used or would have no effect.\r\n\r\nI have a vague memory that one or more of the `PersonName` classes was at one time subclassed from `str`, or at least that it was discussed... does anyone remember? Maybe it would be easier now with only Python 3 supported.\n`PersonName` was derived from `str` or `unicode` in Python 2, but that caused a number of problems, which is why you switched to `PersonName3` in Python 3, I think. I agree though that it makes sense to implement `str` methods, either by implementing some of them, or generically by adding `__getattr__` that converts it to `str` and applies the attribute to that string. ", "created_at": "2020-06-26T11:47:17Z", "version": "2.0", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains"], "PASS_TO_PASS": ["pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time"], "environment_setup_commit": "9d69811e539774f296c2f289839147e741251716"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-793", "base_commit": "897fe092ae3ef282a21c894b47134233bdd5cdd0", "patch": "diff --git a/pydicom/values.py b/pydicom/values.py\n--- a/pydicom/values.py\n+++ b/pydicom/values.py\n@@ -310,7 +310,12 @@ def convert_UR_string(byte_string, is_little_endian, struct_format=None):\n def convert_value(VR, raw_data_element, encodings=None):\n \"\"\"Return the converted value (from raw bytes) for the given VR\"\"\"\n if VR not in converters:\n- message = \"Unknown Value Representation '{0}'\".format(VR)\n+ # `VR` characters are in the ascii alphabet ranges 65 - 90, 97 - 122\n+ char_range = list(range(65, 91)) + list(range(97, 123))\n+ # If the VR characters are outside that range then print hex values\n+ if ord(VR[0]) not in char_range or ord(VR[1]) not in char_range:\n+ VR = ' '.join(['0x{:02x}'.format(ord(ch)) for ch in VR])\n+ message = \"Unknown Value Representation '{}'\".format(VR)\n raise NotImplementedError(message)\n \n # Look up the function to convert that VR\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -15,7 +15,7 @@\n import pydicom.config\n from pydicom.dataset import Dataset, FileDataset\n from pydicom.data import get_testdata_files\n-from pydicom.filereader import dcmread\n+from pydicom.filereader import dcmread, read_dataset\n from pydicom.dataelem import DataElement, DataElement_from_raw\n from pydicom.errors import InvalidDicomError\n from pydicom.filebase import DicomBytesIO\n@@ -689,6 +689,67 @@ def test_dcmread_does_not_raise(self):\n self.fail('Unexpected EOFError raised')\n \n \n+class TestUnknownVR(object):\n+ @pytest.mark.parametrize(\n+ 'vr_bytes, str_output',\n+ [\n+ # Test limits of char values\n+ (b'\\x00\\x41', '0x00 0x41'), # 000/A\n+ (b'\\x40\\x41', '0x40 0x41'), # 064/A\n+ (b'\\x5B\\x41', '0x5b 0x41'), # 091/A\n+ (b'\\x60\\x41', '0x60 0x41'), # 096/A\n+ (b'\\x7B\\x41', '0x7b 0x41'), # 123/A\n+ (b'\\xFF\\x41', '0xff 0x41'), # 255/A\n+ # Test good/bad\n+ (b'\\x41\\x00', '0x41 0x00'), # A/-\n+ (b'\\x5A\\x00', '0x5a 0x00'), # Z/-\n+ # Test not quite good/bad\n+ (b'\\x61\\x00', '0x61 0x00'), # a/-\n+ (b'\\x7A\\x00', '0x7a 0x00'), # z/-\n+ # Test bad/good\n+ (b'\\x00\\x41', '0x00 0x41'), # -/A\n+ (b'\\x00\\x5A', '0x00 0x5a'), # -/Z\n+ # Test bad/not quite good\n+ (b'\\x00\\x61', '0x00 0x61'), # -/a\n+ (b'\\x00\\x7A', '0x00 0x7a'), # -/z\n+ # Test good/good\n+ (b'\\x41\\x41', 'AA'), # A/A\n+ (b'\\x41\\x5A', 'AZ'), # A/Z\n+ (b'\\x5A\\x41', 'ZA'), # Z/A\n+ (b'\\x5A\\x5A', 'ZZ'), # Z/Z\n+ # Test not quite good\n+ (b'\\x41\\x61', 'Aa'), # A/a\n+ (b'\\x41\\x7A', 'Az'), # A/z\n+ (b'\\x61\\x41', 'aA'), # a/A\n+ (b'\\x61\\x5A', 'aZ'), # a/Z\n+ (b'\\x61\\x61', 'aa'), # a/a\n+ (b'\\x61\\x7A', 'az'), # a/z\n+ (b'\\x5A\\x61', 'Za'), # Z/a\n+ (b'\\x5A\\x7A', 'Zz'), # Z/z\n+ (b'\\x7A\\x41', 'zA'), # z/A\n+ (b'\\x7A\\x5A', 'zZ'), # z/Z\n+ (b'\\x7A\\x61', 'za'), # z/a\n+ (b'\\x7A\\x7A', 'zz'), # z/z\n+ ]\n+ )\n+ def test_fail_decode_msg(self, vr_bytes, str_output):\n+ \"\"\"Regression test for #791.\"\"\"\n+ ds = read_dataset(\n+ BytesIO(\n+ b'\\x08\\x00\\x01\\x00' +\n+ vr_bytes +\n+ b'\\x00\\x00\\x00\\x08\\x00\\x49'\n+ ),\n+ False, True\n+ )\n+ msg = (\n+ r\"Unknown Value Representation '{}' in tag \\(0008, 0001\\)\"\n+ .format(str_output)\n+ )\n+ with pytest.raises(NotImplementedError, match=msg):\n+ print(ds)\n+\n+\n class ReadDataElementTests(unittest.TestCase):\n def setUp(self):\n ds = Dataset()\n", "problem_statement": "Print byte values for unknown VR during read\n#### Description\r\nIf the dataset read fails due to an unknown VR then the exception message prints the VR bytes in a format that isn't useful for debugging.\r\n\r\n#### Steps/Code to Reproduce\r\n```python\r\nfrom io import BytesIO\r\nfrom pydicom.filereader import read_dataset\r\nds = read_dataset(BytesIO(b'\\x08\\x00\\x01\\x00\\x04\\x00\\x00\\x00\\x00\\x08\\x00\\x49'), False, True)\r\nprint(ds)\r\n```\r\n\r\n#### Expected Results\r\n```\r\nNotImplementedError: Unknown Value Representation: '32 31' in tag (0000, 0002)\r\n```\r\n#### Actual Results\r\n```\r\nFile \"<stdin>\", line 1, in <module>\r\n File \".../pydicom/pydicom/dataset.py\", line 1284, in __str__\r\n return self._pretty_str()\r\n File \".../pydicom/pydicom/dataset.py\", line 1022, in _pretty_str\r\n for data_element in self:\r\n File \".../pydicom/pydicom/dataset.py\", line 751, in __iter__\r\n yield self[tag]\r\n File \".../pydicom/pydicom/dataset.py\", line 637, in __getitem__\r\n self[tag] = DataElement_from_raw(data_elem, character_set)\r\n File \".../pydicom/pydicom/dataelem.py\", line 447, in DataElement_from_raw\r\n raise NotImplementedError(\"{0:s} in tag {1!r}\".format(str(e), raw.tag))\r\nNotImplementedError: Unknown Value Representation '\u0004' in tag (0008, 0001)\r\n```\r\n[Or see here for another example](https://user-images.githubusercontent.com/28559755/51027486-4abf4100-1591-11e9-8f44-a739b00ca300.PNG)\r\n\r\n\n", "hints_text": "", "created_at": "2019-01-20T02:31:42Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::ReaderTests::testCT", "pydicom/tests/test_filereader.py::ReaderTests::testCTPixelData", "pydicom/tests/test_filereader.py::ReaderTests::testDeflate", "pydicom/tests/test_filereader.py::ReaderTests::testDir", "pydicom/tests/test_filereader.py::ReaderTests::testEmptyNumbersTag", "pydicom/tests/test_filereader.py::ReaderTests::testExplicitVRBigEndianNoMeta", "pydicom/tests/test_filereader.py::ReaderTests::testExplicitVRLittleEndianNoMeta", "pydicom/tests/test_filereader.py::ReaderTests::testMR", "pydicom/tests/test_filereader.py::ReaderTests::testNestedPrivateSQ", "pydicom/tests/test_filereader.py::ReaderTests::testNoForce", "pydicom/tests/test_filereader.py::ReaderTests::testNoMetaGroupLength", "pydicom/tests/test_filereader.py::ReaderTests::testNoPixelsRead", "pydicom/tests/test_filereader.py::ReaderTests::testNoTransferSyntaxInMeta", "pydicom/tests/test_filereader.py::ReaderTests::testPlanarConfig", "pydicom/tests/test_filereader.py::ReaderTests::testPrivateSQ", "pydicom/tests/test_filereader.py::ReaderTests::testRTDose", "pydicom/tests/test_filereader.py::ReaderTests::testRTPlan", "pydicom/tests/test_filereader.py::ReaderTests::testRTstruct", "pydicom/tests/test_filereader.py::ReaderTests::testSpecificTags", "pydicom/tests/test_filereader.py::ReaderTests::testSpecificTagsWithUnknownLengthSQ", "pydicom/tests/test_filereader.py::ReaderTests::testSpecificTagsWithUnknownLengthTag", "pydicom/tests/test_filereader.py::ReaderTests::testUTF8FileName", "pydicom/tests/test_filereader.py::ReaderTests::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::ReaderTests::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::ReaderTests::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::ReaderTests::test_group_length_wrong", "pydicom/tests/test_filereader.py::ReaderTests::test_long_specific_char_set", "pydicom/tests/test_filereader.py::ReaderTests::test_meta_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::ReaderTests::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_AE", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::DeferredReadTests::testFileExists", "pydicom/tests/test_filereader.py::DeferredReadTests::testTimeCheck", "pydicom/tests/test_filereader.py::DeferredReadTests::testValuesIdentical", "pydicom/tests/test_filereader.py::DeferredReadTests::testZippedDeferred", "pydicom/tests/test_filereader.py::ReadTruncatedFileTests::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::FileLikeTests::testReadFileGivenFileLikeObject", "pydicom/tests/test_filereader.py::FileLikeTests::testReadFileGivenFileObject", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1192", "base_commit": "1f099ae0f75f0e2ed402a21702e584aac54a30ef", "patch": "diff --git a/pydicom/charset.py b/pydicom/charset.py\n--- a/pydicom/charset.py\n+++ b/pydicom/charset.py\n@@ -634,13 +634,16 @@ def convert_encodings(encodings):\n ``True``.\n \"\"\"\n \n- # If a list if passed, we don't want to modify the list in place so copy it\n- encodings = encodings[:]\n+ encodings = encodings or ['']\n \n if isinstance(encodings, str):\n encodings = [encodings]\n- elif not encodings[0]:\n- encodings[0] = 'ISO_IR 6'\n+ else:\n+ # If a list if passed, we don't want to modify the list\n+ # in place so copy it\n+ encodings = encodings[:]\n+ if not encodings[0]:\n+ encodings[0] = 'ISO_IR 6'\n \n py_encodings = []\n for encoding in encodings:\n", "test_patch": "diff --git a/pydicom/tests/test_charset.py b/pydicom/tests/test_charset.py\n--- a/pydicom/tests/test_charset.py\n+++ b/pydicom/tests/test_charset.py\n@@ -140,6 +140,15 @@ def test_bad_charset(self):\n pydicom.charset.decode_element(elem, [])\n assert 'iso8859' in elem.value.encodings\n \n+ def test_empty_charset(self):\n+ \"\"\"Empty charset defaults to ISO IR 6\"\"\"\n+ elem = DataElement(0x00100010, 'PN', 'CITIZEN')\n+ pydicom.charset.decode_element(elem, [''])\n+ assert ('iso8859',) == elem.value.encodings\n+ elem = DataElement(0x00100010, 'PN', 'CITIZEN')\n+ pydicom.charset.decode_element(elem, None)\n+ assert ('iso8859',) == elem.value.encodings\n+\n def test_bad_encoded_single_encoding(self, allow_invalid_values):\n \"\"\"Test handling bad encoding for single encoding\"\"\"\n elem = DataElement(0x00100010, 'PN',\n@@ -189,6 +198,15 @@ def test_convert_python_encodings(self):\n encodings = ['iso_ir_126', 'iso_ir_144']\n assert encodings == pydicom.charset.convert_encodings(encodings)\n \n+ def test_convert_empty_encoding(self):\n+ \"\"\"Test that empty encodings are handled as default encoding\"\"\"\n+ encodings = ''\n+ assert ['iso8859'] == pydicom.charset.convert_encodings(encodings)\n+ encodings = ['']\n+ assert ['iso8859'] == pydicom.charset.convert_encodings(encodings)\n+ encodings = None\n+ assert ['iso8859'] == pydicom.charset.convert_encodings(encodings)\n+\n def test_bad_decoded_multi_byte_encoding(self, allow_invalid_values):\n \"\"\"Test handling bad encoding for single encoding\"\"\"\n elem = DataElement(0x00100010, 'PN',\n", "problem_statement": "\"TypeError: 'NoneType' object is not subscriptable\" when reading dcm file with empty string as Chartset and \"use_none_as_empty_text_VR_value=True\"\n**Describe the bug**\r\nOnce thing I noticed is that `convert_encodings` in `charset.py` expects a list of encodings (according to the docstrings) from tag `0008,0005` but it can be just a value. \r\n\r\nThe problem is when reading Dicom files in production environments I noticed that some devices that are capturing the DICOMs are not very DICOM Compliant and is sending empty string , which it should be allowed as `0008,0005` is a 1C type, which means that if present it should have a valid value. \r\n\r\nI enabled `use_none_as_empty_text_VR_value` to make sure other tags whose value should be float or int have None instead of empty string, but if `0008,0005` value is empty string is switched to None and `convert_encodings` fails with `TypeError: 'NoneType' object is not subscriptable`\r\n\r\n**Expected behavior**\r\nThe expected behavior should be that if empty string or not present it should default to:\r\n```\r\n# default encoding if no encoding defined - corresponds to ISO IR 6 / ASCII\r\ndefault_encoding = \"iso8859\"\r\n```\r\n\r\n**Steps To Reproduce**\r\n\r\nout.dcm file if provided for testing with mock data but `Specific Character Set` set to empty string\r\n\r\nIf setting the `(0008, 0005) Specific Character Set` to empty string and setting `pydicom.config.use_none_as_empty_text_VR_value = True`\r\n\r\n```\r\n>>> import pydicom\r\n>>> pydicom.config.datetime_conversion = True\r\n>>> pydicom.config.allow_DS_float = True\r\n>>> pydicom.config.use_none_as_empty_text_VR_value = True\r\n>>> dataset = pydicom.dcmread(\"test.dcm\")\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/Users/bernardo/.virtualenvs/backend-api/lib/python3.7/site-packages/pydicom/filereader.py\", line 871, in dcmread\r\n force=force, specific_tags=specific_tags)\r\n File \"/Users/bernardo/.virtualenvs/backend-api/lib/python3.7/site-packages/pydicom/filereader.py\", line 744, in read_partial\r\n specific_tags=specific_tags)\r\n File \"/Users/bernardo/.virtualenvs/backend-api/lib/python3.7/site-packages/pydicom/filereader.py\", line 383, in read_dataset\r\n encoding = convert_encodings(char_set)\r\n File \"/Users/bernardo/.virtualenvs/backend-api/lib/python3.7/site-packages/pydicom/charset.py\", line 638, in convert_encodings\r\n encodings = encodings[:]\r\nTypeError: 'NoneType' object is not subscriptable\r\n>>> pydicom.config.use_none_as_empty_text_VR_value = False\r\n>>> dataset = pydicom.dcmread(\"test.dcm\")\r\n```\r\n`(0008, 0005) Specific Character Set CS: ''`\r\n\r\n**Your environment**\r\n\r\n```bash\r\npython -m pydicom.env_info\r\nmodule | version\r\n------ | -------\r\nplatform | Darwin-19.6.0-x86_64-i386-64bit\r\nPython | 3.7.6 (default, Dec 30 2019, 19:38:26) [Clang 11.0.0 (clang-1100.0.33.16)]\r\npydicom | 2.0.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | _module not found_\r\nPIL | 7.0.0\r\n```\r\n\r\n\r\n[out.dcm.zip](https://github.com/pydicom/pydicom/files/5248618/out.dcm.zip)\r\n\n", "hints_text": "As you wrote, an empty string is not allowed as Specific Character Set, but I agree that this is a case that we shall handle gracefully (e.g. just handle as if the tag were absent). I will have a look.", "created_at": "2020-09-19T12:22:29Z", "version": "2.0", "FAIL_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_convert_empty_encoding"], "PASS_TO_PASS": ["pydicom/tests/test_charset.py::TestCharset::test_encodings", "pydicom/tests/test_charset.py::TestCharset::test_nested_character_sets", "pydicom/tests/test_charset.py::TestCharset::test_inherited_character_set_in_sequence", "pydicom/tests/test_charset.py::TestCharset::test_standard_file", "pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set", "pydicom/tests/test_charset.py::TestCharset::test_invalid_character_set_enforce_valid", "pydicom/tests/test_charset.py::TestCharset::test_decoding_with_specific_tags", "pydicom/tests/test_charset.py::TestCharset::test_bad_charset", "pydicom/tests/test_charset.py::TestCharset::test_empty_charset", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_encoded_single_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_code_extensions_not_allowed", "pydicom/tests/test_charset.py::TestCharset::test_convert_encodings_warnings", "pydicom/tests/test_charset.py::TestCharset::test_convert_python_encodings", "pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_decoded_multi_byte_encoding_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence", "pydicom/tests/test_charset.py::TestCharset::test_unknown_escape_sequence_enforce_standard", "pydicom/tests/test_charset.py::TestCharset::test_patched_charset", "pydicom/tests/test_charset.py::TestCharset::test_patched_code_extension_charset", "pydicom/tests/test_charset.py::TestCharset::test_multi_charset_default_value", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_personname", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_multi_charset_text", "pydicom/tests/test_charset.py::TestCharset::test_single_byte_code_extensions[ISO", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrArab-\\u0642\\u0628\\u0627\\u0646\\u064a^\\u0644\\u0646\\u0632\\u0627\\u0631]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFren-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrFrenMulti-Buc^J\\xe9r\\xf4me]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGerm-\\xc4neas^R\\xfcdiger]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrGreek-\\u0394\\u03b9\\u03bf\\u03bd\\u03c5\\u03c3\\u03b9\\u03bf\\u03c2]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH31-Yamada^Tarou=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrH32-\\uff94\\uff8f\\uff80\\uff9e^\\uff80\\uff9b\\uff73=\\u5c71\\u7530^\\u592a\\u90ce=\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrHbrw-\\u05e9\\u05e8\\u05d5\\u05df^\\u05d3\\u05d1\\u05d5\\u05e8\\u05d4]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrI2-Hong^Gildong=\\u6d2a^\\u5409\\u6d1e=\\ud64d^\\uae38\\ub3d9]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMulti-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrJapMultiExplicitIR6-\\u3084\\u307e\\u3060^\\u305f\\u308d\\u3046]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrKoreanMulti-\\uae40\\ud76c\\uc911]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrRuss-\\u041b\\u044e\\u043ace\\u043c\\u0431yp\\u0433]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX1-Wang^XiaoDong=\\u738b^\\u5c0f\\u6771]", "pydicom/tests/test_charset.py::TestCharset::test_charset_patient_names[chrX2-Wang^XiaoDong=\\u738b^\\u5c0f\\u4e1c]", "pydicom/tests/test_charset.py::TestCharset::test_changed_character_set", "pydicom/tests/test_charset.py::TestCharset::test_invalid_second_encoding", "pydicom/tests/test_charset.py::TestCharset::test_invalid_second_encoding_strict", "pydicom/tests/test_charset.py::TestCharset::test_japanese_multi_byte_personname", "pydicom/tests/test_charset.py::TestCharset::test_japanese_multi_byte_encoding", "pydicom/tests/test_charset.py::TestCharset::test_bad_japanese_encoding", "pydicom/tests/test_charset.py::TestCharset::test_deprecated_decode"], "environment_setup_commit": "9d69811e539774f296c2f289839147e741251716"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1236", "base_commit": "c2c6145d679adc97924d6c8a761a50b8e2819e3f", "patch": "diff --git a/pydicom/pixel_data_handlers/__init__.py b/pydicom/pixel_data_handlers/__init__.py\n--- a/pydicom/pixel_data_handlers/__init__.py\n+++ b/pydicom/pixel_data_handlers/__init__.py\n@@ -1,7 +1,7 @@\n \n from pydicom.pixel_data_handlers.util import (\n apply_color_lut, apply_modality_lut, apply_voi_lut, convert_color_space,\n+ apply_voi, apply_windowing\n )\n \n apply_rescale = apply_modality_lut\n-apply_windowing = apply_voi_lut\ndiff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py\n--- a/pydicom/pixel_data_handlers/util.py\n+++ b/pydicom/pixel_data_handlers/util.py\n@@ -3,7 +3,7 @@\n \n from struct import unpack\n from sys import byteorder\n-from typing import Dict\n+from typing import Dict, Optional, Union, List, Tuple, TYPE_CHECKING, cast\n import warnings\n \n try:\n@@ -15,8 +15,15 @@\n from pydicom.data import get_palette_files\n from pydicom.uid import UID\n \n+if TYPE_CHECKING:\n+ from pydicom.dataset import Dataset\n \n-def apply_color_lut(arr, ds=None, palette=None):\n+\n+def apply_color_lut(\n+ arr: \"np.ndarray\",\n+ ds: Optional[\"Dataset\"] = None,\n+ palette: Optional[Union[str, UID]] = None\n+) -> \"np.ndarray\":\n \"\"\"Apply a color palette lookup table to `arr`.\n \n .. versionadded:: 1.4\n@@ -187,7 +194,7 @@ def apply_color_lut(arr, ds=None, palette=None):\n return out\n \n \n-def apply_modality_lut(arr, ds):\n+def apply_modality_lut(arr: \"np.ndarray\", ds: \"Dataset\") -> \"np.ndarray\":\n \"\"\"Apply a modality lookup table or rescale operation to `arr`.\n \n .. versionadded:: 1.4\n@@ -261,11 +268,20 @@ def apply_modality_lut(arr, ds):\n return arr\n \n \n-def apply_voi_lut(arr, ds, index=0):\n+def apply_voi_lut(\n+ arr: \"np.ndarray\",\n+ ds: \"Dataset\",\n+ index: int = 0,\n+ prefer_lut: bool = True\n+) -> \"np.ndarray\":\n \"\"\"Apply a VOI lookup table or windowing operation to `arr`.\n \n .. versionadded:: 1.4\n \n+ .. versionchanged:: 2.1\n+\n+ Added the `prefer_lut` keyword parameter\n+\n Parameters\n ----------\n arr : numpy.ndarray\n@@ -280,8 +296,12 @@ def apply_voi_lut(arr, ds, index=0):\n ``np.float64``. If neither are present then `arr` will be returned\n unchanged.\n index : int, optional\n- Where the VOI LUT Module contains multiple possible views, this is\n+ When the VOI LUT Module contains multiple alternative views, this is\n the index of the view to return (default ``0``).\n+ prefer_lut : bool\n+ When the VOI LUT Module contains both *Window Width*/*Window Center*\n+ and *VOI LUT Sequence*, if ``True`` (default) then apply the VOI LUT,\n+ otherwise apply the windowing operation.\n \n Returns\n -------\n@@ -297,6 +317,8 @@ def apply_voi_lut(arr, ds, index=0):\n See Also\n --------\n :func:`~pydicom.pixel_data_handlers.util.apply_modality_lut`\n+ :func:`~pydicom.pixel_data_handlers.util.apply_voi`\n+ :func:`~pydicom.pixel_data_handlers.util.apply_windowing`\n \n References\n ----------\n@@ -307,134 +329,253 @@ def apply_voi_lut(arr, ds, index=0):\n * DICOM Standard, Part 4, :dcm:`Annex N.2.1.1\n <part04/sect_N.2.html#sect_N.2.1.1>`\n \"\"\"\n+ valid_voi = False\n if 'VOILUTSequence' in ds:\n- if not np.issubdtype(arr.dtype, np.integer):\n- warnings.warn(\n- \"Applying a VOI LUT on a float input array may give \"\n- \"incorrect results\"\n- )\n+ valid_voi = None not in [\n+ ds.VOILUTSequence[0].get('LUTDescriptor', None),\n+ ds.VOILUTSequence[0].get('LUTData', None)\n+ ]\n+ valid_windowing = None not in [\n+ ds.get('WindowCenter', None),\n+ ds.get('WindowWidth', None)\n+ ]\n \n- # VOI LUT Sequence contains one or more items\n- item = ds.VOILUTSequence[index]\n- nr_entries = item.LUTDescriptor[0] or 2**16\n- first_map = item.LUTDescriptor[1]\n+ if valid_voi and valid_windowing:\n+ if prefer_lut:\n+ return apply_voi(arr, ds, index)\n \n- # PS3.3 C.8.11.3.1.5: may be 8, 10-16\n- nominal_depth = item.LUTDescriptor[2]\n- if nominal_depth in list(range(10, 17)):\n- dtype = 'uint16'\n- elif nominal_depth == 8:\n- dtype = 'uint8'\n- else:\n- raise NotImplementedError(\n- \"'{}' bits per LUT entry is not supported\"\n- .format(nominal_depth)\n- )\n+ return apply_windowing(arr, ds, index)\n \n- # Ambiguous VR, US or OW\n- if item['LUTData'].VR == 'OW':\n- endianness = '<' if ds.is_little_endian else '>'\n- unpack_fmt = '{}{}H'.format(endianness, nr_entries)\n- lut_data = unpack(unpack_fmt, item.LUTData)\n- else:\n- lut_data = item.LUTData\n- lut_data = np.asarray(lut_data, dtype=dtype)\n+ if valid_voi:\n+ return apply_voi(arr, ds, index)\n \n- # IVs < `first_map` get set to first LUT entry (i.e. index 0)\n- clipped_iv = np.zeros(arr.shape, dtype=dtype)\n- # IVs >= `first_map` are mapped by the VOI LUT\n- # `first_map` may be negative, positive or 0\n- mapped_pixels = arr >= first_map\n- clipped_iv[mapped_pixels] = arr[mapped_pixels] - first_map\n- # IVs > number of entries get set to last entry\n- np.clip(clipped_iv, 0, nr_entries - 1, out=clipped_iv)\n+ if valid_windowing:\n+ return apply_windowing(arr, ds, index)\n \n- return lut_data[clipped_iv]\n- elif 'WindowCenter' in ds and 'WindowWidth' in ds:\n- if ds.PhotometricInterpretation not in ['MONOCHROME1', 'MONOCHROME2']:\n- raise ValueError(\n- \"When performing a windowing operation only 'MONOCHROME1' and \"\n- \"'MONOCHROME2' are allowed for (0028,0004) Photometric \"\n- \"Interpretation\"\n- )\n+ return arr\n \n- # May be LINEAR (default), LINEAR_EXACT, SIGMOID or not present, VM 1\n- voi_func = getattr(ds, 'VOILUTFunction', 'LINEAR').upper()\n- # VR DS, VM 1-n\n- elem = ds['WindowCenter']\n- center = elem.value[index] if elem.VM > 1 else elem.value\n- elem = ds['WindowWidth']\n- width = elem.value[index] if elem.VM > 1 else elem.value\n-\n- # The output range depends on whether or not a modality LUT or rescale\n- # operation has been applied\n- if 'ModalityLUTSequence' in ds:\n- # Unsigned - see PS3.3 C.11.1.1.1\n- y_min = 0\n- bit_depth = ds.ModalityLUTSequence[0].LUTDescriptor[2]\n- y_max = 2**bit_depth - 1\n- elif ds.PixelRepresentation == 0:\n- # Unsigned\n- y_min = 0\n- y_max = 2**ds.BitsStored - 1\n- else:\n- # Signed\n- y_min = -2**(ds.BitsStored - 1)\n- y_max = 2**(ds.BitsStored - 1) - 1\n-\n- if 'RescaleSlope' in ds and 'RescaleIntercept' in ds:\n- # Otherwise its the actual data range\n- y_min = y_min * ds.RescaleSlope + ds.RescaleIntercept\n- y_max = y_max * ds.RescaleSlope + ds.RescaleIntercept\n-\n- y_range = y_max - y_min\n- arr = arr.astype('float64')\n-\n- if voi_func in ['LINEAR', 'LINEAR_EXACT']:\n- # PS3.3 C.11.2.1.2.1 and C.11.2.1.3.2\n- if voi_func == 'LINEAR':\n- if width < 1:\n- raise ValueError(\n- \"The (0028,1051) Window Width must be greater than or \"\n- \"equal to 1 for a 'LINEAR' windowing operation\"\n- )\n- center -= 0.5\n- width -= 1\n- elif width <= 0:\n- raise ValueError(\n- \"The (0028,1051) Window Width must be greater than 0 \"\n- \"for a 'LINEAR_EXACT' windowing operation\"\n- )\n \n- below = arr <= (center - width / 2)\n- above = arr > (center + width / 2)\n- between = np.logical_and(~below, ~above)\n+def apply_voi(\n+ arr: \"np.ndarray\", ds: \"Dataset\", index: int = 0\n+) -> \"np.ndarray\":\n+ \"\"\"Apply a VOI lookup table to `arr`.\n \n- arr[below] = y_min\n- arr[above] = y_max\n- if between.any():\n- arr[between] = (\n- ((arr[between] - center) / width + 0.5) * y_range + y_min\n- )\n- elif voi_func == 'SIGMOID':\n- # PS3.3 C.11.2.1.3.1\n- if width <= 0:\n+ .. versionadded:: 2.1\n+\n+ Parameters\n+ ----------\n+ arr : numpy.ndarray\n+ The :class:`~numpy.ndarray` to apply the VOI LUT to.\n+ ds : dataset.Dataset\n+ A dataset containing a :dcm:`VOI LUT Module<part03/sect_C.11.2.html>`.\n+ If (0028,3010) *VOI LUT Sequence* is present then returns an array\n+ of ``np.uint8`` or ``np.uint16``, depending on the 3rd value of\n+ (0028,3002) *LUT Descriptor*, otherwise `arr` will be returned\n+ unchanged.\n+ index : int, optional\n+ When the VOI LUT Module contains multiple alternative views, this is\n+ the index of the view to return (default ``0``).\n+\n+ Returns\n+ -------\n+ numpy.ndarray\n+ An array with applied VOI LUT.\n+\n+ See Also\n+ --------\n+ :func:`~pydicom.pixel_data_handlers.util.apply_modality_lut`\n+ :func:`~pydicom.pixel_data_handlers.util.apply_windowing`\n+\n+ References\n+ ----------\n+ * DICOM Standard, Part 3, :dcm:`Annex C.11.2\n+ <part03/sect_C.11.html#sect_C.11.2>`\n+ * DICOM Standard, Part 3, :dcm:`Annex C.8.11.3.1.5\n+ <part03/sect_C.8.11.3.html#sect_C.8.11.3.1.5>`\n+ * DICOM Standard, Part 4, :dcm:`Annex N.2.1.1\n+ <part04/sect_N.2.html#sect_N.2.1.1>`\n+ \"\"\"\n+ if \"VOILUTSequence\" not in ds:\n+ return arr\n+\n+ if not np.issubdtype(arr.dtype, np.integer):\n+ warnings.warn(\n+ \"Applying a VOI LUT on a float input array may give \"\n+ \"incorrect results\"\n+ )\n+\n+ # VOI LUT Sequence contains one or more items\n+ item = ds.VOILUTSequence[index]\n+ nr_entries = item.LUTDescriptor[0] or 2**16\n+ first_map = item.LUTDescriptor[1]\n+\n+ # PS3.3 C.8.11.3.1.5: may be 8, 10-16\n+ nominal_depth = item.LUTDescriptor[2]\n+ if nominal_depth in list(range(10, 17)):\n+ dtype = 'uint16'\n+ elif nominal_depth == 8:\n+ dtype = 'uint8'\n+ else:\n+ raise NotImplementedError(\n+ f\"'{nominal_depth}' bits per LUT entry is not supported\"\n+ )\n+\n+ # Ambiguous VR, US or OW\n+ if item['LUTData'].VR == 'OW':\n+ endianness = '<' if ds.is_little_endian else '>'\n+ unpack_fmt = f'{endianness}{nr_entries}H'\n+ lut_data = unpack(unpack_fmt, item.LUTData)\n+ else:\n+ lut_data = item.LUTData\n+ lut_data = np.asarray(lut_data, dtype=dtype)\n+\n+ # IVs < `first_map` get set to first LUT entry (i.e. index 0)\n+ clipped_iv = np.zeros(arr.shape, dtype=dtype)\n+ # IVs >= `first_map` are mapped by the VOI LUT\n+ # `first_map` may be negative, positive or 0\n+ mapped_pixels = arr >= first_map\n+ clipped_iv[mapped_pixels] = arr[mapped_pixels] - first_map\n+ # IVs > number of entries get set to last entry\n+ np.clip(clipped_iv, 0, nr_entries - 1, out=clipped_iv)\n+\n+ return lut_data[clipped_iv]\n+\n+\n+def apply_windowing(\n+ arr: \"np.ndarray\", ds: \"Dataset\", index: int = 0\n+) -> \"np.ndarray\":\n+ \"\"\"Apply a windowing operation to `arr`.\n+\n+ .. versionadded:: 2.1\n+\n+ Parameters\n+ ----------\n+ arr : numpy.ndarray\n+ The :class:`~numpy.ndarray` to apply the windowing operation to.\n+ ds : dataset.Dataset\n+ A dataset containing a :dcm:`VOI LUT Module<part03/sect_C.11.2.html>`.\n+ If (0028,1050) *Window Center* and (0028,1051) *Window Width* are\n+ present then returns an array of ``np.float64``, otherwise `arr` will\n+ be returned unchanged.\n+ index : int, optional\n+ When the VOI LUT Module contains multiple alternative views, this is\n+ the index of the view to return (default ``0``).\n+\n+ Returns\n+ -------\n+ numpy.ndarray\n+ An array with applied windowing operation.\n+\n+ Notes\n+ -----\n+ When the dataset requires a modality LUT or rescale operation as part of\n+ the Modality LUT module then that must be applied before any windowing\n+ operation.\n+\n+ See Also\n+ --------\n+ :func:`~pydicom.pixel_data_handlers.util.apply_modality_lut`\n+ :func:`~pydicom.pixel_data_handlers.util.apply_voi`\n+\n+ References\n+ ----------\n+ * DICOM Standard, Part 3, :dcm:`Annex C.11.2\n+ <part03/sect_C.11.html#sect_C.11.2>`\n+ * DICOM Standard, Part 3, :dcm:`Annex C.8.11.3.1.5\n+ <part03/sect_C.8.11.3.html#sect_C.8.11.3.1.5>`\n+ * DICOM Standard, Part 4, :dcm:`Annex N.2.1.1\n+ <part04/sect_N.2.html#sect_N.2.1.1>`\n+ \"\"\"\n+ if \"WindowWidth\" not in ds and \"WindowCenter\" not in ds:\n+ return arr\n+\n+ if ds.PhotometricInterpretation not in ['MONOCHROME1', 'MONOCHROME2']:\n+ raise ValueError(\n+ \"When performing a windowing operation only 'MONOCHROME1' and \"\n+ \"'MONOCHROME2' are allowed for (0028,0004) Photometric \"\n+ \"Interpretation\"\n+ )\n+\n+ # May be LINEAR (default), LINEAR_EXACT, SIGMOID or not present, VM 1\n+ voi_func = cast(str, getattr(ds, 'VOILUTFunction', 'LINEAR')).upper()\n+ # VR DS, VM 1-n\n+ elem = ds['WindowCenter']\n+ center = elem.value[index] if elem.VM > 1 else elem.value\n+ elem = ds['WindowWidth']\n+ width = elem.value[index] if elem.VM > 1 else elem.value\n+\n+ # The output range depends on whether or not a modality LUT or rescale\n+ # operation has been applied\n+ if 'ModalityLUTSequence' in ds:\n+ # Unsigned - see PS3.3 C.11.1.1.1\n+ y_min = 0\n+ bit_depth = ds.ModalityLUTSequence[0].LUTDescriptor[2]\n+ y_max = 2**bit_depth - 1\n+ elif ds.PixelRepresentation == 0:\n+ # Unsigned\n+ y_min = 0\n+ y_max = 2**ds.BitsStored - 1\n+ else:\n+ # Signed\n+ y_min = -2**(ds.BitsStored - 1)\n+ y_max = 2**(ds.BitsStored - 1) - 1\n+\n+ slope = ds.get('RescaleSlope', None)\n+ intercept = ds.get('RescaleIntercept', None)\n+ if slope is not None and intercept is not None:\n+ # Otherwise its the actual data range\n+ y_min = y_min * ds.RescaleSlope + ds.RescaleIntercept\n+ y_max = y_max * ds.RescaleSlope + ds.RescaleIntercept\n+\n+ y_range = y_max - y_min\n+ arr = arr.astype('float64')\n+\n+ if voi_func in ['LINEAR', 'LINEAR_EXACT']:\n+ # PS3.3 C.11.2.1.2.1 and C.11.2.1.3.2\n+ if voi_func == 'LINEAR':\n+ if width < 1:\n raise ValueError(\n- \"The (0028,1051) Window Width must be greater than 0 \"\n- \"for a 'SIGMOID' windowing operation\"\n+ \"The (0028,1051) Window Width must be greater than or \"\n+ \"equal to 1 for a 'LINEAR' windowing operation\"\n )\n+ center -= 0.5\n+ width -= 1\n+ elif width <= 0:\n+ raise ValueError(\n+ \"The (0028,1051) Window Width must be greater than 0 \"\n+ \"for a 'LINEAR_EXACT' windowing operation\"\n+ )\n \n- arr = y_range / (1 + np.exp(-4 * (arr - center) / width)) + y_min\n- else:\n+ below = arr <= (center - width / 2)\n+ above = arr > (center + width / 2)\n+ between = np.logical_and(~below, ~above)\n+\n+ arr[below] = y_min\n+ arr[above] = y_max\n+ if between.any():\n+ arr[between] = (\n+ ((arr[between] - center) / width + 0.5) * y_range + y_min\n+ )\n+ elif voi_func == 'SIGMOID':\n+ # PS3.3 C.11.2.1.3.1\n+ if width <= 0:\n raise ValueError(\n- \"Unsupported (0028,1056) VOI LUT Function value '{}'\"\n- .format(voi_func)\n+ \"The (0028,1051) Window Width must be greater than 0 \"\n+ \"for a 'SIGMOID' windowing operation\"\n )\n \n+ arr = y_range / (1 + np.exp(-4 * (arr - center) / width)) + y_min\n+ else:\n+ raise ValueError(\n+ f\"Unsupported (0028,1056) VOI LUT Function value '{voi_func}'\"\n+ )\n+\n return arr\n \n \n-def convert_color_space(arr, current, desired):\n+def convert_color_space(\n+ arr: \"np.ndarray\", current: str, desired: str\n+) -> \"np.ndarray\":\n \"\"\"Convert the image(s) in `arr` from one color space to another.\n \n .. versionchanged:: 1.4\n@@ -501,7 +642,7 @@ def _no_change(arr):\n return converter(arr)\n \n \n-def _convert_RGB_to_YBR_FULL(arr):\n+def _convert_RGB_to_YBR_FULL(arr: \"np.ndarray\") -> \"np.ndarray\":\n \"\"\"Return an ndarray converted from RGB to YBR_FULL color space.\n \n Parameters\n@@ -543,7 +684,7 @@ def _convert_RGB_to_YBR_FULL(arr):\n return arr.astype(orig_dtype)\n \n \n-def _convert_YBR_FULL_to_RGB(arr):\n+def _convert_YBR_FULL_to_RGB(arr: \"np.ndarray\") -> \"np.ndarray\":\n \"\"\"Return an ndarray converted from YBR_FULL to RGB color space.\n \n Parameters\n@@ -585,7 +726,9 @@ def _convert_YBR_FULL_to_RGB(arr):\n return arr.astype(orig_dtype)\n \n \n-def dtype_corrected_for_endianness(is_little_endian, numpy_dtype):\n+def dtype_corrected_for_endianness(\n+ is_little_endian: bool, numpy_dtype: \"np.dtype\"\n+) -> \"np.dtype\":\n \"\"\"Return a :class:`numpy.dtype` corrected for system and :class:`Dataset`\n endianness.\n \n@@ -618,7 +761,12 @@ def dtype_corrected_for_endianness(is_little_endian, numpy_dtype):\n return numpy_dtype\n \n \n-def _expand_segmented_lut(data, fmt, nr_segments=None, last_value=None):\n+def _expand_segmented_lut(\n+ data: Tuple[int, ...],\n+ fmt: str,\n+ nr_segments: Optional[int] = None,\n+ last_value: Optional[int] = None\n+) -> List[int]:\n \"\"\"Return a list containing the expanded lookup table data.\n \n Parameters\n@@ -652,7 +800,7 @@ def _expand_segmented_lut(data, fmt, nr_segments=None, last_value=None):\n # Little endian: e.g. 0x0302 0x0100, big endian, e.g. 0x0203 0x0001\n indirect_ii = [3, 2, 1, 0] if '<' in fmt else [2, 3, 0, 1]\n \n- lut = []\n+ lut: List[int] = []\n offset = 0\n segments_read = 0\n # Use `offset + 1` to account for possible trailing null\n@@ -722,7 +870,7 @@ def _expand_segmented_lut(data, fmt, nr_segments=None, last_value=None):\n return lut\n \n \n-def get_expected_length(ds, unit='bytes'):\n+def get_expected_length(ds: \"Dataset\", unit: str = 'bytes') -> int:\n \"\"\"Return the expected length (in terms of bytes or pixels) of the *Pixel\n Data*.\n \n@@ -765,14 +913,14 @@ def get_expected_length(ds, unit='bytes'):\n The expected length of the *Pixel Data* in either whole bytes or\n pixels, excluding the NULL trailing padding byte for odd length data.\n \"\"\"\n- length = ds.Rows * ds.Columns * ds.SamplesPerPixel\n+ length: int = ds.Rows * ds.Columns * ds.SamplesPerPixel\n length *= get_nr_frames(ds)\n \n if unit == 'pixels':\n return length\n \n # Correct for the number of bytes per pixel\n- bits_allocated = ds.BitsAllocated\n+ bits_allocated = cast(int, ds.BitsAllocated)\n if bits_allocated == 1:\n # Determine the nearest whole number of bytes needed to contain\n # 1-bit pixel data. e.g. 10 x 10 1-bit pixels is 100 bits, which\n@@ -788,7 +936,7 @@ def get_expected_length(ds, unit='bytes'):\n return length\n \n \n-def get_image_pixel_ids(ds) -> Dict[str, int]:\n+def get_image_pixel_ids(ds: \"Dataset\") -> Dict[str, int]:\n \"\"\"Return a dict of the pixel data affecting element's :func:`id` values.\n \n .. versionadded:: 1.4\n@@ -845,7 +993,7 @@ def get_image_pixel_ids(ds) -> Dict[str, int]:\n return {kw: id(getattr(ds, kw, None)) for kw in keywords}\n \n \n-def get_j2k_parameters(codestream):\n+def get_j2k_parameters(codestream: bytes) -> Dict[str, object]:\n \"\"\"Return a dict containing JPEG 2000 component parameters.\n \n .. versionadded:: 2.1\n@@ -883,7 +1031,7 @@ def get_j2k_parameters(codestream):\n return {}\n \n \n-def get_nr_frames(ds):\n+def get_nr_frames(ds: \"Dataset\") -> int:\n \"\"\"Return NumberOfFrames or 1 if NumberOfFrames is None.\n \n Parameters\n@@ -897,7 +1045,7 @@ def get_nr_frames(ds):\n int\n An integer for the NumberOfFrames or 1 if NumberOfFrames is None\n \"\"\"\n- nr_frames = getattr(ds, 'NumberOfFrames', 1)\n+ nr_frames: Optional[int] = getattr(ds, 'NumberOfFrames', 1)\n # 'NumberOfFrames' may exist in the DICOM file but have value equal to None\n if nr_frames is None:\n warnings.warn(\"A value of None for (0028,0008) 'Number of Frames' is \"\n@@ -908,7 +1056,7 @@ def get_nr_frames(ds):\n return nr_frames\n \n \n-def pixel_dtype(ds, as_float=False):\n+def pixel_dtype(ds: \"Dataset\", as_float: bool = False) -> \"np.dtype\":\n \"\"\"Return a :class:`numpy.dtype` for the pixel data in `ds`.\n \n Suitable for use with IODs containing the Image Pixel module (with\n@@ -1009,7 +1157,7 @@ def pixel_dtype(ds, as_float=False):\n return dtype\n \n \n-def reshape_pixel_array(ds, arr):\n+def reshape_pixel_array(ds: \"Dataset\", arr: \"np.ndarray\") -> \"np.ndarray\":\n \"\"\"Return a reshaped :class:`numpy.ndarray` `arr`.\n \n +------------------------------------------+-----------+----------+\n", "test_patch": "diff --git a/pydicom/tests/test_handler_util.py b/pydicom/tests/test_handler_util.py\n--- a/pydicom/tests/test_handler_util.py\n+++ b/pydicom/tests/test_handler_util.py\n@@ -28,7 +28,9 @@\n apply_modality_lut,\n apply_voi_lut,\n get_j2k_parameters,\n- get_nr_frames\n+ get_nr_frames,\n+ apply_voi,\n+ apply_windowing\n )\n from pydicom.uid import (ExplicitVRLittleEndian, ImplicitVRLittleEndian,\n UncompressedPixelTransferSyntaxes)\n@@ -1412,191 +1414,8 @@ def test_unknown_opcode_raises(self):\n \n \n @pytest.mark.skipif(not HAVE_NP, reason=\"Numpy is not available\")\n-class TestNumpy_VOILUT:\n- \"\"\"Tests for util.apply_voi_lut().\"\"\"\n- def test_voi_single_view(self):\n- \"\"\"Test VOI LUT with a single view.\"\"\"\n- ds = dcmread(VOI_08_1F)\n- assert 8 == ds.BitsAllocated\n- assert 8 == ds.BitsStored\n- assert 0 == ds.PixelRepresentation\n- item = ds.VOILUTSequence[0]\n- assert [256, 0, 16] == item.LUTDescriptor\n- lut = item.LUTData\n- assert 0 == lut[0]\n- assert 19532 == lut[76]\n- assert 45746 == lut[178]\n- assert 65535 == lut[255]\n-\n- arr = ds.pixel_array\n- assert 0 == arr[387, 448]\n- assert 76 == arr[178, 126]\n- assert 178 == arr[186, 389]\n- assert 255 == arr[129, 79]\n-\n- out = apply_voi_lut(arr, ds)\n- assert 0 == out[387, 448]\n- assert 19532 == out[178, 126]\n- assert 45746 == out[186, 389]\n- assert 65535 == out[129, 79]\n-\n- def test_voi_multi_view(self):\n- \"\"\"Test VOI LUT with multiple views.\"\"\"\n- ds = dcmread(VOI_08_1F)\n- assert 8 == ds.BitsAllocated\n- assert 8 == ds.BitsStored\n- assert 0 == ds.PixelRepresentation\n- item0 = ds.VOILUTSequence[0]\n- # Add another view thats the inverse\n- ds.VOILUTSequence.append(Dataset())\n- item1 = ds.VOILUTSequence[1]\n- item1.LUTDescriptor = [256, 0, 16]\n- item1.LUTData = item0.LUTData[::-1]\n-\n- arr = ds.pixel_array\n- assert 0 == arr[387, 448]\n- assert 76 == arr[178, 126]\n- assert 178 == arr[186, 389]\n- assert 255 == arr[129, 79]\n-\n- out0 = apply_voi_lut(arr, ds)\n- assert 0 == out0[387, 448]\n- assert 19532 == out0[178, 126]\n- assert 45746 == out0[186, 389]\n- assert 65535 == out0[129, 79]\n-\n- out1 = apply_voi_lut(arr, ds, index=1)\n- assert 65535 == out1[387, 448]\n- assert 46003 == out1[178, 126]\n- assert 19789 == out1[186, 389]\n- assert 0 == out1[129, 79]\n-\n- def test_voi_multi_frame(self):\n- \"\"\"Test VOI with a multiple frames.\"\"\"\n- ds = dcmread(VOI_08_1F)\n- assert 8 == ds.BitsAllocated\n- assert 8 == ds.BitsStored\n- assert 0 == ds.PixelRepresentation\n-\n- arr = ds.pixel_array\n- arr = np.stack([arr, 255 - arr])\n- assert (2, 512, 512) == arr.shape\n-\n- out = apply_voi_lut(arr, ds)\n- assert 0 == out[0, 387, 448]\n- assert 19532 == out[0, 178, 126]\n- assert 45746 == out[0, 186, 389]\n- assert 65535 == out[0, 129, 79]\n- assert 65535 == out[1, 387, 448]\n- assert 46003 == out[1, 178, 126]\n- assert 19789 == out[1, 186, 389]\n- assert 0 == out[1, 129, 79]\n-\n- def test_voi_zero_entries(self):\n- \"\"\"Test that 0 entries is interpreted correctly.\"\"\"\n- ds = dcmread(VOI_08_1F)\n- seq = ds.VOILUTSequence[0]\n- seq.LUTDescriptor = [0, 0, 16]\n- assert 256 == len(seq.LUTData)\n- arr = np.asarray([0, 255, 256, 65535])\n- msg = r\"index 256 is out of bounds\"\n- with pytest.raises(IndexError, match=msg):\n- apply_voi_lut(arr, ds)\n-\n- # LUTData with 65536 entries\n- seq.LUTData = [0] * 65535 + [1]\n- out = apply_voi_lut(arr, ds)\n- assert [0, 0, 0, 1] == list(out)\n-\n- def test_voi_uint8(self):\n- \"\"\"Test uint VOI LUT with an 8-bit LUT.\"\"\"\n- ds = Dataset()\n- ds.PixelRepresentation = 0\n- ds.BitsStored = 8\n- ds.VOILUTSequence = [Dataset()]\n- item = ds.VOILUTSequence[0]\n- item.LUTDescriptor = [4, 0, 8]\n- item.LUTData = [0, 127, 128, 255]\n- arr = np.asarray([0, 1, 128, 254, 255], dtype='uint8')\n- out = apply_voi_lut(arr, ds)\n- assert 'uint8' == out.dtype\n- assert [0, 127, 255, 255, 255] == out.tolist()\n-\n- def test_voi_uint16(self):\n- \"\"\"Test uint VOI LUT with an 16-bit LUT.\"\"\"\n- ds = Dataset()\n- ds.PixelRepresentation = 0\n- ds.BitsStored = 16\n- ds.VOILUTSequence = [Dataset()]\n- item = ds.VOILUTSequence[0]\n- item.LUTDescriptor = [4, 0, 16]\n- item.LUTData = [0, 127, 32768, 65535]\n- arr = np.asarray([0, 1, 2, 3, 255], dtype='uint16')\n- out = apply_voi_lut(arr, ds)\n- assert 'uint16' == out.dtype\n- assert [0, 127, 32768, 65535, 65535] == out.tolist()\n-\n- def test_voi_int8(self):\n- \"\"\"Test int VOI LUT with an 8-bit LUT.\"\"\"\n- ds = Dataset()\n- ds.PixelRepresentation = 1\n- ds.BitsStored = 8\n- ds.VOILUTSequence = [Dataset()]\n- item = ds.VOILUTSequence[0]\n- item.LUTDescriptor = [4, 0, 8]\n- item.LUTData = [0, 127, 128, 255]\n- arr = np.asarray([0, -1, 2, -128, 127], dtype='int8')\n- out = apply_voi_lut(arr, ds)\n- assert 'uint8' == out.dtype\n- assert [0, 0, 128, 0, 255] == out.tolist()\n-\n- def test_voi_int16(self):\n- \"\"\"Test int VOI LUT with an 16-bit LUT.\"\"\"\n- ds = Dataset()\n- ds.PixelRepresentation = 0\n- ds.BitsStored = 16\n- ds.VOILUTSequence = [Dataset()]\n- item = ds.VOILUTSequence[0]\n- item.LUTDescriptor = [4, 0, 16]\n- item.LUTData = [0, 127, 32768, 65535]\n- arr = np.asarray([0, -1, 2, -128, 255], dtype='int16')\n- out = apply_voi_lut(arr, ds)\n- assert 'uint16' == out.dtype\n- assert [0, 0, 32768, 0, 65535] == out.tolist()\n-\n- def test_voi_bad_depth(self):\n- \"\"\"Test bad LUT depth raises exception.\"\"\"\n- ds = dcmread(VOI_08_1F)\n- item = ds.VOILUTSequence[0]\n- item.LUTDescriptor[2] = 7\n- msg = r\"'7' bits per LUT entry is not supported\"\n- with pytest.raises(NotImplementedError, match=msg):\n- apply_voi_lut(ds.pixel_array, ds)\n-\n- item.LUTDescriptor[2] = 17\n- msg = r\"'17' bits per LUT entry is not supported\"\n- with pytest.raises(NotImplementedError, match=msg):\n- apply_voi_lut(ds.pixel_array, ds)\n-\n- def test_voi_uint16_array_float(self):\n- \"\"\"Test warning when array is float and VOI LUT with an 16-bit LUT\"\"\"\n- ds = Dataset()\n- ds.PixelRepresentation = 0\n- ds.BitsStored = 16\n- ds.VOILUTSequence = [Dataset()]\n- item = ds.VOILUTSequence[0]\n- item.LUTDescriptor = [4, 0, 16]\n- item.LUTData = [0, 127, 32768, 65535]\n- arr = np.asarray([0, 1, 2, 3, 255], dtype='float64')\n- msg = (\n- r\"Applying a VOI LUT on a float input array may give \"\n- r\"incorrect results\"\n- )\n-\n- with pytest.warns(UserWarning, match=msg):\n- out = apply_voi_lut(arr, ds)\n- assert [0, 127, 32768, 65535, 65535] == out.tolist()\n-\n+class TestNumpy_ApplyWindowing:\n+ \"\"\"Tests for util.apply_windowing().\"\"\"\n def test_window_single_view(self):\n \"\"\"Test windowing with a single view.\"\"\"\n # 12-bit unsigned\n@@ -1611,7 +1430,7 @@ def test_window_single_view(self):\n \n arr = ds.pixel_array\n assert 642 == arr[326, 130]\n- out = apply_voi_lut(arr, ds)\n+ out = apply_windowing(arr, ds)\n assert 3046.6 == pytest.approx(out[326, 130], abs=0.1)\n \n def test_window_multi_view(self):\n@@ -1631,9 +1450,9 @@ def test_window_multi_view(self):\n \n arr = ds.pixel_array\n assert 642 == arr[326, 130]\n- out = apply_voi_lut(arr, ds)\n+ out = apply_windowing(arr, ds)\n assert 3046.6 == pytest.approx(out[326, 130], abs=0.1)\n- out = apply_voi_lut(arr, ds, index=1)\n+ out = apply_windowing(arr, ds, index=1)\n assert 4095.0 == pytest.approx(out[326, 130], abs=0.1)\n \n def test_window_uint8(self):\n@@ -1647,24 +1466,24 @@ def test_window_uint8(self):\n # Linear\n ds.WindowWidth = 1\n ds.WindowCenter = 0\n- assert [255, 255, 255, 255, 255] == apply_voi_lut(arr, ds).tolist()\n+ assert [255, 255, 255, 255, 255] == apply_windowing(arr, ds).tolist()\n \n ds.WindowWidth = 128\n ds.WindowCenter = 254\n assert [0, 0, 0, 128.5, 130.5] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n # Linear exact\n ds.VOILUTFunction = 'LINEAR_EXACT'\n assert [0, 0, 0, 127.5, 129.5] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n # Sigmoid\n ds.VOILUTFunction = 'SIGMOID'\n assert [0.1, 0.1, 4.9, 127.5, 129.5] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n def test_window_uint16(self):\n@@ -1677,22 +1496,22 @@ def test_window_uint16(self):\n \n ds.WindowWidth = 1\n ds.WindowCenter = 0\n- assert [65535] * 5 == apply_voi_lut(arr, ds).tolist()\n+ assert [65535] * 5 == apply_windowing(arr, ds).tolist()\n \n ds.WindowWidth = 32768\n ds.WindowCenter = 254\n assert [32260.5, 32262.5, 65535, 65535, 65535] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n ds.VOILUTFunction = 'LINEAR_EXACT'\n assert [32259.5, 32261.5, 65535, 65535, 65535] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n ds.VOILUTFunction = 'SIGMOID'\n assert [32259.5, 32261.5, 64319.8, 65512.3, 65512.3] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n def test_window_uint32(self):\n@@ -1706,14 +1525,14 @@ def test_window_uint32(self):\n \n ds.WindowWidth = 1\n ds.WindowCenter = 0\n- assert [y_max] * 5 == apply_voi_lut(arr, ds).tolist()\n+ assert [y_max] * 5 == apply_windowing(arr, ds).tolist()\n \n ds.WindowWidth = 342423423423\n ds.WindowCenter = 757336\n assert (\n [2147474148.4, 2147474148.4,\n 2174409724, 2201345299.7, 2201345299.7] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1721,7 +1540,7 @@ def test_window_uint32(self):\n assert (\n [2147474148.3, 2147474148.4,\n 2174409724, 2201345299.7, 2201345299.7] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1729,7 +1548,7 @@ def test_window_uint32(self):\n assert (\n [2147474148.3, 2147474148.4,\n 2174408313.1, 2201334008.2, 2201334008.3] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1745,25 +1564,25 @@ def test_window_int8(self):\n ds.WindowWidth = 1\n ds.WindowCenter = 0\n assert [-128, -128, -128, 127, 127, 127, 127] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist()\n+ apply_windowing(arr, ds).tolist()\n )\n \n ds.WindowWidth = 128\n ds.WindowCenter = -5\n assert [-128, -128, 8.5, 10.5, 12.6, 127, 127] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n # Linear exact\n ds.VOILUTFunction = 'LINEAR_EXACT'\n assert [-128, -128, 7.5, 9.5, 11.5, 127, 127] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n # Sigmoid\n ds.VOILUTFunction = 'SIGMOID'\n assert [-122.7, -122.5, 7.5, 9.4, 11.4, 122.8, 122.9] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n \n def test_window_int16(self):\n@@ -1780,7 +1599,7 @@ def test_window_int16(self):\n assert (\n [-32768, -32768, -32768,\n 32767, 32767, 32767, 32767] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1789,7 +1608,7 @@ def test_window_int16(self):\n assert (\n [-32768, -32768, 2321.6,\n 2837.6, 3353.7, 32767, 32767] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1798,7 +1617,7 @@ def test_window_int16(self):\n assert (\n [-32768, -32768, 2047.5,\n 2559.5, 3071.5, 32767, 32767] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1807,7 +1626,7 @@ def test_window_int16(self):\n assert (\n [-31394.1, -31351.4, 2044.8,\n 2554.3, 3062.5, 31692, 31724.6] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1825,7 +1644,7 @@ def test_window_int32(self):\n assert (\n [-2**31, -2**31, -2**31,\n 2**31 - 1, 2**31 - 1, 2**31 - 1, 2**31 - 1] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1834,7 +1653,7 @@ def test_window_int32(self):\n assert (\n [-2147483648, -2147483648, 152183880, 186002520.1,\n 219821160.3, 2147483647, 2147483647] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1843,7 +1662,7 @@ def test_window_int32(self):\n assert (\n [-2147483648, -2147483648, 134217727.5, 167772159.5,\n 201326591.5, 2147483647, 2147483647] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1852,7 +1671,7 @@ def test_window_int32(self):\n assert (\n [-2057442919.3, -2054646500.7, 134043237.4, 167431657.4,\n 200738833.7, 2077033158.8, 2079166214.8] == pytest.approx(\n- apply_voi_lut(arr, ds).tolist(), abs=0.1\n+ apply_windowing(arr, ds).tolist(), abs=0.1\n )\n )\n \n@@ -1872,7 +1691,7 @@ def test_window_multi_frame(self):\n assert (2, 484, 484) == arr.shape\n assert 642 == arr[0, 326, 130]\n assert 3453 == arr[1, 326, 130]\n- out = apply_voi_lut(arr, ds)\n+ out = apply_windowing(arr, ds)\n assert 3046.6 == pytest.approx(out[0, 326, 130], abs=0.1)\n assert 4095.0 == pytest.approx(out[1, 326, 130], abs=0.1)\n \n@@ -1902,7 +1721,7 @@ def test_window_rescale(self):\n assert 770.4 == hu[326, 130]\n assert 1347.6 == hu[316, 481]\n # With rescale -> output range is 0 to 4914\n- out = apply_voi_lut(hu, ds)\n+ out = apply_windowing(hu, ds)\n assert 0 == pytest.approx(out[16, 60], abs=0.1)\n assert 4455.6 == pytest.approx(out[326, 130], abs=0.1)\n assert 4914.0 == pytest.approx(out[316, 481], abs=0.1)\n@@ -1930,7 +1749,7 @@ def test_window_modality_lut(self):\n hu = apply_modality_lut(arr, ds)\n assert 65535 == hu[16, 60]\n assert 49147 == hu[0, 1]\n- out = apply_voi_lut(hu, ds)\n+ out = apply_windowing(hu, ds)\n assert 65535.0 == pytest.approx(out[16, 60], abs=0.1)\n assert 32809.0 == pytest.approx(out[0, 1], abs=0.1)\n # Output range must be 0 to 2**16 - 1\n@@ -1943,7 +1762,7 @@ def test_window_bad_photometric_interp(self):\n ds.PhotometricInterpretation = 'RGB'\n msg = r\"only 'MONOCHROME1' and 'MONOCHROME2' are allowed\"\n with pytest.raises(ValueError, match=msg):\n- apply_voi_lut(ds.pixel_array, ds)\n+ apply_windowing(ds.pixel_array, ds)\n \n def test_window_bad_parameters(self):\n \"\"\"Test bad windowing parameters raise exceptions.\"\"\"\n@@ -1952,22 +1771,22 @@ def test_window_bad_parameters(self):\n ds.VOILUTFunction = 'LINEAR'\n msg = r\"Width must be greater than or equal to 1\"\n with pytest.raises(ValueError, match=msg):\n- apply_voi_lut(ds.pixel_array, ds)\n+ apply_windowing(ds.pixel_array, ds)\n \n ds.VOILUTFunction = 'LINEAR_EXACT'\n msg = r\"Width must be greater than 0\"\n with pytest.raises(ValueError, match=msg):\n- apply_voi_lut(ds.pixel_array, ds)\n+ apply_windowing(ds.pixel_array, ds)\n \n ds.VOILUTFunction = 'SIGMOID'\n msg = r\"Width must be greater than 0\"\n with pytest.raises(ValueError, match=msg):\n- apply_voi_lut(ds.pixel_array, ds)\n+ apply_windowing(ds.pixel_array, ds)\n \n ds.VOILUTFunction = 'UNKNOWN'\n msg = r\"Unsupported \\(0028,1056\\) VOI LUT Function value 'UNKNOWN'\"\n with pytest.raises(ValueError, match=msg):\n- apply_voi_lut(ds.pixel_array, ds)\n+ apply_windowing(ds.pixel_array, ds)\n \n def test_window_bad_index(self, no_numpy_use):\n \"\"\"Test windowing with a bad view index.\"\"\"\n@@ -1975,7 +1794,7 @@ def test_window_bad_index(self, no_numpy_use):\n assert 2 == len(ds.WindowWidth)\n arr = ds.pixel_array\n with pytest.raises(IndexError, match=r\"list index out of range\"):\n- apply_voi_lut(arr, ds, index=2)\n+ apply_windowing(arr, ds, index=2)\n \n def test_unchanged(self):\n \"\"\"Test input array is unchanged if no VOI LUT\"\"\"\n@@ -1984,7 +1803,219 @@ def test_unchanged(self):\n ds.PixelRepresentation = 1\n ds.BitsStored = 8\n arr = np.asarray([-128, -127, -1, 0, 1, 126, 127], dtype='int8')\n- out = apply_voi_lut(arr, ds)\n+ out = apply_windowing(arr, ds)\n+ assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n+\n+ def test_rescale_empty(self):\n+ \"\"\"Test RescaleSlope and RescaleIntercept being empty.\"\"\"\n+ ds = dcmread(WIN_12_1F)\n+ ds.RescaleSlope = None\n+ ds.RescaleIntercept = None\n+\n+ arr = ds.pixel_array\n+ assert 0 == arr[16, 60]\n+ assert 642 == arr[326, 130]\n+ assert 1123 == arr[316, 481]\n+ out = apply_windowing(arr, ds)\n+ assert 0 == pytest.approx(out[16, 60], abs=0.1)\n+ assert 3046.6 == pytest.approx(out[326, 130], abs=0.1)\n+ assert 4095.0 == pytest.approx(out[316, 481], abs=0.1)\n+\n+\[email protected](not HAVE_NP, reason=\"Numpy is not available\")\n+class TestNumpy_ApplyVOI:\n+ \"\"\"Tests for util.apply_voi().\"\"\"\n+ def test_voi_single_view(self):\n+ \"\"\"Test VOI LUT with a single view.\"\"\"\n+ ds = dcmread(VOI_08_1F)\n+ assert 8 == ds.BitsAllocated\n+ assert 8 == ds.BitsStored\n+ assert 0 == ds.PixelRepresentation\n+ item = ds.VOILUTSequence[0]\n+ assert [256, 0, 16] == item.LUTDescriptor\n+ lut = item.LUTData\n+ assert 0 == lut[0]\n+ assert 19532 == lut[76]\n+ assert 45746 == lut[178]\n+ assert 65535 == lut[255]\n+\n+ arr = ds.pixel_array\n+ assert 0 == arr[387, 448]\n+ assert 76 == arr[178, 126]\n+ assert 178 == arr[186, 389]\n+ assert 255 == arr[129, 79]\n+\n+ out = apply_voi(arr, ds)\n+ assert 0 == out[387, 448]\n+ assert 19532 == out[178, 126]\n+ assert 45746 == out[186, 389]\n+ assert 65535 == out[129, 79]\n+\n+ def test_voi_multi_view(self):\n+ \"\"\"Test VOI LUT with multiple views.\"\"\"\n+ ds = dcmread(VOI_08_1F)\n+ assert 8 == ds.BitsAllocated\n+ assert 8 == ds.BitsStored\n+ assert 0 == ds.PixelRepresentation\n+ item0 = ds.VOILUTSequence[0]\n+ # Add another view thats the inverse\n+ ds.VOILUTSequence.append(Dataset())\n+ item1 = ds.VOILUTSequence[1]\n+ item1.LUTDescriptor = [256, 0, 16]\n+ item1.LUTData = item0.LUTData[::-1]\n+\n+ arr = ds.pixel_array\n+ assert 0 == arr[387, 448]\n+ assert 76 == arr[178, 126]\n+ assert 178 == arr[186, 389]\n+ assert 255 == arr[129, 79]\n+\n+ out0 = apply_voi(arr, ds)\n+ assert 0 == out0[387, 448]\n+ assert 19532 == out0[178, 126]\n+ assert 45746 == out0[186, 389]\n+ assert 65535 == out0[129, 79]\n+\n+ out1 = apply_voi(arr, ds, index=1)\n+ assert 65535 == out1[387, 448]\n+ assert 46003 == out1[178, 126]\n+ assert 19789 == out1[186, 389]\n+ assert 0 == out1[129, 79]\n+\n+ def test_voi_multi_frame(self):\n+ \"\"\"Test VOI with a multiple frames.\"\"\"\n+ ds = dcmread(VOI_08_1F)\n+ assert 8 == ds.BitsAllocated\n+ assert 8 == ds.BitsStored\n+ assert 0 == ds.PixelRepresentation\n+\n+ arr = ds.pixel_array\n+ arr = np.stack([arr, 255 - arr])\n+ assert (2, 512, 512) == arr.shape\n+\n+ out = apply_voi(arr, ds)\n+ assert 0 == out[0, 387, 448]\n+ assert 19532 == out[0, 178, 126]\n+ assert 45746 == out[0, 186, 389]\n+ assert 65535 == out[0, 129, 79]\n+ assert 65535 == out[1, 387, 448]\n+ assert 46003 == out[1, 178, 126]\n+ assert 19789 == out[1, 186, 389]\n+ assert 0 == out[1, 129, 79]\n+\n+ def test_voi_zero_entries(self):\n+ \"\"\"Test that 0 entries is interpreted correctly.\"\"\"\n+ ds = dcmread(VOI_08_1F)\n+ seq = ds.VOILUTSequence[0]\n+ seq.LUTDescriptor = [0, 0, 16]\n+ assert 256 == len(seq.LUTData)\n+ arr = np.asarray([0, 255, 256, 65535])\n+ msg = r\"index 256 is out of bounds\"\n+ with pytest.raises(IndexError, match=msg):\n+ apply_voi(arr, ds)\n+\n+ # LUTData with 65536 entries\n+ seq.LUTData = [0] * 65535 + [1]\n+ out = apply_voi(arr, ds)\n+ assert [0, 0, 0, 1] == list(out)\n+\n+ def test_voi_uint8(self):\n+ \"\"\"Test uint VOI LUT with an 8-bit LUT.\"\"\"\n+ ds = Dataset()\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 8\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 8]\n+ item.LUTData = [0, 127, 128, 255]\n+ arr = np.asarray([0, 1, 128, 254, 255], dtype='uint8')\n+ out = apply_voi(arr, ds)\n+ assert 'uint8' == out.dtype\n+ assert [0, 127, 255, 255, 255] == out.tolist()\n+\n+ def test_voi_uint16(self):\n+ \"\"\"Test uint VOI LUT with an 16-bit LUT.\"\"\"\n+ ds = Dataset()\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 16\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 16]\n+ item.LUTData = [0, 127, 32768, 65535]\n+ arr = np.asarray([0, 1, 2, 3, 255], dtype='uint16')\n+ out = apply_voi(arr, ds)\n+ assert 'uint16' == out.dtype\n+ assert [0, 127, 32768, 65535, 65535] == out.tolist()\n+\n+ def test_voi_int8(self):\n+ \"\"\"Test int VOI LUT with an 8-bit LUT.\"\"\"\n+ ds = Dataset()\n+ ds.PixelRepresentation = 1\n+ ds.BitsStored = 8\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 8]\n+ item.LUTData = [0, 127, 128, 255]\n+ arr = np.asarray([0, -1, 2, -128, 127], dtype='int8')\n+ out = apply_voi(arr, ds)\n+ assert 'uint8' == out.dtype\n+ assert [0, 0, 128, 0, 255] == out.tolist()\n+\n+ def test_voi_int16(self):\n+ \"\"\"Test int VOI LUT with an 16-bit LUT.\"\"\"\n+ ds = Dataset()\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 16\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 16]\n+ item.LUTData = [0, 127, 32768, 65535]\n+ arr = np.asarray([0, -1, 2, -128, 255], dtype='int16')\n+ out = apply_voi(arr, ds)\n+ assert 'uint16' == out.dtype\n+ assert [0, 0, 32768, 0, 65535] == out.tolist()\n+\n+ def test_voi_bad_depth(self):\n+ \"\"\"Test bad LUT depth raises exception.\"\"\"\n+ ds = dcmread(VOI_08_1F)\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor[2] = 7\n+ msg = r\"'7' bits per LUT entry is not supported\"\n+ with pytest.raises(NotImplementedError, match=msg):\n+ apply_voi(ds.pixel_array, ds)\n+\n+ item.LUTDescriptor[2] = 17\n+ msg = r\"'17' bits per LUT entry is not supported\"\n+ with pytest.raises(NotImplementedError, match=msg):\n+ apply_voi(ds.pixel_array, ds)\n+\n+ def test_voi_uint16_array_float(self):\n+ \"\"\"Test warning when array is float and VOI LUT with an 16-bit LUT\"\"\"\n+ ds = Dataset()\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 16\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 16]\n+ item.LUTData = [0, 127, 32768, 65535]\n+ arr = np.asarray([0, 1, 2, 3, 255], dtype='float64')\n+ msg = (\n+ r\"Applying a VOI LUT on a float input array may give \"\n+ r\"incorrect results\"\n+ )\n+\n+ with pytest.warns(UserWarning, match=msg):\n+ out = apply_voi(arr, ds)\n+ assert [0, 127, 32768, 65535, 65535] == out.tolist()\n+\n+ def test_unchanged(self):\n+ \"\"\"Test input array is unchanged if no VOI LUT\"\"\"\n+ ds = Dataset()\n+ ds.PhotometricInterpretation = 'MONOCHROME1'\n+ ds.PixelRepresentation = 1\n+ ds.BitsStored = 8\n+ arr = np.asarray([-128, -127, -1, 0, 1, 126, 127], dtype='int8')\n+ out = apply_voi(arr, ds)\n assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n \n def test_voi_lutdata_ow(self):\n@@ -2001,11 +2032,94 @@ def test_voi_lutdata_ow(self):\n item.LUTData = pack('<4H', *item.LUTData)\n item['LUTData'].VR = 'OW'\n arr = np.asarray([0, 1, 2, 3, 255], dtype='uint16')\n- out = apply_voi_lut(arr, ds)\n+ out = apply_voi(arr, ds)\n assert 'uint16' == out.dtype\n assert [0, 127, 32768, 65535, 65535] == out.tolist()\n \n \[email protected](not HAVE_NP, reason=\"Numpy is not available\")\n+class TestNumpy_ApplyVOILUT:\n+ def test_unchanged(self):\n+ \"\"\"Test input array is unchanged if no VOI LUT\"\"\"\n+ ds = Dataset()\n+ ds.PhotometricInterpretation = 'MONOCHROME1'\n+ ds.PixelRepresentation = 1\n+ ds.BitsStored = 8\n+ arr = np.asarray([-128, -127, -1, 0, 1, 126, 127], dtype='int8')\n+ out = apply_voi_lut(arr, ds)\n+ assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n+\n+ def test_only_windowing(self):\n+ \"\"\"Test only windowing operation elements present.\"\"\"\n+ ds = Dataset()\n+ ds.PhotometricInterpretation = 'MONOCHROME1'\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 8\n+ arr = np.asarray([0, 1, 128, 254, 255], dtype='uint8')\n+\n+ ds.WindowWidth = 1\n+ ds.WindowCenter = 0\n+ assert [255, 255, 255, 255, 255] == apply_voi_lut(arr, ds).tolist()\n+\n+ def test_only_voi(self):\n+ \"\"\"Test only LUT operation elements present.\"\"\"\n+ ds = Dataset()\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 8\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 8]\n+ item.LUTData = [0, 127, 128, 255]\n+ arr = np.asarray([0, 1, 128, 254, 255], dtype='uint8')\n+ out = apply_voi_lut(arr, ds)\n+ assert 'uint8' == out.dtype\n+ assert [0, 127, 255, 255, 255] == out.tolist()\n+\n+ def test_voi_windowing(self):\n+ \"\"\"Test both LUT and windowing operation elements present.\"\"\"\n+ ds = Dataset()\n+ ds.PhotometricInterpretation = 'MONOCHROME1'\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 8\n+ ds.WindowWidth = 1\n+ ds.WindowCenter = 0\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 8]\n+ item.LUTData = [0, 127, 128, 255]\n+ arr = np.asarray([0, 1, 128, 254, 255], dtype='uint8')\n+\n+ # Defaults to LUT\n+ out = apply_voi_lut(arr, ds)\n+ assert [0, 127, 255, 255, 255] == out.tolist()\n+\n+ out = apply_voi_lut(arr, ds, prefer_lut=False)\n+ assert [255, 255, 255, 255, 255] == out.tolist()\n+\n+ def test_voi_windowing_empty(self):\n+ \"\"\"Test empty VOI elements.\"\"\"\n+ ds = Dataset()\n+ ds.PhotometricInterpretation = 'MONOCHROME1'\n+ ds.PixelRepresentation = 0\n+ ds.BitsStored = 8\n+ ds.WindowWidth = 1\n+ ds.WindowCenter = 0\n+ ds.VOILUTSequence = [Dataset()]\n+ item = ds.VOILUTSequence[0]\n+ item.LUTDescriptor = [4, 0, 8]\n+ item.LUTData = [0, 127, 128, 255]\n+ arr = np.asarray([0, 1, 128, 254, 255], dtype='uint8')\n+\n+ # Test empty VOI elements\n+ item.LUTData = None\n+ out = apply_voi_lut(arr, ds)\n+ assert [255, 255, 255, 255, 255] == out.tolist()\n+\n+ # Test empty windowing elements\n+ ds.WindowWidth = None\n+ out = apply_voi_lut(arr, ds)\n+ assert [0, 1, 128, 254, 255] == out.tolist()\n+\n class TestGetJ2KParameters:\n \"\"\"Tests for get_j2k_parameters.\"\"\"\n def test_precision(self):\n", "problem_statement": "apply_voi_lut - unclear what it does if both WL/VOILUTFunction _and_ VOILUTSequence are present\nhttps://pydicom.github.io/pydicom/dev/reference/generated/pydicom.pixel_data_handlers.util.html#pydicom.pixel_data_handlers.util.apply_voi_lut\r\n\r\nHi all,\r\n\r\nI'm working with some mammo image (digital) that have both \r\n- window/level (0028,1050 0028,1051) plus VOILUTFunction (0028,1056) (set to SIGMOID) (set of 3 WL values)\r\n- VOILUT sequences (0028, 3010)\r\n\r\nspecified.\r\n\r\nProblem\r\n---\r\n\r\nIt's unclear from the documentation when both a VOILUT (0028,3010) _and_ WL (0028,1051...) are present which is applied - the lut or the wl.\r\n\r\nIt just says if a LUT's present, it will apply that, and if a WL set is present it will apply that.\r\n\r\nQuestions\r\n---\r\n\r\n- If both LUT and WL are supplied, by the dicom standard, which should be applied?\r\n- Separately to the above question about which is applied, if _both_ LUT and WL sequences are supplied, is there a way in `apply_voi_lut` to specify applying one or the other? (ie force application of the WL instead of LUT etc)\r\n\r\n- Also, if an image has a sequence of WL values rather than being single valued (so 0028,1050 & 0028,1051 are sequences), does the `index` parameter to `apply_voi_lut` apply to specify which in the sequence you want to use?\r\n\r\nThanks!\r\n\napply_voi_lut can't handle missing DICOM meta info\nI have encountered two real life examples where `apply_voi_lut` does not handle corruption in DICOM meta fields\r\n\r\ncase 1:\r\n```\r\n(0028, 1050) Window Center DS: \"128.0\"\r\n(0028, 1051) Window Width DS: \"256.0\"\r\n(0028, 1052) Rescale Intercept DS: None\r\n(0028, 1053) Rescale Slope DS: None\r\n```\r\nthrows an exception\r\n\r\n```\r\n File \"python3.7/site-packages/pydicom/pixel_data_handlers/util.py\", line 380, in apply_voi_lut\r\n y_min = y_min * ds.RescaleSlope + ds.RescaleIntercept\r\nTypeError: unsupported operand type(s) for *: 'int' and 'NoneType' \r\n```\r\n\r\n\r\ncase 2:\r\n\r\n```\r\n(0028, 1050) Window Center DS: \"2607.0\"\r\n(0028, 1051) Window Width DS: \"2785.0\"\r\n(0028, 1052) Rescale Intercept DS: \"0.0\"\r\n(0028, 1053) Rescale Slope DS: \"1.0\"\r\n(0028, 1054) Rescale Type LO: 'US'\r\n(0028, 2110) Lossy Image Compression CS: '00'\r\n(0028, 3010) VOI LUT Sequence 1 item(s) ---- \r\n (0028, 3002) LUT Descriptor SS: None\r\n (0028, 3003) LUT Explanation LO: 'Noramal'\r\n (0028, 3006) LUT Data OW: None\r\n```\r\n\r\nthrows an exception\r\n\r\n```\r\n File \"python3.7/site-packages/pydicom/pixel_data_handlers/util.py\", line 312, in apply_voi_lut\r\n nr_entries = item.LUTDescriptor[0] or 2**16\r\nTypeError: 'NoneType' object is not subscriptable\r\n```\r\n\r\n\r\nSo far I have handled this with:\r\n\r\n```\r\n def _lut_convert(self):\r\n return apply_voi_lut(self.input_dicom.pixel_array, self.input_dicom)\r\n\r\n def _get_raw_data(self):\r\n\r\n # convert to presentation LUT\r\n try:\r\n data = self._lut_convert()\r\n # many things can be corrupted in the VOILUTSequence attribute,\r\n # fall back to default WC/WW conversion\r\n except Exception as e:\r\n try:\r\n if \"VOILUTSequence\" in self.input_dicom:\r\n del self.input_dicom[\"VOILUTSequence\"]\r\n data = self._lut_convert()\r\n except Exception as e:\r\n raise InvalidImage(f\"Could not convert to presentation LUT due to: {e}\")\r\n```\r\n\r\nWhile the case 1 could be seen as an expected behavior (?), I imagine case 2 should be handled by WC/WW transformations if followed DICOM standard?\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\n", "hints_text": "For some reason when I wrote it, I assumed it was a case of either/or for *VOI LUT Sequence*/*Window Center*, but now that I look at the Standard again I see it possible that both can be present (although only one can be applied). I'll probably add a flag to allow selecting which one is used when both are present.\n> If both LUT and WL are supplied, by the dicom standard, which should be applied?\r\n\r\nThat should be up to the user\r\n\r\n> Separately to the above question about which is applied, if both LUT and WL sequences are supplied, is there a way in apply_voi_lut to specify applying one or the other? (ie force application of the WL instead of LUT etc)\r\n\r\nNot at the moment, although you could force which is applied by deleting the corresponding element(s) for the operation you don't want\r\n\r\n> Also, if an image has a sequence of WL values rather than being single valued (so 0028,1050 & 0028,1051 are sequences), does the index parameter to apply_voi_lut apply to specify which in the sequence you want to use?\r\n\r\nYes\nIs it possible that you could attach an anonymised dataset we could add to our test data? It'd be helpful to have a real dataset.\n", "created_at": "2020-10-26T20:49:06Z", "version": "2.0", "FAIL_TO_PASS": ["pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_pixel_representation_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_bits_allocated_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unsupported_dtypes", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-1-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-1-False-int8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-0-False-uint16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-1-False-int16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-False-uint32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-1-False-int32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-True-float32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[64-0-True-float64]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_uncompressed_syntaxes", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_nr_frames_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_samples_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_planar_conf_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_current_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_desired_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[RGB-RGB]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_single_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_no_endian_raises", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_slope_intercept", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lutdata_ow", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_neither_ds_nor_palette_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unknown_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unavailable_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_supplemental_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_lut_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unequal_lut_length_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_no_palette_color", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16_2frame", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_litle", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_big", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_16_allocated_8_entries", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_alpha", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_well_known_palette", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_positive", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_negative", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_discrete", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_linear", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_08", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_16", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_spring", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_summer", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_fall", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_winter", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_linear_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_indirect_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_unknown_opcode_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint32", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int32", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_rescale", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_modality_lut", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_photometric_interp", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_parameters", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_index", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_rescale_empty", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_int8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_int16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_bad_depth", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint16_array_float", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_lutdata_ow", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_only_windowing", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_only_voi", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_voi_windowing", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_voi_windowing_empty", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_precision", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_not_j2k", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_no_siz", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_short_bytestream", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_none", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_missing", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_existing"], "PASS_TO_PASS": [], "environment_setup_commit": "9d69811e539774f296c2f289839147e741251716"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-955", "base_commit": "fdd4fc8098920b1cda6127bdc05ff1e542b519fb", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -686,6 +686,13 @@ def __repr__(self):\n RawDataElement.is_raw = True\n \n \n+# The first and third values of the following elements are always US\n+# even if the VR is SS (PS3.3 C.7.6.3.1.5, C.11.1, C.11.2).\n+# (0028,1101-1103) RGB Palette Color LUT Descriptor\n+# (0028,3002) LUT Descriptor\n+_LUT_DESCRIPTOR_TAGS = (0x00281101, 0x00281102, 0x00281103, 0x00283002)\n+\n+\n def DataElement_from_raw(raw_data_element, encoding=None):\n \"\"\"Return a :class:`DataElement` created from `raw_data_element`.\n \n@@ -738,5 +745,10 @@ def DataElement_from_raw(raw_data_element, encoding=None):\n value = convert_value(VR, raw, encoding)\n except NotImplementedError as e:\n raise NotImplementedError(\"{0:s} in tag {1!r}\".format(str(e), raw.tag))\n+\n+ if raw.tag in _LUT_DESCRIPTOR_TAGS and value[0] < 0:\n+ # We only fix the first value as the third value is 8 or 16\n+ value[0] += 65536\n+\n return DataElement(raw.tag, VR, value, raw.value_tell,\n raw.length == 0xFFFFFFFF, already_converted=True)\ndiff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py\n--- a/pydicom/pixel_data_handlers/util.py\n+++ b/pydicom/pixel_data_handlers/util.py\n@@ -115,9 +115,6 @@ def apply_color_lut(arr, ds=None, palette=None):\n lut_desc = ds.RedPaletteColorLookupTableDescriptor\n # A value of 0 = 2^16 entries\n nr_entries = lut_desc[0] or 2**16\n- # Workaround for #942: first value is always unsigned\n- if nr_entries < 0:\n- nr_entries += 2**16\n \n # May be negative if Pixel Representation is 1\n first_map = lut_desc[1]\n@@ -217,9 +214,6 @@ def apply_modality_lut(arr, ds):\n if hasattr(ds, 'ModalityLUTSequence'):\n item = ds.ModalityLUTSequence[0]\n nr_entries = item.LUTDescriptor[0] or 2**16\n- # Workaround for #942: first value is always unsigned\n- if nr_entries < 0:\n- nr_entries += 2**16\n first_map = item.LUTDescriptor[1]\n nominal_depth = item.LUTDescriptor[2]\n \n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -7,6 +7,7 @@\n from io import BytesIO\n import os\n import shutil\n+from struct import unpack\n import sys\n import tempfile\n \n@@ -631,6 +632,27 @@ def test_dcmread_does_not_raise(self):\n except EOFError:\n self.fail('Unexpected EOFError raised')\n \n+ def test_lut_descriptor(self):\n+ \"\"\"Regression test for #942: incorrect first value\"\"\"\n+ prefixes = [\n+ b'\\x28\\x00\\x01\\x11',\n+ b'\\x28\\x00\\x02\\x11',\n+ b'\\x28\\x00\\x03\\x11',\n+ b'\\x28\\x00\\x02\\x30'\n+ ]\n+ suffix = b'\\x53\\x53\\x06\\x00\\x00\\xf5\\x00\\xf8\\x10\\x00'\n+\n+ for raw_tag in prefixes:\n+ tag = unpack('<2H', raw_tag)\n+ bs = DicomBytesIO(raw_tag + suffix)\n+ bs.is_little_endian = True\n+ bs.is_implicit_VR = False\n+\n+ ds = dcmread(bs, force=True)\n+ elem = ds[tag]\n+ assert elem.VR == 'SS'\n+ assert elem.value == [62720, -2048, 16]\n+\n \n class TestIncorrectVR(object):\n def setup(self):\ndiff --git a/pydicom/tests/test_handler_util.py b/pydicom/tests/test_handler_util.py\n--- a/pydicom/tests/test_handler_util.py\n+++ b/pydicom/tests/test_handler_util.py\n@@ -841,18 +841,6 @@ def test_lut_sequence_zero_entries(self):\n out = apply_modality_lut(arr, ds)\n assert [0, 0, 0, 1] == list(out)\n \n- def test_lut_sequence_entries_negative(self):\n- \"\"\"Test workaround for #942: SS VR should give uint nr entries.\"\"\"\n- ds = dcmread(MOD_16_SEQ)\n- seq = ds.ModalityLUTSequence[0]\n- seq.LUTDescriptor = [-32767, 0, 16] # 32769\n- seq.LUTData = [0] * 32768 + [1]\n- arr = np.asarray([-10, 0, 32767, 32768, 32769])\n- out = apply_modality_lut(arr, ds)\n- # IV < index 0 -> 0\n- # IV > index 32768 -> 32768\n- assert [0, 0, 0, 1, 1] == list(out)\n-\n def test_unchanged(self):\n \"\"\"Test no modality LUT transform.\"\"\"\n ds = dcmread(MOD_16)\n@@ -1154,26 +1142,6 @@ def test_first_map_negative(self):\n assert [60160, 25600, 37376] == list(rgb[arr == 130][0])\n assert ([60160, 25600, 37376] == rgb[arr == 130]).all()\n \n- def test_nr_entries_negative(self):\n- \"\"\"Test workaround for #942: SS VR should give uint nr entries.\"\"\"\n- ds = dcmread(PAL_08_200_0_16_1F, force=True)\n- ds.file_meta = Dataset()\n- ds.file_meta.TransferSyntaxUID = ImplicitVRLittleEndian\n- ds.RedPaletteColorLookupTableDescriptor[0] = -32767 # 32769\n- # 16-bit entries, 32769 entries per LUT\n- ds.RedPaletteColorLookupTableData = b'\\x00\\x00' * 32768 + b'\\xff\\xff'\n- ds.GreenPaletteColorLookupTableData = b'\\x00\\x00' * 32768 + b'\\xff\\xff'\n- ds.BluePaletteColorLookupTableData = b'\\x00\\x00' * 32768 + b'\\xff\\xff'\n- # IV < index 0 -> 0\n- # IV > index 32768 -> 32768\n- arr = np.asarray([-10, 0, 32767, 32768, 32769])\n- rgb = apply_color_lut(arr, ds)\n- assert [0, 0, 0] == list(rgb[0])\n- assert [0, 0, 0] == list(rgb[1])\n- assert [0, 0, 0] == list(rgb[2])\n- assert [65535, 65535, 65535] == list(rgb[3])\n- assert [65535, 65535, 65535] == list(rgb[4])\n-\n \n @pytest.mark.skipif(not HAVE_NP, reason=\"Numpy is not available\")\n class TestNumpy_ExpandSegmentedLUT(object):\n", "problem_statement": "LUT Descriptor values don't follow standard\n**Describe the bug**\r\n(0028,3002) [LUT Descriptor](http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.11.html#sect_C.11.1.1) has VM = 3, with value as `[number of entries in LUT, first stored pixel value mapped, LUT entry bit depth]`. The VR for the element is ambiguous and may be US or SS depending on the value of (0028,0103) Pixel Representation, however this only affects the second value, not the first or last which are always US.\r\n\r\nThe problem is that a Pixel Representation value of 1 (i.e. 2s complement) gives a LUT Descriptor value 1 as signed when it should always be unsigned.\r\n\r\n> Since LUT Descriptor (0028,3002) is multi-valued, in an Explicit VR Transfer Syntax, only one value representation (US or SS) may be specified, even though the first and third values are always by definition interpreted as unsigned. The explicit VR actually used is dictated by the VR needed to represent the second value, which will be consistent with Pixel Representation (0028,0103).\r\n\r\nAlso affects Red/Green/Blue Palette Color Lookup Table Descriptor.\r\n\r\n**Steps To Reproduce**\r\n```python\r\nfrom pydicom import dcmread\r\nfrom pydicom.filebase import DicomBytesIO\r\n\r\n# Explicit VR: SS\r\nlut = b'\\x28\\x00\\x02\\x30\\x53\\x53\\x06\\x00\\x00\\xf5\\x00\\xf8\\x10\\x00'\r\n\r\nbs = DicomBytesIO(lut)\r\nbs.is_little_endian = True\r\nbs.is_implicit_VR = False\r\n\r\nds = dcmread(bs, force=True)\r\nassert ds.LUTDescriptor == [62720, -2048, 16]\r\n```\r\n\r\n**Your environment**\r\nAffects current `master`\r\n\n", "hints_text": "", "created_at": "2019-09-28T01:51:58Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_lut_descriptor"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_empty_numbers_tag", "pydicom/tests/test_filereader.py::TestReader::test_UTF8_filename", "pydicom/tests/test_filereader.py::TestReader::test_RTPlan", "pydicom/tests/test_filereader.py::TestReader::test_RTDose", "pydicom/tests/test_filereader.py::TestReader::test_CT", "pydicom/tests/test_filereader.py::TestReader::test_CT_PixelData", "pydicom/tests/test_filereader.py::TestReader::test_no_force", "pydicom/tests/test_filereader.py::TestReader::test_RTStruct", "pydicom/tests/test_filereader.py::TestReader::test_dir", "pydicom/tests/test_filereader.py::TestReader::test_MR", "pydicom/tests/test_filereader.py::TestReader::test_deflate", "pydicom/tests/test_filereader.py::TestReader::test_no_pixels_read", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_SQ", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_tag", "pydicom/tests/test_filereader.py::TestReader::test_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_nested_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_no_meta_group_length", "pydicom/tests/test_filereader.py::TestReader::test_no_transfer_syntax_in_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_little_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_big_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_planar_config", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::TestReader::test_long_specific_char_set", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::TestReader::test_group_length_wrong", "pydicom/tests/test_filereader.py::TestReader::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_empty_file", "pydicom/tests/test_filereader.py::TestReader::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used_strict", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_AE", "pydicom/tests/test_filereader.py::TestDeferredRead::test_time_check", "pydicom/tests/test_filereader.py::TestDeferredRead::test_file_exists", "pydicom/tests/test_filereader.py::TestDeferredRead::test_values_identical", "pydicom/tests/test_filereader.py::TestDeferredRead::test_zipped_deferred", "pydicom/tests/test_filereader.py::TestDeferredRead::test_filelike_deferred", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelDataArray", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_object", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_like_object", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_pixel_representation_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_bits_allocated_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unsupported_dtypes", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-0-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-1-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-0-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-1-int8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-0-uint16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-1-int16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-uint32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-1-int32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_uncompressed_syntaxes", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_nr_frames_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_samples_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_planar_conf_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_current_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_desired_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[RGB-RGB]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_single_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_no_endian_raises", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_slope_intercept", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_neither_ds_nor_palette_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unknown_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unavailable_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_supplemental_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_lut_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unequal_lut_length_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_no_palette_color", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16_2frame", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_litle", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_big", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_16_allocated_8_entries", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_alpha", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_well_known_palette", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_positive", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_negative", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_discrete", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_linear", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_08", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_16", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_spring", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_summer", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_fall", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_winter", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_linear_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_indirect_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_unknown_opcode_raises"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1031", "base_commit": "64f5b8daaa798836579c56912244b7732ab073be", "patch": "diff --git a/pydicom/dataelem.py b/pydicom/dataelem.py\n--- a/pydicom/dataelem.py\n+++ b/pydicom/dataelem.py\n@@ -76,7 +76,7 @@ def empty_value_for_VR(VR, raw=False):\n if it is empty.\n \"\"\"\n if VR == 'SQ':\n- return []\n+ return b'' if raw else []\n if config.use_none_as_empty_text_VR_value:\n return None\n if VR in ('AE', 'AS', 'CS', 'DA', 'DT', 'LO', 'LT',\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -15,11 +15,11 @@\n \n from pydicom._storage_sopclass_uids import CTImageStorage\n from pydicom import config, __version_info__, uid\n-from pydicom.data import get_testdata_files, get_charset_files\n+from pydicom.data import get_testdata_file, get_charset_files\n from pydicom.dataset import Dataset, FileDataset\n from pydicom.dataelem import DataElement, RawDataElement\n from pydicom.filebase import DicomBytesIO\n-from pydicom.filereader import dcmread, read_dataset\n+from pydicom.filereader import dcmread, read_dataset, read_file\n from pydicom.filewriter import (write_data_element, write_dataset,\n correct_ambiguous_vr, write_file_meta_info,\n correct_ambiguous_vr_element, write_numbers,\n@@ -34,16 +34,16 @@\n from pydicom.values import convert_text\n from ._write_stds import impl_LE_deflen_std_hex\n \n-rtplan_name = get_testdata_files(\"rtplan.dcm\")[0]\n-rtdose_name = get_testdata_files(\"rtdose.dcm\")[0]\n-ct_name = get_testdata_files(\"CT_small.dcm\")[0]\n-mr_name = get_testdata_files(\"MR_small.dcm\")[0]\n-mr_implicit_name = get_testdata_files(\"MR_small_implicit.dcm\")[0]\n-mr_bigendian_name = get_testdata_files(\"MR_small_bigendian.dcm\")[0]\n-jpeg_name = get_testdata_files(\"JPEG2000.dcm\")[0]\n-no_ts = get_testdata_files(\"meta_missing_tsyntax.dcm\")[0]\n-color_pl_name = get_testdata_files(\"color-pl.dcm\")[0]\n-sc_rgb_name = get_testdata_files(\"SC_rgb.dcm\")[0]\n+rtplan_name = get_testdata_file(\"rtplan.dcm\")\n+rtdose_name = get_testdata_file(\"rtdose.dcm\")\n+ct_name = get_testdata_file(\"CT_small.dcm\")\n+mr_name = get_testdata_file(\"MR_small.dcm\")\n+mr_implicit_name = get_testdata_file(\"MR_small_implicit.dcm\")\n+mr_bigendian_name = get_testdata_file(\"MR_small_bigendian.dcm\")\n+jpeg_name = get_testdata_file(\"JPEG2000.dcm\")\n+no_ts = get_testdata_file(\"meta_missing_tsyntax.dcm\")\n+color_pl_name = get_testdata_file(\"color-pl.dcm\")\n+sc_rgb_name = get_testdata_file(\"SC_rgb.dcm\")\n datetime_name = mr_name\n \n unicode_name = get_charset_files(\"chrH31.dcm\")[0]\n@@ -204,6 +204,15 @@ def test_write_removes_grouplength(self):\n # group length has been removed\n assert 0x00080000 not in ds\n \n+ def test_write_empty_sequence(self):\n+ \"\"\"Make sure that empty sequence is correctly written.\"\"\"\n+ # regression test for #1030\n+ ds = read_file(get_testdata_file('test-SR.dcm'))\n+ ds.save_as(self.file_out)\n+ self.file_out.seek(0)\n+ ds = read_file(self.file_out)\n+ assert ds.PerformedProcedureCodeSequence == []\n+\n \n class TestScratchWriteDateTime(TestWriteFile):\n \"\"\"Write and reread simple or multi-value DA/DT/TM data elements\"\"\"\n", "problem_statement": "Crash writing DICOM with 1.4.0\npydicom 1.4.0\r\nWindows-10-10.0.18362-SP0\r\nPython 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)]\r\nGDCM 3.0.2\r\nPillow 7.0.0\r\n\r\nType error raises when writing file with pydicom 1.4.0, works in 1.3.0.\r\n\r\n```\r\nds = pydicom.read_file('fail2404.anon.dcm')\r\n#print(ds.get((0x0040, 0x0275)))\r\nds.save_as('bort.dcm')\r\n```\r\n\r\nInterestingly, the crash goes away if the offending tag is accessed (uncomment the print and then the `save_as` works fine).\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\tag.py\", line 30, in tag_in_exception\r\n yield\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\filewriter.py\", line 555, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\filewriter.py\", line 463, in write_data_element\r\n buffer.write(data_element.value)\r\nTypeError: a bytes-like object is required, not 'list'\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"./pydcmbug.py\", line 7, in <module>\r\n ds.save_as('bort.dcm')\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\dataset.py\", line 1810, in save_as\r\n pydicom.dcmwrite(filename, self, write_like_original)\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\filewriter.py\", line 946, in dcmwrite\r\n write_dataset(fp, get_item(dataset, slice(0x00010000, None)))\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\filewriter.py\", line 555, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \"C:\\Program Files\\Python37\\lib\\contextlib.py\", line 130, in __exit__\r\n self.gen.throw(type, value, traceback)\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\tag.py\", line 37, in tag_in_exception\r\n raise type(ex)(msg)\r\nTypeError: With tag (0040, 0275) got exception: a bytes-like object is required, not 'list'\r\nTraceback (most recent call last):\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\tag.py\", line 30, in tag_in_exception\r\n yield\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\filewriter.py\", line 555, in write_dataset\r\n write_data_element(fp, dataset.get_item(tag), dataset_encoding)\r\n File \"C:\\Program Files\\Python37\\lib\\site-packages\\pydicom\\filewriter.py\", line 463, in write_data_element\r\n buffer.write(data_element.value)\r\nTypeError: a bytes-like object is required, not 'list'\r\n```\r\n\r\n[fail.zip](https://github.com/pydicom/pydicom/files/4072693/fail.zip)\r\n\n", "hints_text": "Ok, found the problem. This has been introduced by by PR #965 (by myself). Will provide a fix ASAP...\r\n", "created_at": "2020-01-16T18:53:50Z", "version": "1.4", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::test_write_empty_sequence", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_empty_sequence"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testListItemWriteBack", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_attribute", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit_using_index", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestScratchWrite::testImpl_LE_deflen_write", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "5098c9147fadcb3e5918487036867931435adeb8"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1555", "base_commit": "9db89e1d8f5e82dc617f9c8cbf303fe23a0632b9", "patch": "diff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -1488,7 +1488,7 @@ def _convert_pixel_data_without_handler(self) -> None:\n possible_handlers = [\n hh for hh in pydicom.config.pixel_data_handlers\n if hh is not None\n- and hh.supports_transfer_syntax(ts) # type: ignore[attr-defined]\n+ and hh.supports_transfer_syntax(ts)\n ]\n \n # No handlers support the transfer syntax\n@@ -1504,7 +1504,7 @@ def _convert_pixel_data_without_handler(self) -> None:\n # dependencies met\n available_handlers = [\n hh for hh in possible_handlers\n- if hh.is_available() # type: ignore[attr-defined]\n+ if hh.is_available()\n ]\n \n # There are handlers that support the transfer syntax but none of them\n@@ -1518,13 +1518,13 @@ def _convert_pixel_data_without_handler(self) -> None:\n )\n pkg_msg = []\n for hh in possible_handlers:\n- hh_deps = hh.DEPENDENCIES # type: ignore[attr-defined]\n+ hh_deps = hh.DEPENDENCIES\n # Missing packages\n missing = [dd for dd in hh_deps if have_package(dd) is None]\n # Package names\n names = [hh_deps[name][1] for name in missing]\n pkg_msg.append(\n- f\"{hh.HANDLER_NAME} \" # type: ignore[attr-defined]\n+ f\"{hh.HANDLER_NAME} \"\n f\"(req. {', '.join(names)})\"\n )\n \n@@ -1819,7 +1819,7 @@ def overlay_array(self, group: int) -> \"numpy.ndarray\":\n \n available_handlers = [\n hh for hh in overlay_data_handlers\n- if hh.is_available() # type: ignore[attr-defined]\n+ if hh.is_available()\n ]\n if not available_handlers:\n # For each of the handlers we want to find which\n@@ -1830,13 +1830,13 @@ def overlay_array(self, group: int) -> \"numpy.ndarray\":\n )\n pkg_msg = []\n for hh in overlay_data_handlers:\n- hh_deps = hh.DEPENDENCIES # type: ignore[attr-defined]\n+ hh_deps = hh.DEPENDENCIES\n # Missing packages\n missing = [dd for dd in hh_deps if have_package(dd) is None]\n # Package names\n names = [hh_deps[name][1] for name in missing]\n pkg_msg.append(\n- f\"{hh.HANDLER_NAME} \" # type: ignore[attr-defined]\n+ f\"{hh.HANDLER_NAME} \"\n f\"(req. {', '.join(names)})\"\n )\n \n@@ -1846,7 +1846,7 @@ def overlay_array(self, group: int) -> \"numpy.ndarray\":\n for handler in available_handlers:\n try:\n # Use the handler to get an ndarray of the pixel data\n- func = handler.get_overlay_array # type: ignore[attr-defined]\n+ func = handler.get_overlay_array\n return cast(\"numpy.ndarray\", func(self, group))\n except Exception as exc:\n logger.debug(\ndiff --git a/pydicom/encoders/base.py b/pydicom/encoders/base.py\n--- a/pydicom/encoders/base.py\n+++ b/pydicom/encoders/base.py\n@@ -84,11 +84,11 @@ def add_plugin(self, label: str, import_path: Tuple[str, str]) -> None:\n module = import_module(import_path[0])\n \n # `is_available(UID)` is required for plugins\n- if module.is_available(self.UID): # type: ignore[attr-defined]\n+ if module.is_available(self.UID):\n self._available[label] = getattr(module, import_path[1])\n else:\n # `ENCODER_DEPENDENCIES[UID]` is required for plugins\n- deps = module.ENCODER_DEPENDENCIES # type: ignore[attr-defined]\n+ deps = module.ENCODER_DEPENDENCIES\n self._unavailable[label] = deps[self.UID]\n \n @staticmethod\ndiff --git a/pydicom/filebase.py b/pydicom/filebase.py\n--- a/pydicom/filebase.py\n+++ b/pydicom/filebase.py\n@@ -182,15 +182,15 @@ def __init__(\n self.close = file_like_obj.close\n self.name: str = getattr(file_like_obj, 'name', '<no filename>')\n \n- def no_write(self, bytes_read: bytes) -> None:\n+ def no_write(self, bytes_read: bytes) -> int:\n \"\"\"Used for file-like objects where no write is available\"\"\"\n raise IOError(\"This DicomFileLike object has no write() method\")\n \n- def no_read(self, bytes_read: Optional[int] = None) -> None:\n+ def no_read(self, size: int = -1) -> bytes:\n \"\"\"Used for file-like objects where no read is available\"\"\"\n raise IOError(\"This DicomFileLike object has no read() method\")\n \n- def no_seek(self, offset: int, from_what: int = 0) -> None:\n+ def no_seek(self, offset: int, whence: int = 0) -> int:\n \"\"\"Used for file-like objects where no seek is available\"\"\"\n raise IOError(\"This DicomFileLike object has no seek() method\")\n \ndiff --git a/pydicom/fileset.py b/pydicom/fileset.py\n--- a/pydicom/fileset.py\n+++ b/pydicom/fileset.py\n@@ -2865,10 +2865,10 @@ def my_recorder(ds: Dataset) -> Dataset:\n \n def _single_level_record_type(ds: Dataset) -> str:\n \"\"\"Return a single-level *Directory Record Type* for `ds`.\"\"\"\n- sop_class = getattr(ds, \"SOPClassUID\", None)\n+ sop_class = cast(Optional[UID], getattr(ds, \"SOPClassUID\", None))\n \n try:\n- return _SINGLE_LEVEL_SOP_CLASSES[sop_class]\n+ return _SINGLE_LEVEL_SOP_CLASSES[sop_class] # type: ignore[index]\n except KeyError:\n return \"PATIENT\"\n \n@@ -2888,9 +2888,9 @@ def _four_level_record_type(ds: Dataset) -> str:\n if \"RTPlanLabel\" in ds:\n return \"RT PLAN\"\n \n- sop_class = getattr(ds, \"SOPClassUID\", None)\n+ sop_class = cast(Optional[UID], getattr(ds, \"SOPClassUID\", None))\n \n try:\n- return _FOUR_LEVEL_SOP_CLASSES[sop_class]\n+ return _FOUR_LEVEL_SOP_CLASSES[sop_class] # type: ignore[index]\n except KeyError:\n return \"IMAGE\"\ndiff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -1000,6 +1000,7 @@ def dcmwrite(\n Write a DICOM file from a dataset that was read in with ``dcmread()``.\n ``save_as()`` wraps ``dcmwrite()``.\n \"\"\"\n+ tsyntax: Optional[UID]\n \n # Ensure is_little_endian and is_implicit_VR are set\n if None in (dataset.is_little_endian, dataset.is_implicit_VR):\n@@ -1090,7 +1091,7 @@ def dcmwrite(\n fp.write(preamble)\n fp.write(b'DICM')\n \n- tsyntax: Optional[UID] = None # type: ignore[no-redef]\n+ tsyntax = None\n if dataset.file_meta: # May be an empty Dataset\n # If we want to `write_like_original`, don't enforce_standard\n write_file_meta_info(\ndiff --git a/pydicom/pixel_data_handlers/util.py b/pydicom/pixel_data_handlers/util.py\n--- a/pydicom/pixel_data_handlers/util.py\n+++ b/pydicom/pixel_data_handlers/util.py\n@@ -244,7 +244,7 @@ def apply_modality_lut(arr: \"np.ndarray\", ds: \"Dataset\") -> \"np.ndarray\":\n * DICOM Standard, Part 4, :dcm:`Annex N.2.1.1\n <part04/sect_N.2.html#sect_N.2.1.1>`\n \"\"\"\n- if 'ModalityLUTSequence' in ds:\n+ if ds.get(\"ModalityLUTSequence\"):\n item = cast(List[\"Dataset\"], ds.ModalityLUTSequence)[0]\n nr_entries = cast(List[int], item.LUTDescriptor)[0] or 2**16\n first_map = cast(List[int], item.LUTDescriptor)[1]\n@@ -342,7 +342,7 @@ def apply_voi_lut(\n <part04/sect_N.2.html#sect_N.2.1.1>`\n \"\"\"\n valid_voi = False\n- if 'VOILUTSequence' in ds:\n+ if ds.get('VOILUTSequence'):\n ds.VOILUTSequence = cast(List[\"Dataset\"], ds.VOILUTSequence)\n valid_voi = None not in [\n ds.VOILUTSequence[0].get('LUTDescriptor', None),\n@@ -408,7 +408,7 @@ def apply_voi(\n * DICOM Standard, Part 4, :dcm:`Annex N.2.1.1\n <part04/sect_N.2.html#sect_N.2.1.1>`\n \"\"\"\n- if \"VOILUTSequence\" not in ds:\n+ if not ds.get('VOILUTSequence'):\n return arr\n \n if not np.issubdtype(arr.dtype, np.integer):\n@@ -529,7 +529,7 @@ def apply_windowing(\n ds.BitsStored = cast(int, ds.BitsStored)\n y_min: float\n y_max: float\n- if 'ModalityLUTSequence' in ds:\n+ if ds.get('ModalityLUTSequence'):\n # Unsigned - see PS3.3 C.11.1.1.1\n y_min = 0\n item = cast(List[\"Dataset\"], ds.ModalityLUTSequence)[0]\ndiff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -55,7 +55,10 @@ def __getstate__(self) -> Dict[str, Any]:\n def __setstate__(self, state: Dict[str, Any]) -> None:\n self.__dict__.update(state)\n \n- def __reduce_ex__(self, protocol: int) -> Tuple[Any, ...]:\n+ def __reduce_ex__( # type: ignore[override]\n+ self, protocol: int\n+ ) -> Tuple[Any, ...]:\n+ # Python 3.8 - protocol: SupportsIndex (added in 3.8)\n # datetime.time, and datetime.datetime return Tuple[Any, ...]\n # datetime.date doesn't define __reduce_ex__\n reduce_ex = cast(Tuple[Any, ...], super().__reduce_ex__(protocol))\n@@ -324,17 +327,17 @@ def __new__( # type: ignore[misc]\n if match.group('ms'):\n microsecond = int(match.group('ms').rstrip().ljust(6, '0'))\n \n- return super().__new__( # type: ignore[call-arg, no-any-return]\n+ return super().__new__(\n cls, hour, minute, second, microsecond\n )\n \n if isinstance(val, datetime.time):\n- return super().__new__( # type: ignore[call-arg, no-any-return]\n+ return super().__new__(\n cls, val.hour, val.minute, val.second, val.microsecond\n )\n \n try:\n- return super().__new__( # type: ignore[call-arg, no-any-return]\n+ return super().__new__(\n cls, *args, **kwargs\n )\n except Exception as exc:\n@@ -925,7 +928,7 @@ def __new__( # type: ignore[misc]\n if len(args) and args[0] is None:\n return None\n \n- return cast(\"PersonName\", super().__new__(cls))\n+ return super().__new__(cls)\n \n def __init__(\n self,\n", "test_patch": "diff --git a/pydicom/tests/test_handler_util.py b/pydicom/tests/test_handler_util.py\n--- a/pydicom/tests/test_handler_util.py\n+++ b/pydicom/tests/test_handler_util.py\n@@ -890,6 +890,10 @@ def test_unchanged(self):\n out = apply_modality_lut(arr, ds)\n assert arr is out\n \n+ ds.ModalityLUTSequence = []\n+ out = apply_modality_lut(arr, ds)\n+ assert arr is out\n+\n def test_lutdata_ow(self):\n \"\"\"Test LUT Data with VR OW.\"\"\"\n ds = dcmread(MOD_16_SEQ)\n@@ -1839,6 +1843,10 @@ def test_unchanged(self):\n out = apply_windowing(arr, ds)\n assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n \n+ ds.ModalityLUTSequence = []\n+ out = apply_windowing(arr, ds)\n+ assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n+\n def test_rescale_empty(self):\n \"\"\"Test RescaleSlope and RescaleIntercept being empty.\"\"\"\n ds = dcmread(WIN_12_1F)\n@@ -2051,6 +2059,11 @@ def test_unchanged(self):\n out = apply_voi(arr, ds)\n assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n \n+ ds.VOILUTSequence = []\n+ out = apply_voi(arr, ds)\n+ assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n+\n+\n def test_voi_lutdata_ow(self):\n \"\"\"Test LUT Data with VR OW.\"\"\"\n ds = Dataset()\n@@ -2072,6 +2085,7 @@ def test_voi_lutdata_ow(self):\n \n @pytest.mark.skipif(not HAVE_NP, reason=\"Numpy is not available\")\n class TestNumpy_ApplyVOILUT:\n+ \"\"\"Tests for util.apply_voi_lut()\"\"\"\n def test_unchanged(self):\n \"\"\"Test input array is unchanged if no VOI LUT\"\"\"\n ds = Dataset()\n@@ -2082,6 +2096,10 @@ def test_unchanged(self):\n out = apply_voi_lut(arr, ds)\n assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n \n+ ds.VOILUTSequence = []\n+ out = apply_voi_lut(arr, ds)\n+ assert [-128, -127, -1, 0, 1, 126, 127] == out.tolist()\n+\n def test_only_windowing(self):\n \"\"\"Test only windowing operation elements present.\"\"\"\n ds = Dataset()\n", "problem_statement": "Converting Dicom image to Png\n**Describe the issue**\r\nhi, i am trying to convert Dicom image to png but in case of some particular file i am getting this \"list out of range error\".\r\n\r\n**Expected behavior**\r\ndicom image converted to png pne\r\n\r\n**Steps To Reproduce**\r\nHow to reproduce the issue. Please include:\r\n1. A minimum working code sample\r\n```\r\nfrom pydicom import dcmread\r\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\r\n dicom = dcmread(path, force=True)\r\n \r\n # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \"human-friendly\" view\r\n if voi_lut:\r\n data = apply_voi_lut(dicom.pixel_array, dicom)\r\n else:\r\n data = dicom.pixel_array\r\n \r\n # depending on this value, X-ray may look inverted - fix that:\r\n if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\r\n data = np.amax(data) - data\r\n \r\n data = data - np.min(data)\r\n data = data / np.max(data)\r\n data = (data * 255).astype(np.uint8)\r\n \r\n return data\r\n\r\nimg = read_xray('/content/a.5545da1153f57ff8425be6f4bc712c090e7e22efff194da525210c84aba2a947.dcm')\r\nplt.figure(figsize = (12,12))\r\nplt.imshow(img)\r\n```\r\n2. The traceback (if one occurred)\r\n```\r\nIndexError Traceback (most recent call last)\r\n<ipython-input-13-6e53d7d16b90> in <module>()\r\n 19 return data\r\n 20 \r\n---> 21 img = read_xray('/content/a.5545da1153f57ff8425be6f4bc712c090e7e22efff194da525210c84aba2a947.dcm')\r\n 22 plt.figure(figsize = (12,12))\r\n 23 plt.imshow(img)\r\n\r\n2 frames\r\n/usr/local/lib/python3.7/dist-packages/pydicom/multival.py in __getitem__(self, index)\r\n 93 self, index: Union[slice, int]\r\n 94 ) -> Union[MutableSequence[_ItemType], _ItemType]:\r\n---> 95 return self._list[index]\r\n 96 \r\n 97 def insert(self, position: int, val: _T) -> None:\r\n\r\nIndexError: list index out of range\r\n```\r\n\r\n3. Which of the following packages are available and their versions:\r\n * Numpy : latest as of 29th dec\r\n * Pillow : latest as of 29th dec\r\n * JPEG-LS : latest as of 29th dec\r\n * GDCM : latest as of 29th dec\r\n4. The anonymized DICOM dataset (if possible).\r\nimage link : https://drive.google.com/file/d/1j13XTTPCLX-8e7FE--1n5Staxz7GGNWm/view?usp=sharing\r\n\r\n**Your environment**\r\nIf you're using **pydicom 2 or later**, please use the `pydicom.env_info`\r\nmodule to gather information about your environment and paste it in the issue:\r\n\r\n```bash\r\n$ python -m pydicom.env_info\r\n```\r\n\r\nFor **pydicom 1.x**, please run the following code snippet and paste the\r\noutput.\r\n\r\n```python\r\nimport platform, sys, pydicom\r\nprint(platform.platform(),\r\n \"\\nPython\", sys.version,\r\n \"\\npydicom\", pydicom.__version__)\r\n```\r\n\n", "hints_text": "```\r\nTraceback (most recent call last):\r\n File \"pyd1554.py\", line 29, in <module>\r\n img = read_xray('datasets/pyd1554.dcm')\r\n File \"...pyd1554.py\", line 14, in read_xray\r\n data = apply_voi_lut(dicom.pixel_array, dicom)\r\n File \".../pydicom/pixel_data_handlers/util.py\", line 348, in apply_voi_lut\r\n ds.VOILUTSequence[0].get('LUTDescriptor', None),\r\n File \".../pydicom/multival.py\", line 95, in __getitem__\r\n return self._list[index]\r\nIndexError: list index out of range\r\n```\r\nThe *VOI LUT Sequence* is empty, which is probably non-conformant but I can't actually tell what the *SOP Class UID* is (your anonymiser is weird, but probably mammo).\r\n\r\nHere's the whole (also weird) *VOI LUT Sequence* (in hex):\r\n```\r\n Tag | SQ | | Length | Seq end delimiter |\r\n28 00 10 30 53 51 00 00 FF FF FF FF FE FF DD E0 00 00 00 00\r\n```\r\n\r\nI might add a check for an empty sequence in `apply_voi_lut` (and the other visualisation functions).\r\n", "created_at": "2021-12-29T08:49:15Z", "version": "2.2", "FAIL_TO_PASS": ["pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_unchanged"], "PASS_TO_PASS": ["pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_pixel_representation_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unknown_bits_allocated_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_unsupported_dtypes", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[1-1-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-0-False-uint8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[8-1-False-int8]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-0-False-uint16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[16-1-False-int16]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-False-uint32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-1-False-int32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[32-0-True-float32]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_supported_dtypes[64-0-True-float64]", "pydicom/tests/test_handler_util.py::TestNumpy_PixelDtype::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_1frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_reference_2frame_3sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_1frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_1sample", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_2frame_3sample_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_0conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_compressed_syntaxes_1conf", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_uncompressed_syntaxes", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_nr_frames_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_samples_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ReshapePixelArray::test_invalid_planar_conf_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_current_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_unknown_desired_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[RGB-RGB]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL_422]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_current_is_desired[YBR_FULL_422-YBR_FULL]", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_single_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_rgb_ybr_rgb_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ConvertColourSpace::test_frame_by_frame", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_byte_swapping", "pydicom/tests/test_handler_util.py::TestNumpy_DtypeCorrectedForEndianness::test_no_endian_raises", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_bytes[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_in_pixels[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape0-1-length0]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape1-1-length1]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape2-1-length2]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape3-1-length3]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape4-1-length4]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape5-1-length5]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape6-1-length6]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape7-1-length7]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape8-1-length8]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape9-8-length9]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape10-8-length10]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape11-8-length11]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape12-8-length12]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape13-8-length13]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape14-8-length14]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape15-16-length15]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape16-16-length16]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape17-16-length17]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape18-16-length18]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape19-16-length19]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape20-32-length20]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape21-32-length21]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape22-32-length22]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape23-32-length23]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape24-32-length24]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape25-1-length25]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape26-1-length26]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape27-1-length27]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape28-1-length28]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape29-1-length29]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape30-1-length30]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape31-1-length31]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape32-1-length32]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape33-1-length33]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape34-8-length34]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape35-8-length35]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape36-8-length36]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape37-8-length37]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape38-8-length38]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape39-8-length39]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape40-16-length40]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape41-16-length41]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape42-16-length42]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape43-32-length43]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape44-32-length44]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape45-32-length45]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape46-1-length46]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape47-1-length47]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape48-1-length48]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape49-1-length49]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape50-1-length50]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape51-1-length51]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape52-1-length52]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape53-1-length53]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape54-1-length54]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape55-8-length55]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape56-8-length56]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape57-8-length57]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape58-16-length58]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape59-16-length59]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape60-16-length60]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape61-32-length61]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape62-32-length62]", "pydicom/tests/test_handler_util.py::TestGetExpectedLength::test_length_ybr_422[shape63-32-length63]", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_slope_intercept", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lut_sequence_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ModalityLUT::test_lutdata_ow", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_neither_ds_nor_palette_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unknown_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_palette_unavailable_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_supplemental_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_invalid_lut_bit_depth_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unequal_lut_length_raises", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_no_palette_color", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint08_16_2frame", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_litle", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_uint16_16_segmented_big", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_16_allocated_8_entries", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_alpha", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_well_known_palette", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_positive", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_first_map_negative", "pydicom/tests/test_handler_util.py::TestNumpy_PaletteColor::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_discrete", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_linear", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_08", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_indirect_16", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_spring", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_summer", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_fall", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_palettes_winter", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_linear_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_first_indirect_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ExpandSegmentedLUT::test_unknown_opcode_raises", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_uint32", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_int32", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_rescale", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_modality_lut", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_photometric_interp", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_parameters", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_window_bad_index", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_unchanged", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyWindowing::test_rescale_empty", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_single_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_multi_view", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_multi_frame", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_zero_entries", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_int8", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_int16", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_bad_depth", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_uint16_array_float", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOI::test_voi_lutdata_ow", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_only_windowing", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_only_voi", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_voi_windowing", "pydicom/tests/test_handler_util.py::TestNumpy_ApplyVOILUT::test_voi_windowing_empty", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_precision", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_not_j2k", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_no_siz", "pydicom/tests/test_handler_util.py::TestGetJ2KParameters::test_short_bytestream", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_none", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_missing", "pydicom/tests/test_handler_util.py::TestGetNrFrames::test_existing"], "environment_setup_commit": "0fa18d2a2179c92efc22200ed6b3689e66cecf92"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-809", "base_commit": "356a51ab4bc54fd18950041ebc44dbfa1a425a10", "patch": "diff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -197,6 +197,9 @@ def __init__(self, *args, **kwargs):\n self.is_little_endian = None\n self.is_implicit_VR = None\n \n+ # the parent data set, if this dataset is a sequence item\n+ self.parent = None\n+\n def __enter__(self):\n \"\"\"Method invoked on entry to a with statement.\"\"\"\n return self\n@@ -555,7 +558,13 @@ def __getattr__(self, name):\n # Try the base class attribute getter (fix for issue 332)\n return super(Dataset, self).__getattribute__(name)\n else:\n- return self[tag].value\n+ data_elem = self[tag]\n+ value = data_elem.value\n+ if data_elem.VR == 'SQ':\n+ # let a sequence know its parent dataset, as sequence items\n+ # may need parent dataset tags to resolve ambiguous tags\n+ value.parent = self\n+ return value\n \n @property\n def _character_set(self):\n@@ -1165,6 +1174,11 @@ def __setattr__(self, name, value):\n # don't have this tag yet->create the data_element instance\n VR = dictionary_VR(tag)\n data_element = DataElement(tag, VR, value)\n+ if VR == 'SQ':\n+ # let a sequence know its parent dataset to pass it\n+ # to its items, who may need parent dataset tags\n+ # to resolve ambiguous tags\n+ data_element.parent = self\n else:\n # already have this data_element, just changing its value\n data_element = self[tag]\ndiff --git a/pydicom/filewriter.py b/pydicom/filewriter.py\n--- a/pydicom/filewriter.py\n+++ b/pydicom/filewriter.py\n@@ -69,6 +69,9 @@ def _correct_ambiguous_vr_element(elem, ds, is_little_endian):\n # US if PixelRepresentation value is 0x0000, else SS\n # For references, see the list at\n # https://github.com/darcymason/pydicom/pull/298\n+ # PixelRepresentation is usually set in the root dataset\n+ while 'PixelRepresentation' not in ds and ds.parent:\n+ ds = ds.parent\n if ds.PixelRepresentation == 0:\n elem.VR = 'US'\n byte_type = 'H'\ndiff --git a/pydicom/sequence.py b/pydicom/sequence.py\n--- a/pydicom/sequence.py\n+++ b/pydicom/sequence.py\n@@ -43,6 +43,9 @@ def __init__(self, iterable=None):\n if isinstance(iterable, Dataset):\n raise TypeError('The Sequence constructor requires an iterable')\n \n+ # the parent dataset\n+ self._parent = None\n+\n # If no inputs are provided, we create an empty Sequence\n if not iterable:\n iterable = list()\n@@ -50,6 +53,24 @@ def __init__(self, iterable=None):\n # validate_dataset is used as a pseudo type_constructor\n super(Sequence, self).__init__(validate_dataset, iterable)\n \n+ @property\n+ def parent(self):\n+ \"\"\"Return the parent dataset.\"\"\"\n+ return self._parent\n+\n+ @parent.setter\n+ def parent(self, value):\n+ \"\"\"Set the parent dataset and pass it to all items.\"\"\"\n+ if value != self._parent:\n+ self._parent = value\n+ for item in self._list:\n+ item.parent = self._parent\n+\n+ def __setitem__(self, i, val):\n+ \"\"\"Set the parent dataset to the new sequence item\"\"\"\n+ super(Sequence, self).__setitem__(i, val)\n+ val.parent = self._parent\n+\n def __str__(self):\n \"\"\"String description of the Sequence.\"\"\"\n lines = [str(x) for x in self]\n", "test_patch": "diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py\n--- a/pydicom/tests/test_filewriter.py\n+++ b/pydicom/tests/test_filewriter.py\n@@ -864,6 +864,47 @@ def test_write_new_ambiguous(self):\n assert ds[0x00283002].VR == 'US'\n assert ds.LUTDescriptor == [1, 0]\n \n+ def test_ambiguous_element_in_sequence_explicit(self):\n+ \"\"\"Test that writing a sequence with an ambiguous element\n+ as explicit transfer syntax works.\"\"\"\n+ # regression test for #804\n+ ds = Dataset()\n+ ds.PixelRepresentation = 0\n+ ds.ModalityLUTSequence = [Dataset()]\n+ ds.ModalityLUTSequence[0].LUTDescriptor = [0, 0, 16]\n+ ds.ModalityLUTSequence[0].LUTExplanation = None\n+ ds.ModalityLUTSequence[0].ModalityLUTType = 'US' # US = unspecified\n+ ds.ModalityLUTSequence[0].LUTData = b'\\x0000\\x149a\\x1f1c\\xc2637'\n+\n+ ds.is_little_endian = True\n+ ds.is_implicit_VR = False\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+\n+ ds = dcmread(fp, force=True)\n+ assert 'US' == ds.ModalityLUTSequence[0][0x00283002].VR\n+\n+ def test_ambiguous_element_in_sequence_implicit(self):\n+ \"\"\"Test that reading a sequence with an ambiguous element\n+ from a file with implicit transfer syntax works.\"\"\"\n+ # regression test for #804\n+ ds = Dataset()\n+ ds.PixelRepresentation = 0\n+ ds.ModalityLUTSequence = [Dataset()]\n+ ds.ModalityLUTSequence[0].LUTDescriptor = [0, 0, 16]\n+ ds.ModalityLUTSequence[0].LUTExplanation = None\n+ ds.ModalityLUTSequence[0].ModalityLUTType = 'US' # US = unspecified\n+ ds.ModalityLUTSequence[0].LUTData = b'\\x0000\\x149a\\x1f1c\\xc2637'\n+\n+ ds.is_little_endian = True\n+ ds.is_implicit_VR = True\n+ fp = BytesIO()\n+ ds.save_as(fp, write_like_original=True)\n+ ds = dcmread(fp, force=True)\n+ # we first have to access the value to trigger correcting the VR\n+ assert 16 == ds.ModalityLUTSequence[0].LUTDescriptor[2]\n+ assert 'US' == ds.ModalityLUTSequence[0][0x00283002].VR\n+\n \n class TestCorrectAmbiguousVRElement(object):\n \"\"\"Test filewriter.correct_ambiguous_vr_element\"\"\"\n", "problem_statement": "\"Printing\" of certain dicom files fails once, but works the second time\n<!-- Instructions For Filing a Bug: https://github.com/pydicom/pydicom/blob/master/CONTRIBUTING.md#filing-bugs -->\r\n\r\n#### Description\r\n\"Printing\" of certain dicom files (see [example](https://github.com/pydicom/pydicom/files/2865551/dicom_exception.zip)) fails once, but not the second time\r\n\r\n#### Steps/Code to Reproduce\r\n```python\r\nfrom pydicom import read_file\r\n\r\na = read_file('...')\r\nprint(a)\r\n# triggers exception: AttributeError: With tag (0028, 3000) got exception: Failed to resolve ambiguous VR for tag (0028, 3002): 'Dataset' object has no attribute 'PixelRepresentation'\r\n\r\n# try same thing again...\r\nprint(a)\r\n# just works...\r\n```\r\n\r\n#### Versions\r\nBehaviour as described above at least on:\r\n```\r\nLinux-4.18.0-15-generic-x86_64-with-Ubuntu-18.10-cosmic\r\n('Python', '2.7.15+ (default, Oct 2 2018, 22:12:08) \\n[GCC 8.2.0]')\r\n('numpy', '1.14.5')\r\n('pydicom', '1.3.0.dev0')\r\n```\r\nand\r\n\r\n\r\n```\r\n('pydicom', '1.2.2')\r\n```\r\n\r\nWorks as expected on:\r\n```\r\nLinux-4.18.0-15-generic-x86_64-with-Ubuntu-18.10-cosmic\r\n('Python', '2.7.15+ (default, Oct 2 2018, 22:12:08) \\n[GCC 8.2.0]')\r\n('pydicom', '1.0.1')\r\n```\n", "hints_text": "Occurs because Pixel Representation is in the top level-dataset while the ambiguous element is in a sequence.\r\n\r\nRegression test:\r\n```python\r\nfrom pydicom.dataset import Dataset\r\n\r\nds = Dataset()\r\nds.PixelRepresentation = 0\r\nds.ModalityLUTSequence = [Dataset()]\r\nds.ModalityLUTSequence[0].LUTDescriptor = [0, 0, 16]\r\nds.ModalityLUTSequence[0].LUTExplanation = None\r\nds.ModalityLUTSequence[0].ModalityLUTType = 'US' # US = unspecified\r\nds.ModalityLUTSequence[0].LUTData = b'\\x0000\\x149a\\x1f1c\\c2637'\r\n\r\nds.is_little_endian= True\r\nds.is_implicit_VR = False\r\nds.save_as('test.dcm')\r\n```\r\n\r\nThe reason it works the second time is the ambiguous VR correction only gets used during the initial decoding (pydicom uses deferred decoding which is triggered by the first `print()`).\r\n\r\nThis might be a bit tricky to fix elegantly...\nOne thing we should probably change is to warn rather than raise if ambiguous correction fails during decoding. Should still raise if occurs during encoding\n> This might be a bit tricky to fix elegantly...\r\n\r\nYes... we have to support the cases where the tag needed to resolve the ambiguity is in the sequence item, or in any parent dataset (for nested sequences). Having the parent dataset as a member in the dataset would allow this, but this would also mean, that it has always to be set on creating a sequence item... not sure if this is a good idea. \nAnother option is to pass the function a dict/Dataset containing elements required for resolving ambiguity (if they're present)", "created_at": "2019-03-04T20:14:54Z", "version": "1.2", "FAIL_TO_PASS": ["pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_explicit", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_ambiguous_element_in_sequence_implicit"], "PASS_TO_PASS": ["pydicom/tests/test_filewriter.py::TestWriteFile::testRTPlan", "pydicom/tests/test_filewriter.py::TestWriteFile::testRTDose", "pydicom/tests/test_filewriter.py::TestWriteFile::testCT", "pydicom/tests/test_filewriter.py::TestWriteFile::testMR", "pydicom/tests/test_filewriter.py::TestWriteFile::testUnicode", "pydicom/tests/test_filewriter.py::TestWriteFile::testMultiPN", "pydicom/tests/test_filewriter.py::TestWriteFile::testJPEG2000", "pydicom/tests/test_filewriter.py::TestWriteFile::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestWriteFile::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTPlan", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testRTDose", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testCT", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMR", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testUnicode", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testMultiPN", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testJPEG2000", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::testwrite_short_uid", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_no_ts", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_double_filemeta", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_ffff_ffff", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_write_removes_grouplength", "pydicom/tests/test_filewriter.py::TestScratchWriteDateTime::test_multivalue_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_empty_AT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_empty_LO", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DA", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_TM", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_multi_DT", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_ascii_vr_with_padding", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OD_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_OL_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UC_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UR_explicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_UN_implicit_little", "pydicom/tests/test_filewriter.py::TestWriteDataElement::test_write_unknown_vr_raises", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_write_new_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_not_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_data_element", "pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVRElement::test_correct_ambiguous_raw_data_element", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_raises", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_little_endian", "pydicom/tests/test_filewriter.py::TestWriteAmbiguousVR::test_write_explicit_vr_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raw_elements_preserved_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_dataset_with_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_implicit_to_explicit_vr_using_destination", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_explicit_to_implicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_big_to_little_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_little_to_big_endian", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_changed_character_set", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_private_tag_vr_from_implicit_data", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_convert_rgb_from_implicit_to_explicit_vr", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard", "pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta", "pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position", "pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_empty_value", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_list", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_singleton", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_exception", "pydicom/tests/test_filewriter.py::TestWriteNumbers::test_write_big_endian", "pydicom/tests/test_filewriter.py::TestWritePN::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_groups", "pydicom/tests/test_filewriter.py::TestWritePN::test_single_byte_multi_charset_values", "pydicom/tests/test_filewriter.py::TestWriteText::test_no_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_encode_mixed_charsets_text", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_byte_multi_charset_text_multivalue", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding", "pydicom/tests/test_filewriter.py::TestWriteText::test_invalid_encoding_enforce_standard", "pydicom/tests/test_filewriter.py::TestWriteText::test_single_value_with_delimiters", "pydicom/tests/test_filewriter.py::TestWriteDT::test_format_dt", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_to_gzip", "pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_writing_too_big_data_in_explicit_encoding"], "environment_setup_commit": "b4b44acbf1ddcaf03df16210aac46cb3a8acd6b9"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-933", "base_commit": "38436b6824c079564b8760ea6acfa4c0fd3ee9c3", "patch": "diff --git a/pydicom/dataset.py b/pydicom/dataset.py\n--- a/pydicom/dataset.py\n+++ b/pydicom/dataset.py\n@@ -2114,11 +2114,12 @@ def __init__(self,\n self.file_meta = file_meta\n self.is_implicit_VR = is_implicit_VR\n self.is_little_endian = is_little_endian\n+ filename = None\n if isinstance(filename_or_obj, compat.string_types):\n- self.filename = filename_or_obj\n+ filename = filename_or_obj\n self.fileobj_type = open\n elif isinstance(filename_or_obj, io.BufferedReader):\n- self.filename = filename_or_obj.name\n+ filename = filename_or_obj.name\n # This is the appropriate constructor for io.BufferedReader\n self.fileobj_type = open\n else:\n@@ -2126,17 +2127,20 @@ def __init__(self,\n # http://docs.python.org/reference/datamodel.html\n self.fileobj_type = filename_or_obj.__class__\n if getattr(filename_or_obj, \"name\", False):\n- self.filename = filename_or_obj.name\n+ filename = filename_or_obj.name\n elif getattr(filename_or_obj, \"filename\",\n False): # gzip python <2.7?\n- self.filename = filename_or_obj.filename\n+ filename = filename_or_obj.filename\n else:\n # e.g. came from BytesIO or something file-like\n- self.filename = None\n+ self.filename = filename_or_obj\n+\n self.timestamp = None\n- if self.filename and os.path.exists(self.filename):\n- statinfo = os.stat(self.filename)\n- self.timestamp = statinfo.st_mtime\n+ if filename:\n+ self.filename = filename\n+ if os.path.exists(filename):\n+ statinfo = os.stat(filename)\n+ self.timestamp = statinfo.st_mtime\n \n def __eq__(self, other):\n \"\"\"Compare `self` and `other` for equality.\ndiff --git a/pydicom/filereader.py b/pydicom/filereader.py\n--- a/pydicom/filereader.py\n+++ b/pydicom/filereader.py\n@@ -44,7 +44,7 @@ def data_element_generator(fp,\n Parameters\n ----------\n fp : file-like\n- The file like to read from.\n+ The file-like to read from.\n is_implicit_VR : bool\n ``True`` if the data is encoded as implicit VR, ``False`` otherwise.\n is_little_endian : bool\n@@ -912,28 +912,63 @@ def data_element_offset_to_value(is_implicit_VR, VR):\n return offset\n \n \n-def read_deferred_data_element(fileobj_type, filename, timestamp,\n+def read_deferred_data_element(fileobj_type, filename_or_obj, timestamp,\n raw_data_elem):\n \"\"\"Read the previously deferred value from the file into memory\n- and return a raw data element\"\"\"\n+ and return a raw data element.\n+\n+ .. note:\n+\n+ This is called internally by pydicom and will normally not be\n+ needed in user code.\n+\n+ Parameters\n+ ----------\n+ fileobj_type : type\n+ The type of the original file object.\n+ filename_or_obj : str or file-like\n+ The filename of the original file if one exists, or the file-like\n+ object where the data element persists.\n+ timestamp : time or None\n+ The time the original file has been read, if not a file-like.\n+ raw_data_elem : dataelem.RawDataElement\n+ The raw data element with no value set.\n+\n+ Returns\n+ -------\n+ dataelem.RawDataElement\n+ The data element with the value set.\n+\n+ Raises\n+ ------\n+ IOError\n+ If `filename_or_obj` is ``None``.\n+ IOError\n+ If `filename_or_obj` is a filename and the corresponding file does\n+ not exist.\n+ ValueError\n+ If the VR or tag of `raw_data_elem` does not match the read value.\n+ \"\"\"\n logger.debug(\"Reading deferred element %r\" % str(raw_data_elem.tag))\n # If it wasn't read from a file, then return an error\n- if filename is None:\n+ if filename_or_obj is None:\n raise IOError(\"Deferred read -- original filename not stored. \"\n \"Cannot re-open\")\n+ is_filename = isinstance(filename_or_obj, compat.string_types)\n+\n # Check that the file is the same as when originally read\n- if not os.path.exists(filename):\n+ if is_filename and not os.path.exists(filename_or_obj):\n raise IOError(u\"Deferred read -- original file \"\n- \"{0:s} is missing\".format(filename))\n+ \"{0:s} is missing\".format(filename_or_obj))\n if timestamp is not None:\n- statinfo = os.stat(filename)\n+ statinfo = os.stat(filename_or_obj)\n if statinfo.st_mtime != timestamp:\n warnings.warn(\"Deferred read warning -- file modification time \"\n \"has changed.\")\n \n # Open the file, position to the right place\n- # fp = self.typefileobj(self.filename, \"rb\")\n- fp = fileobj_type(filename, 'rb')\n+ fp = (fileobj_type(filename_or_obj, 'rb')\n+ if is_filename else filename_or_obj)\n is_implicit_VR = raw_data_elem.is_implicit_VR\n is_little_endian = raw_data_elem.is_little_endian\n offset = data_element_offset_to_value(is_implicit_VR, raw_data_elem.VR)\n", "test_patch": "diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py\n--- a/pydicom/tests/test_filereader.py\n+++ b/pydicom/tests/test_filereader.py\n@@ -3,6 +3,7 @@\n \"\"\"Unit tests for the pydicom.filereader module.\"\"\"\n \n import gzip\n+import io\n from io import BytesIO\n import os\n import shutil\n@@ -918,6 +919,14 @@ def test_zipped_deferred(self):\n # the right place, it was re-opened as a normal file, not a zip file\n ds.InstanceNumber\n \n+ def test_filelike_deferred(self):\n+ \"\"\"Deferred values work with file-like objects.\"\"\"\n+ with open(ct_name, 'rb') as fp:\n+ data = fp.read()\n+ filelike = io.BytesIO(data)\n+ dataset = pydicom.dcmread(filelike, defer_size=1024)\n+ assert 32768 == len(dataset.PixelData)\n+\n \n class TestReadTruncatedFile(object):\n def testReadFileWithMissingPixelData(self):\n", "problem_statement": "Deferred Read Fails For File-Like Objects\n#### Description\r\nDeferred reads are failing when dcmread is passed a file-like object (instead of a filepath). There are two old issues from 2014 which describe the same issue which were apparently fixed, but I'm still seeing it on v1.3:\r\nhttps://github.com/pydicom/pydicom/issues/104\r\nhttps://github.com/pydicom/pydicom/issues/74\r\n\r\n#### Steps/Code to Reproduce\r\n```\r\nimport io\r\nimport pydicom\r\n\r\nwith open(\"./0.dcm\", \"rb\") as fp:\r\n data = fp.read()\r\nfilelike = io.BytesIO(data)\r\n\r\ndataset = pydicom.dcmread(filelike, defer_size=1024)\r\nprint(len(dataset.PixelData))\r\n```\r\n\r\n#### Expected Results\r\nPydicom should hold onto the supplied file-like and use that for the deferred read, rather than trying to grab the file-like's .name/.filename attr and use that to re-open. It could also hold onto it's own open'd file-like (if supplied a file_path) and use that for deferred reads to simplify things.\r\n\r\n#### Actual Results\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"/usr/local/lib/python3.6/dist-packages/pydicom/dataset.py\", line 747, in __getattr__\r\n data_elem = self[tag]\r\n File \"/usr/local/lib/python3.6/dist-packages/pydicom/dataset.py\", line 826, in __getitem__\r\n data_elem)\r\n File \"/usr/local/lib/python3.6/dist-packages/pydicom/filereader.py\", line 911, in read_deferred_data_element\r\n raise IOError(\"Deferred read -- original filename not stored. \"\r\nOSError: Deferred read -- original filename not stored. Cannot re-open\r\n\r\n#### Versions\r\nLinux-4.18.0-25-generic-x86_64-with-Ubuntu-18.10-cosmic\r\nPython 3.6.7 (default, Oct 22 2018, 11:32:17) \r\npydicom 1.3.0\n", "hints_text": "This certainly makes sense, though deferred reads have not been implemented for file-like, so I see this as a feature request. \r\n@darcymason - I suggest to flag this for the 1.4 release.\nNote that the two mentioned issues have not addressed this - the first one was not about deferred read, the second one was about deferred read from a gzip file (the fix just made sure the correct filename was used).", "created_at": "2019-08-15T20:21:09Z", "version": "1.3", "FAIL_TO_PASS": ["pydicom/tests/test_filereader.py::TestDeferredRead::test_filelike_deferred"], "PASS_TO_PASS": ["pydicom/tests/test_filereader.py::TestReader::test_empty_numbers_tag", "pydicom/tests/test_filereader.py::TestReader::test_UTF8_filename", "pydicom/tests/test_filereader.py::TestReader::test_RTPlan", "pydicom/tests/test_filereader.py::TestReader::test_RTDose", "pydicom/tests/test_filereader.py::TestReader::test_CT", "pydicom/tests/test_filereader.py::TestReader::test_CT_PixelData", "pydicom/tests/test_filereader.py::TestReader::test_no_force", "pydicom/tests/test_filereader.py::TestReader::test_RTStruct", "pydicom/tests/test_filereader.py::TestReader::test_dir", "pydicom/tests/test_filereader.py::TestReader::test_MR", "pydicom/tests/test_filereader.py::TestReader::test_deflate", "pydicom/tests/test_filereader.py::TestReader::test_no_pixels_read", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_SQ", "pydicom/tests/test_filereader.py::TestReader::test_specific_tags_with_unknown_length_tag", "pydicom/tests/test_filereader.py::TestReader::test_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_nested_private_SQ", "pydicom/tests/test_filereader.py::TestReader::test_no_meta_group_length", "pydicom/tests/test_filereader.py::TestReader::test_no_transfer_syntax_in_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_little_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_explicit_VR_big_endian_no_meta", "pydicom/tests/test_filereader.py::TestReader::test_planar_config", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_explicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_correct_ambiguous_vr_compressed", "pydicom/tests/test_filereader.py::TestReader::test_long_specific_char_set", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_file_meta_dataset", "pydicom/tests/test_filereader.py::TestReader::test_no_preamble_command_group_dataset", "pydicom/tests/test_filereader.py::TestReader::test_group_length_wrong", "pydicom/tests/test_filereader.py::TestReader::test_preamble_command_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_preamble_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_meta_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_commandset_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_file_meta_dataset_implicit_vr", "pydicom/tests/test_filereader.py::TestReader::test_no_dataset", "pydicom/tests/test_filereader.py::TestReader::test_empty_file", "pydicom/tests/test_filereader.py::TestReader::test_dcmread_does_not_raise", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_implicit_vr_expected_explicit_used_strict", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used", "pydicom/tests/test_filereader.py::TestIncorrectVR::test_explicit_vr_expected_implicit_used_strict", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00A-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[@A-0x40", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[[A-0x5b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[`A-0x60", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[{A-0x7b", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\xffA-0xff", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[A\\x00-0x41", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Z\\x00-0x5a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[a\\x00-0x61", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[z\\x00-0x7a", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00Z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00a-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[\\x00z-0x00", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AA-AA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[AZ-AZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZA-ZA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[ZZ-ZZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Aa-Aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Az-Az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aA-aA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aZ-aZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[aa-aa]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[az-az]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Za-Za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[Zz-Zz]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zA-zA]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zZ-zZ]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[za-za]", "pydicom/tests/test_filereader.py::TestUnknownVR::test_fail_decode_msg[zz-zz]", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OD_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_OL_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UC_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_implicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_UR_explicit_little", "pydicom/tests/test_filereader.py::TestReadDataElement::test_read_AE", "pydicom/tests/test_filereader.py::TestDeferredRead::test_time_check", "pydicom/tests/test_filereader.py::TestDeferredRead::test_file_exists", "pydicom/tests/test_filereader.py::TestDeferredRead::test_values_identical", "pydicom/tests/test_filereader.py::TestDeferredRead::test_zipped_deferred", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelData", "pydicom/tests/test_filereader.py::TestReadTruncatedFile::testReadFileWithMissingPixelDataArray", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_object", "pydicom/tests/test_filereader.py::TestFileLike::test_read_file_given_file_like_object", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_explicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_little_endian_implicit", "pydicom/tests/test_filereader.py::TestDataElementGenerator::test_big_endian_explicit"], "environment_setup_commit": "7241f5d9db0de589b230bb84212fbb643a7c86c3"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1633", "base_commit": "98ac88706e7ab17cd279c94949ac6af4e87f341d", "patch": "diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py\n--- a/pydicom/valuerep.py\n+++ b/pydicom/valuerep.py\n@@ -874,7 +874,7 @@ def __init__(\n \n if (validation_mode == config.RAISE and\n not self.auto_format):\n- if len(repr(self)[1:-1]) > 16:\n+ if len(str(self)) > 16:\n raise OverflowError(\n \"Values for elements with a VR of 'DS' must be <= 16 \"\n \"characters long, but the float provided requires > 16 \"\n@@ -884,7 +884,7 @@ def __init__(\n \"explicitly construct a DS object with 'auto_format' \"\n \"set to True\"\n )\n- if not is_valid_ds(repr(self)[1:-1]):\n+ if not is_valid_ds(str(self)):\n # This will catch nan and inf\n raise ValueError(\n f'Value \"{str(self)}\" is not valid for elements with a VR '\n", "test_patch": "diff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py\n--- a/pydicom/tests/test_valuerep.py\n+++ b/pydicom/tests/test_valuerep.py\n@@ -603,6 +603,13 @@ def test_enforce_valid_values_length(self):\n valuerep.DSfloat('3.141592653589793',\n validation_mode=config.RAISE)\n \n+ def test_handle_missing_leading_zero(self):\n+ \"\"\"Test that no error is raised with maximum length DS string\n+ without leading zero.\"\"\"\n+ # Regression test for #1632\n+ valuerep.DSfloat(\".002006091181818\",\n+ validation_mode=config.RAISE)\n+\n def test_DSfloat_auto_format(self):\n \"\"\"Test creating a value using DSfloat copies auto_format\"\"\"\n x = DSfloat(math.pi, auto_format=True)\n", "problem_statement": "OverflowError \"VR of 'DS' must be <= 16 characters long\" triggered when element is 16 characters long\n**Describe the bug**\r\n\r\n`OverflowError` triggered while accessing `PixelData`, which the values compliant with the standard. In the sample referenced in the example below, we have this, which satisfies DS VR:\r\n\r\n```\r\n(0028,0030) DS [.002006091181818\\.002006091181818] # 34, 2 PixelSpacing\r\n```\r\n\r\nBut nevertheless the error is triggered while trying to access `PixelData`:\r\n\r\n```\r\nOverflowError: Values for elements with a VR of 'DS' must be <= 16 characters long, \r\nbut the float provided requires > 16 characters to be accurately represented. Use a \r\nsmaller string, set 'config.settings.reading_validation_mode' to 'WARN' to override \r\nthe length check, or explicitly construct a DS object with 'auto_format' set to True\r\n```\r\n\r\n**Expected behavior**\r\n\r\n`OverflowError` does not get triggered.\r\n\r\n**Steps To Reproduce**\r\n\r\nFollow the steps of this Colab notebook: https://colab.research.google.com/drive/1FcSgjBKazh0YN-jlJYdID0YUTh90CAvZ?usp=sharing\r\n\r\n**Your environment**\r\n\r\n```\r\nmodule | version\r\n------ | -------\r\nplatform | Linux-5.4.144+-x86_64-with-Ubuntu-18.04-bionic\r\nPython | 3.7.13 (default, Mar 16 2022, 17:37:17) [GCC 7.5.0]\r\npydicom | 2.3.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | 1.21.5\r\nPIL | 9.1.0\r\npylibjpeg | _module not found_\r\nopenjpeg | _module not found_\r\nlibjpeg | _module not found_\r\n```\r\n\r\nRelated issue: https://github.com/imi-bigpicture/wsidicom/issues/49\r\n\r\ncc: @DanielaSchacherer @dclunie @hackermd \n", "hints_text": "For reference, a possibly similar issue came up in dcmjs: https://github.com/dcmjs-org/dcmjs/issues/175\nI had a quick look, and the problem seems to be that the length is not taken from the original string, but from the string representation, which in this case adds a leading zero... This check has been introduced in pydicom 2.2.0.", "created_at": "2022-04-14T18:26:56Z", "version": "2.3", "FAIL_TO_PASS": ["pydicom/tests/test_valuerep.py::TestDSfloat::test_handle_missing_leading_zero"], "PASS_TO_PASS": ["pydicom/tests/test_valuerep.py::TestTM::test_pickling", "pydicom/tests/test_valuerep.py::TestTM::test_pickling_tm_from_time", "pydicom/tests/test_valuerep.py::TestTM::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestTM::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestTM::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestTM::test_comparison", "pydicom/tests/test_valuerep.py::TestTM::test_time_behavior", "pydicom/tests/test_valuerep.py::TestDT::test_pickling", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime", "pydicom/tests/test_valuerep.py::TestDT::test_pickling_dt_from_datetime_with_timezone", "pydicom/tests/test_valuerep.py::TestDT::test_new_empty_str", "pydicom/tests/test_valuerep.py::TestDT::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_new_str_conversion", "pydicom/tests/test_valuerep.py::TestDT::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDT::test_comparison", "pydicom/tests/test_valuerep.py::TestDT::test_datetime_behavior", "pydicom/tests/test_valuerep.py::TestDA::test_pickling", "pydicom/tests/test_valuerep.py::TestDA::test_new_obj_conversion", "pydicom/tests/test_valuerep.py::TestDA::test_str_and_repr", "pydicom/tests/test_valuerep.py::TestDA::test_comparison", "pydicom/tests/test_valuerep.py::TestDA::test_date_behavior", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[3.14159265358979]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[-1234.456e78]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E-5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[1.234E+5]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[+1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_valid[42", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[nan]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[3.141592653589793]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1,000]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[127.0.0.1]", "pydicom/tests/test_valuerep.py::TestIsValidDS::test_invalid[1.e]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.0-1.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.0-0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.0--0.0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[0.123-0.123]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-0.321--0.321]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1e-05-1e-05]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[3.141592653589793-3.14159265358979]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-3.141592653589793--3.1415926535898]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[5.385940192876374e-07-5.3859401929e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[-5.385940192876374e-07--5.385940193e-07]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[12342534378.125532-12342534378.1255]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[64070869985876.78-64070869985876.8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_auto_format[1.7976931348623157e+308-1.797693135e+308]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[100]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[101]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[-1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[2]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[3]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[4]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[5]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[6]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[7]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[8]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[9]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[10]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[11]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[12]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[13]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[14]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[15]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_powers_of_negative_pi[16]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan0]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[nan1]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[-inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_invalid[inf]", "pydicom/tests/test_valuerep.py::TestTruncateFloatForDS::test_wrong_type", "pydicom/tests/test_valuerep.py::TestDS::test_empty_value", "pydicom/tests/test_valuerep.py::TestDS::test_float_values", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_pickling[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_new_empty[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_new_empty[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str_value[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str_value[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_str[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_repr[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSdecimal[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_length", "pydicom/tests/test_valuerep.py::TestDSfloat::test_DSfloat_auto_format", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-nan]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf0]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[nan2]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[-inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_enforce_valid_values_value[inf1]", "pydicom/tests/test_valuerep.py::TestDSfloat::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSfloat::test_hash", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_pickling", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_float_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_new_empty", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_str_value", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSfloat", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_repr", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_string_too_long", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_string_too_long_raises", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_from_invalid_DS", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_invalid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-NaN]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[-Infinity]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val4]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val5]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val6]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_enforce_valid_values_value[val7]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[True]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_auto_format_valid_string[False]", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_DSdecimal_auto_format", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestDSdecimal::test_hash", "pydicom/tests/test_valuerep.py::TestIS::test_empty_value", "pydicom/tests/test_valuerep.py::TestIS::test_str_value", "pydicom/tests/test_valuerep.py::TestIS::test_valid_value", "pydicom/tests/test_valuerep.py::TestIS::test_invalid_value", "pydicom/tests/test_valuerep.py::TestIS::test_pickling", "pydicom/tests/test_valuerep.py::TestIS::test_longint", "pydicom/tests/test_valuerep.py::TestIS::test_overflow", "pydicom/tests/test_valuerep.py::TestIS::test_str", "pydicom/tests/test_valuerep.py::TestIS::test_repr", "pydicom/tests/test_valuerep.py::TestIS::test_comparison_operators", "pydicom/tests/test_valuerep.py::TestIS::test_hash", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_default", "pydicom/tests/test_valuerep.py::TestBadValueRead::test_read_bad_value_in_VR_enforce_valid_value", "pydicom/tests/test_valuerep.py::TestDecimalString::test_DS_decimal_set", "pydicom/tests/test_valuerep.py::TestDecimalString::test_valid_decimal_strings", "pydicom/tests/test_valuerep.py::TestDecimalString::test_invalid_decimal_strings", "pydicom/tests/test_valuerep.py::TestPersonName::test_last_first", "pydicom/tests/test_valuerep.py::TestPersonName::test_no_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_copy", "pydicom/tests/test_valuerep.py::TestPersonName::test_three_component", "pydicom/tests/test_valuerep.py::TestPersonName::test_formatting", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_kr", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_comp_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_bytes_caret_delimiter", "pydicom/tests/test_valuerep.py::TestPersonName::test_unicode_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_not_equal", "pydicom/tests/test_valuerep.py::TestPersonName::test_encoding_carried", "pydicom/tests/test_valuerep.py::TestPersonName::test_hash", "pydicom/tests/test_valuerep.py::TestPersonName::test_next", "pydicom/tests/test_valuerep.py::TestPersonName::test_iterator", "pydicom/tests/test_valuerep.py::TestPersonName::test_contains", "pydicom/tests/test_valuerep.py::TestPersonName::test_length", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_kr_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_bytes", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_jp_from_unicode", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_veterinary", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator", "pydicom/tests/test_valuerep.py::TestPersonName::test_from_named_components_with_separator_from_bytes", "pydicom/tests/test_valuerep.py::TestDateTime::test_date", "pydicom/tests/test_valuerep.py::TestDateTime::test_date_time", "pydicom/tests/test_valuerep.py::TestDateTime::test_time", "pydicom/tests/test_valuerep.py::test_person_name_unicode_warns", "pydicom/tests/test_valuerep.py::test_set_value[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_set_value[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_set_value[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_set_value[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_set_value[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_set_value[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_set_value[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_set_value[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_set_value[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_set_value[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_set_value[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_set_value[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_set_value[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_set_value[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_set_value[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[OV-bytes-vm020-vmN20-SelectorOVValue]", "pydicom/tests/test_valuerep.py::test_set_value[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_set_value[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_set_value[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_set_value[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_set_value[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_set_value[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_set_value[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_set_value[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_set_value[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_set_value[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_set_value[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_set_value[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_set_value[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_set_value[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_set_value[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_set_value[UV-int-vm037-vmN37-SelectorUVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AE-str-vm00-vmN0-Receiver]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AS-str-vm01-vmN1-PatientAge]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[AT-int-vm02-vmN2-OffendingElement]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[CS-str-vm03-vmN3-QualityControlSubject]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DA-str-vm04-vmN4-PatientBirthDate]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-str-vm05-vmN5-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-int-vm06-vmN6-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DS-float-vm07-vmN7-PatientWeight]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[DT-str-vm08-vmN8-AcquisitionDateTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FD-float-vm09-vmN9-RealWorldValueLUTData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[FL-float-vm010-vmN10-VectorAccuracy]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-str-vm011-vmN11-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-int-vm012-vmN12-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[IS-float-vm013-vmN13-BeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LO-str-vm014-vmN14-DataSetSubtype]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[LT-str-vm015-vmN15-ExtendedCodeMeaning]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OB-bytes-vm016-vmN16-FillPattern]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OD-bytes-vm017-vmN17-DoubleFloatPixelData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OF-bytes-vm018-vmN18-UValueData]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OL-bytes-vm019-vmN19-TrackPointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OV-bytes-vm020-vmN20-SelectorOVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[OW-bytes-vm021-vmN21-TrianglePointIndexList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[PN-str-vm022-vmN22-PatientName]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SH-str-vm023-vmN23-CodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SL-int-vm024-vmN24-RationalNumeratorValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SQ-list-vm025-vmN25-BeamSequence]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SS-int-vm026-vmN26-SelectorSSValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[ST-str-vm027-vmN27-InstitutionAddress]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[SV-int-vm028-vmN28-SelectorSVValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[TM-str-vm029-vmN29-StudyTime]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UC-str-vm030-vmN30-LongCodeValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UI-str-vm031-vmN31-SOPClassUID]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UL-int-vm032-vmN32-SimpleFrameList]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UN-bytes-vm033-vmN33-SelectorUNValue]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UR-str-vm034-vmN34-CodingSchemeURL]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[US-int-vm035-vmN35-SourceAcquisitionBeamNumber]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UT-str-vm036-vmN36-StrainAdditionalInformation]", "pydicom/tests/test_valuerep.py::test_assigning_bytes[UV-int-vm037-vmN37-SelectorUVValue]", "pydicom/tests/test_valuerep.py::TestVR::test_behavior", "pydicom/tests/test_valuerep.py::TestVR::test_all_present"], "environment_setup_commit": "a8be738418dee0a2b93c241fbd5e0bc82f4b8680"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1428", "base_commit": "674da68db47a71ee6929288a047b56cf31cf8168", "patch": "diff --git a/pydicom/fileset.py b/pydicom/fileset.py\n--- a/pydicom/fileset.py\n+++ b/pydicom/fileset.py\n@@ -1486,16 +1486,16 @@ def match(ds, **kwargs):\n \n def find_values(\n self,\n- element: Union[str, int],\n+ elements: Union[str, int, List[Union[str, int]]],\n instances: Optional[List[FileInstance]] = None,\n load: bool = False\n- ) -> List[Any]:\n- \"\"\"Return a list of unique values for a given element.\n+ ) -> Union[List[Any], Dict[Union[str, int], List]]:\n+ \"\"\"Return a list of unique values for given element(s).\n \n Parameters\n ----------\n- element : str, int or pydicom.tag.BaseTag\n- The keyword or tag of the element to search for.\n+ elements : str, int or pydicom.tag.BaseTag, or list of these\n+ The keyword or tag of the element(s) to search for.\n instances : list of pydicom.fileset.FileInstance, optional\n Search within the given instances. If not used then all available\n instances will be searched.\n@@ -1508,32 +1508,41 @@ def find_values(\n \n Returns\n -------\n- list of object\n- A list of value(s) for the element available in the instances.\n+ list of object(s), or dict of lists of object(s)\n+\n+ * If single element was queried: A list of value(s) for the element\n+ available in the instances.\n+ * If list of elements was queried: A dict of element value pairs\n+ with lists of value(s) for the elements available in the instances.\n \"\"\"\n- has_element = False\n- results = []\n+ element_list = elements if isinstance(elements, list) else [elements]\n+ has_element = {element: False for element in element_list}\n+ results: Dict = {element: [] for element in element_list}\n iter_instances = instances or iter(self)\n instance: Union[Dataset, FileInstance]\n for instance in iter_instances:\n if load:\n instance = instance.load()\n-\n- if element not in instance:\n- continue\n-\n- has_element = True\n- val = instance[element].value\n- # Not very efficient, but we can't use set\n- if val not in results:\n- results.append(val)\n-\n- if not load and not has_element:\n+ for element in element_list:\n+ if element not in instance:\n+ continue\n+\n+ has_element[element] = True\n+ val = instance[element].value\n+ # Not very efficient, but we can't use set\n+ if val not in results[element]:\n+ results[element].append(val)\n+ missing_elements = [\n+ element for element, v in has_element.items() if not v\n+ ]\n+ if not load and missing_elements:\n warnings.warn(\n \"None of the records in the DICOMDIR dataset contain \"\n- \"the query element, consider using the 'load' parameter \"\n+ f\"{missing_elements}, consider using the 'load' parameter \"\n \"to expand the search to the corresponding SOP instances\"\n )\n+ if not isinstance(elements, list):\n+ return results[element_list[0]]\n \n return results\n \n", "test_patch": "diff --git a/pydicom/tests/test_fileset.py b/pydicom/tests/test_fileset.py\n--- a/pydicom/tests/test_fileset.py\n+++ b/pydicom/tests/test_fileset.py\n@@ -1945,33 +1945,45 @@ def test_find_load(self, private):\n def test_find_values(self, private):\n \"\"\"Test searching the FileSet for element values.\"\"\"\n fs = FileSet(private)\n- assert ['77654033', '98890234'] == fs.find_values(\"PatientID\")\n- assert (\n- [\n+ expected = {\n+ \"PatientID\": ['77654033', '98890234'],\n+ \"StudyDescription\": [\n 'XR C Spine Comp Min 4 Views',\n 'CT, HEAD/BRAIN WO CONTRAST',\n '',\n 'Carotids',\n 'Brain',\n- 'Brain-MRA'\n- ] == fs.find_values(\"StudyDescription\")\n- )\n+ 'Brain-MRA',\n+ ],\n+ }\n+ for k, v in expected.items():\n+ assert fs.find_values(k) == v\n+ assert fs.find_values(list(expected.keys())) == expected\n \n def test_find_values_load(self, private):\n \"\"\"Test FileSet.find_values(load=True).\"\"\"\n fs = FileSet(private)\n+ search_element = \"PhotometricInterpretation\"\n msg = (\n r\"None of the records in the DICOMDIR dataset contain \"\n- r\"the query element, consider using the 'load' parameter \"\n+ fr\"\\['{search_element}'\\], consider using the 'load' parameter \"\n r\"to expand the search to the corresponding SOP instances\"\n )\n with pytest.warns(UserWarning, match=msg):\n- results = fs.find_values(\"PhotometricInterpretation\", load=False)\n+ results = fs.find_values(search_element, load=False)\n assert not results\n \n- assert ['MONOCHROME1', 'MONOCHROME2'] == fs.find_values(\n- \"PhotometricInterpretation\", load=True\n- )\n+ assert fs.find_values(search_element, load=True) == [\n+ 'MONOCHROME1', 'MONOCHROME2'\n+ ]\n+\n+ with pytest.warns(UserWarning, match=msg):\n+ results = fs.find_values([search_element], load=False)\n+ assert not results[search_element]\n+\n+ assert (\n+ fs.find_values([search_element], load=True)\n+ ) == {search_element: ['MONOCHROME1', 'MONOCHROME2']}\n \n def test_empty_file_id(self, dicomdir):\n \"\"\"Test loading a record with an empty File ID.\"\"\"\n", "problem_statement": "Allow to search a list of elements in a `FileSet` while only loading instances once, to drastically improve execution time\n**Is your feature request related to a problem? Please describe.**\r\nCurrently, `fileset.FileSet.find_values` only allows for elements to be searched for one at a time. When executing this action while setting `load` to `True`, this results in a substantial overhead.\r\n\r\n**Describe the solution you'd like**\r\nThe following example code allows loading the instances once, and iterating over a list of elements to find:\r\n```python\r\ndef find_values_quick(self, elements, instances=None):\r\n results = {element: [] for element in elements}\r\n instances = instances or iter(self)\r\n for instance in instances:\r\n instance = instance.load()\r\n for element in elements:\r\n if element not in instance:\r\n continue\r\n val = instance[element].value\r\n if val not in results[element]:\r\n results[element].append(val)\r\n return results\r\n```\n", "hints_text": "Sounds good, do you want to do the PR? Just change `FileSet.find_values` to support an element or iterable of elements.", "created_at": "2021-06-28T08:57:19Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_fileset.py::TestFileSet_Load::test_find_values", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_find_values_load"], "PASS_TO_PASS": ["pydicom/tests/test_fileset.py::test_is_conformant_file_id", "pydicom/tests/test_fileset.py::test_prefixes", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_numeric", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_numeric_prefix", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_numeric_start", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_alphanumeric", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_alphanumeric_prefix", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_alphanumeric_start", "pydicom/tests/test_fileset.py::TestGenerateFilename::test_long_prefix_raises", "pydicom/tests/test_fileset.py::TestRecordNode::test_root", "pydicom/tests/test_fileset.py::TestRecordNode::test_leaf", "pydicom/tests/test_fileset.py::TestRecordNode::test_add", "pydicom/tests/test_fileset.py::TestRecordNode::test_key", "pydicom/tests/test_fileset.py::TestRecordNode::test_key_raises", "pydicom/tests/test_fileset.py::TestRecordNode::test_bad_record", "pydicom/tests/test_fileset.py::TestRecordNode::test_bad_record_missing_req", "pydicom/tests/test_fileset.py::TestRecordNode::test_encoding", "pydicom/tests/test_fileset.py::TestRecordNode::test_remove_raises", "pydicom/tests/test_fileset.py::TestRecordNode::test_file_id_singleton", "pydicom/tests/test_fileset.py::TestRecordNode::test_file_id_missing", "pydicom/tests/test_fileset.py::TestFileInstance::test_getattr", "pydicom/tests/test_fileset.py::TestFileInstance::test_getattr_order", "pydicom/tests/test_fileset.py::TestFileInstance::test_getitem", "pydicom/tests/test_fileset.py::TestFileInstance::test_getitem_special", "pydicom/tests/test_fileset.py::TestFileInstance::test_getitem_order", "pydicom/tests/test_fileset.py::TestFileInstance::test_contains", "pydicom/tests/test_fileset.py::TestFileInstance::test_is_private", "pydicom/tests/test_fileset.py::TestFileInstance::test_properties", "pydicom/tests/test_fileset.py::TestFileInstance::test_path", "pydicom/tests/test_fileset.py::TestFileInstance::test_path_add", "pydicom/tests/test_fileset.py::TestFileInstance::test_path_move", "pydicom/tests/test_fileset.py::TestFileInstance::test_path_removal", "pydicom/tests/test_fileset.py::TestFileInstance::test_load", "pydicom/tests/test_fileset.py::TestFileInstance::test_load_staged_add", "pydicom/tests/test_fileset.py::TestFileInstance::test_load_staged_move", "pydicom/tests/test_fileset.py::TestFileInstance::test_load_staged_removal", "pydicom/tests/test_fileset.py::TestFileInstance::test_for_moving", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid_add", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid_move", "pydicom/tests/test_fileset.py::TestFileInstance::test_fileid_removal", "pydicom/tests/test_fileset.py::TestFileInstance::test_private", "pydicom/tests/test_fileset.py::TestFileSet::test_empty", "pydicom/tests/test_fileset.py::TestFileSet::test_id", "pydicom/tests/test_fileset.py::TestFileSet::test_uid", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_and_charset_written", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_dicomdir", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_charset", "pydicom/tests/test_fileset.py::TestFileSet::test_descriptor_charset_dicomdir", "pydicom/tests/test_fileset.py::TestFileSet::test_path", "pydicom/tests/test_fileset.py::TestFileSet::test_empty_write", "pydicom/tests/test_fileset.py::TestFileSet::test_add_dataset", "pydicom/tests/test_fileset.py::TestFileSet::test_add_bad_dataset", "pydicom/tests/test_fileset.py::TestFileSet::test_add_path", "pydicom/tests/test_fileset.py::TestFileSet::test_add_add", "pydicom/tests/test_fileset.py::TestFileSet::test_remove", "pydicom/tests/test_fileset.py::TestFileSet::test_remove_iter", "pydicom/tests/test_fileset.py::TestFileSet::test_remove_remove", "pydicom/tests/test_fileset.py::TestFileSet::test_remove_add", "pydicom/tests/test_fileset.py::TestFileSet::test_add_remove", "pydicom/tests/test_fileset.py::TestFileSet::test_file_ids_unique", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_path", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_private", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_too_deep", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_bad_leaf", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_add_add", "pydicom/tests/test_fileset.py::TestFileSet::test_add_custom_remove_add", "pydicom/tests/test_fileset.py::TestFileSet::test_clear", "pydicom/tests/test_fileset.py::TestFileSet::test_str_empty", "pydicom/tests/test_fileset.py::TestFileSet::test_str", "pydicom/tests/test_fileset.py::TestFileSet::test_str_update_structure", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_write_dicomdir", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_write_new_path", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_sop_class_raises", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_filename_raises", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_filename_type_raises", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_find", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_find_load", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_empty_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_bad_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_raise", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_exclude", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_no_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_orphans_private", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_big_endian", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_implicit", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_reordered", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_no_offset", "pydicom/tests/test_fileset.py::TestFileSet_Load::test_load_dicomdir_no_uid", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_dicomdir_fs_changes", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_dicomdir_use_existing", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_dicomdir_use_existing_raises", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_remove_addition_bad_path", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_missing_removal", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_removal_addition_collision", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_implicit", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_use_existing", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_write_use_existing_raises", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_instance_missing", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_instance_missing_required_value", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_rt_dose", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_rt_structure_set", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_rt_plan", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_remove_list", "pydicom/tests/test_fileset.py::TestFileSet_Modify::test_add_bad_one_level", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_copy", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_copy_raises", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_copy_implicit", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_file_id", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_additions", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_removals", "pydicom/tests/test_fileset.py::TestFileSet_Copy::test_additions_removals", "pydicom/tests/test_fileset.py::test_one_level_record[HANGING", "pydicom/tests/test_fileset.py::test_one_level_record[IMPLANT-1.2.840.10008.5.1.4.43.1]", "pydicom/tests/test_fileset.py::test_one_level_record[IMPLANT", "pydicom/tests/test_fileset.py::test_one_level_record[PALETTE-1.2.840.10008.5.1.4.39.1]", "pydicom/tests/test_fileset.py::test_four_level_record[IMAGE-1.2.840.10008.5.1.4.1.1.2-CT-None]", "pydicom/tests/test_fileset.py::test_four_level_record[RT", "pydicom/tests/test_fileset.py::test_four_level_record[PRESENTATION-1.2.840.10008.5.1.4.1.1.11.1-PR-None]", "pydicom/tests/test_fileset.py::test_four_level_record[WAVEFORM-1.2.840.10008.5.1.4.1.1.9.1.1-ECG-None]", "pydicom/tests/test_fileset.py::test_four_level_record[SR", "pydicom/tests/test_fileset.py::test_four_level_record[KEY", "pydicom/tests/test_fileset.py::test_four_level_record[SPECTROSCOPY-1.2.840.10008.5.1.4.1.1.4.2-MS-None]", "pydicom/tests/test_fileset.py::test_four_level_record[RAW", "pydicom/tests/test_fileset.py::test_four_level_record[REGISTRATION-1.2.840.10008.5.1.4.1.1.66.1-REG-None]", "pydicom/tests/test_fileset.py::test_four_level_record[FIDUCIAL-1.2.840.10008.5.1.4.1.1.66.2-FID-None]", "pydicom/tests/test_fileset.py::test_four_level_record[ENCAP", "pydicom/tests/test_fileset.py::test_four_level_record[VALUE", "pydicom/tests/test_fileset.py::test_four_level_record[STEREOMETRIC-1.2.840.10008.5.1.4.1.1.77.1.5.3-SMR-None]", "pydicom/tests/test_fileset.py::test_four_level_record[PLAN-1.2.840.10008.5.1.4.34.7-PLAN-None]", "pydicom/tests/test_fileset.py::test_four_level_record[MEASUREMENT-1.2.840.10008.5.1.4.1.1.78.1-LEN-None]", "pydicom/tests/test_fileset.py::test_four_level_record[SURFACE-1.2.840.10008.5.1.4.1.1.66.5-LS-None]", "pydicom/tests/test_fileset.py::test_four_level_record[SURFACE", "pydicom/tests/test_fileset.py::test_four_level_record[TRACT-1.2.840.10008.5.1.4.1.1.66.6-None-None]", "pydicom/tests/test_fileset.py::test_four_level_record[ASSESSMENT-1.2.840.10008.5.1.4.1.1.90.1-ASMT-None]", "pydicom/tests/test_fileset.py::test_four_level_record[RADIOTHERAPY-1.2.840.10008.5.1.4.1.1.481.13-RTRAD-None]"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}, {"repo": "pydicom/pydicom", "instance_id": "pydicom__pydicom-1256", "base_commit": "49a3da4a3d9c24d7e8427a25048a1c7d5c4f7724", "patch": "diff --git a/pydicom/jsonrep.py b/pydicom/jsonrep.py\n--- a/pydicom/jsonrep.py\n+++ b/pydicom/jsonrep.py\n@@ -226,7 +226,8 @@ def get_sequence_item(self, value):\n value_key = unique_value_keys[0]\n elem = DataElement.from_json(\n self.dataset_class, key, vr,\n- val[value_key], value_key\n+ val[value_key], value_key,\n+ self.bulk_data_element_handler\n )\n ds.add(elem)\n return ds\n", "test_patch": "diff --git a/pydicom/tests/test_json.py b/pydicom/tests/test_json.py\n--- a/pydicom/tests/test_json.py\n+++ b/pydicom/tests/test_json.py\n@@ -354,3 +354,25 @@ def bulk_data_reader(tag, vr, value):\n ds = Dataset().from_json(json.dumps(json_data), bulk_data_reader)\n \n assert b'xyzzy' == ds[0x00091002].value\n+\n+ def test_bulk_data_reader_is_called_within_SQ(self):\n+ def bulk_data_reader(_):\n+ return b'xyzzy'\n+\n+ json_data = {\n+ \"003a0200\": {\n+ \"vr\": \"SQ\", \n+ \"Value\": [\n+ {\n+ \"54001010\": {\n+ \"vr\": \"OW\",\n+ \"BulkDataURI\": \"https://a.dummy.url\"\n+ }\n+ }\n+ ]\n+ }\n+ }\n+\n+ ds = Dataset().from_json(json.dumps(json_data), bulk_data_reader)\n+\n+ assert b'xyzzy' == ds[0x003a0200].value[0][0x54001010].value\n", "problem_statement": "from_json does not correctly convert BulkDataURI's in SQ data elements\n**Describe the bug**\r\nWhen a DICOM object contains large data elements in SQ elements and is converted to JSON, those elements are correctly turned into BulkDataURI's. However, when the JSON is converted back to DICOM using from_json, the BulkDataURI's in SQ data elements are not converted back and warnings are thrown.\r\n\r\n**Expected behavior**\r\nThe BulkDataURI's in SQ data elements get converted back correctly.\r\n\r\n**Steps To Reproduce**\r\nTake the `waveform_ecg.dcm` in the test data, convert it to JSON, and then convert the JSON to DICOM\r\n\r\n**Your environment**\r\nmodule | version\r\n------ | -------\r\nplatform | macOS-10.15.7-x86_64-i386-64bit\r\nPython | 3.8.2 (v3.8.2:7b3ab5921f, Feb 24 2020, 17:52:18) [Clang 6.0 (clang-600.0.57)]\r\npydicom | 2.1.0\r\ngdcm | _module not found_\r\njpeg_ls | _module not found_\r\nnumpy | _module not found_\r\nPIL | _module not found_\r\n\r\nThe problem is in `jsonrep.py` at line 227. I plan on submitting a pull-request today for this.\n", "hints_text": "", "created_at": "2020-11-04T21:13:33Z", "version": "2.1", "FAIL_TO_PASS": ["pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_within_SQ"], "PASS_TO_PASS": ["pydicom/tests/test_json.py::TestPersonName::test_json_pn_from_file", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_to_json", "pydicom/tests/test_json.py::TestPersonName::test_pn_components_from_json", "pydicom/tests/test_json.py::TestPersonName::test_empty_value", "pydicom/tests/test_json.py::TestPersonName::test_multi_value_to_json", "pydicom/tests/test_json.py::TestPersonName::test_dataelem_from_json", "pydicom/tests/test_json.py::TestAT::test_to_json", "pydicom/tests/test_json.py::TestAT::test_from_json", "pydicom/tests/test_json.py::TestAT::test_invalid_value_in_json", "pydicom/tests/test_json.py::TestAT::test_invalid_tag_in_json", "pydicom/tests/test_json.py::TestDataSetToJson::test_json_from_dicom_file", "pydicom/tests/test_json.py::TestDataSetToJson::test_roundtrip", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataset_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_dataelement_dumphandler", "pydicom/tests/test_json.py::TestDataSetToJson::test_sort_order", "pydicom/tests/test_json.py::TestSequence::test_nested_sequences", "pydicom/tests/test_json.py::TestBinary::test_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_invalid_inline_binary", "pydicom/tests/test_json.py::TestBinary::test_valid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_invalid_bulkdata_uri", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called", "pydicom/tests/test_json.py::TestBinary::test_bulk_data_reader_is_called_2"], "environment_setup_commit": "506ecea8f378dc687d5c504788fc78810a190b7a"}]\ No newline at end of file