Repository navigation
fix(warnings): show user-facing warnings through warnings.warn - #294
Conversation
7c7dc5a to
20c3fce
Compare
6f4978b to
e45dd38
Compare
|
VERDICT: FAIL Reviewed SHA: 4297e96 (round 2). Base origin/dev 3ae5842, which is still the tip of dev and is the merge base, so the merge is clean. Lane: audit + regression. Blocking finding1. In IPython and Jupyter, every
1b. Same cause, plain
Round-1 findings
What I ran
Acceptance items
Notes (not blocking)
|
4297e96 to
305023e
Compare
|
VERDICT: PASS+NOTES Reviewed SHA: 305023e. Gates ran on that SHA merged with current origin/dev f243254 (#297). The merge is clean: Gates (merged head,
|
| scenario | named location | DeprecationWarning or exception? |
|---|---|---|
real Jupyter kernel (jupyter_client), bandsplot with no fermi |
ipykernel_*/1408399939.py:2 (the cell's line) |
none |
same kernel, KPath with 1 name for 2 segments |
the cell's line 3 | none |
same kernel, QEParser(empty).alat (cached_property) |
the cell's line 2 | none |
| same kernel, helper called in a loop 3 times | the helper's line, shown once | none |
same kernel, simplefilter("error") |
raises UserWarning |
expected |
ipython -c: KPath, then bandsplot |
<ipython-input-1-…>:4 and :5, source line printed |
none (__spec__ is None) |
python s_bands.py, 2 calls in a loop |
s_bands.py:5, twice (matplotlib resets the registry, as the PR documents) |
none |
python -W always::DeprecationWarning s_qe.py |
s_qe.py:5 |
none |
-W error (precompiled pycache, HF warning ignored) |
UserWarning raised from the user's line for KPath, bandsplot and QE alat |
expected |
-W error::DeprecationWarning (HF warning ignored) |
s_kpath.py:4, s_bands.py:5, s_qe.py:5 |
none |
-W ignore |
nothing printed | none |
-W ignore::UserWarning:__main__ and :mymod |
suppressed (module attribution matches stdlib) | none |
Elk from_code without GEOMETRY.OUT (cached_property) |
s_elk.py:4 |
none |
QE alat on an empty dir (cached_property) |
s_qe.py:5 |
none |
FermiHandler(...).plot_fermi_surface(mode="no_such_mode") |
s_fermi.py:5 |
none |
| warning while a user module imports | mymod.py:4 |
none |
matplotlib draw_event callback that calls pyprocar |
s_mpl.py:9 (inside the callback) |
none |
| ThreadPoolExecutor, user function | s_thread.py:7 |
none |
ThreadPoolExecutor, submit(KPath, …) and submit(pyprocar.bandsplot, …) |
concurrent/futures/thread.py:59 |
none |
#299 sites via the ElectronicBandStructureMesh constructor (phase dropped, unrotated ×2, time reversal) and direct ibz2fbz |
head: the user's lines (s_ibz.py:24, :36, :37). origin/dev: pyprocar/core/ebs.py:1669 for 4 of the 5 |
none |
fermi2D(verbose=0) vs verbose=1 |
head: 4 stdout lines vs 47, with ### Parameters ###. origin/dev: 4 lines for both |
n/a |
harness verify_steps |
records both bandsplot warnings under "warnings" in summary.json. The bands driver gives the same 2 failing steps on head and on dev (they already fail on dev) |
n/a |
Things that are the same on origin/dev, not caused by this PR: python -W error and -W error::DeprecationWarning both fail at import pyprocar. The first comes from SyntaxWarnings when no pycache exists. The second comes from the huggingface_hub HF_HUB_ENABLE_HF_TRANSFER DeprecationWarning.
#299 conversions: the 3 ebs.py sites now name the caller's line, where origin/dev named ebs.py:1669. QEParser.symmetries_xml "No rotations found" is now user_logger.debug. No user_logger.warning and no raw warnings.warn remain in pyprocar/ outside log_utils.py.
Mutations of warn_user (10 warning test files, 280 tests including data)
| mutation | failing tests |
|---|---|
drop the pyprocar/ skip |
32 |
| drop the stdlib skip | 9 (Elk and BXSF cached_property tests, bandsplot elk, import-time) |
drop the <frozen skip |
1 (import-time) |
drop the <string> skip |
1 (generated code) |
registry=None |
1 (once per line) |
registry={} |
1 |
add module_globals back |
5 (notebook, script, 3 error-filter tests) |
| remove the thread fallback | 2 |
| use the outermost frame for the fallback | 2 |
co_firstlineno in place of f_lineno |
9 |
drop the _SITE_DIRS exclusion |
survives |
fixed module="pyprocar" |
survives |
Enforcing check: I added 11 forbidden forms to a temporary pyprocar/ module, and tests/test_user_warnings.py flagged all 11. The 9 user-logger forms were the direct call, a module name, .log(logging.WARNING), .log(30), self.lg.error, a name imported from scriptBandsplot, getLogger(name="user"), a local .exception, and .log(level=ERROR). The 2 warnings forms were w.warn and from warnings import warn. The CLAUDE.md row is present.
Acceptance (#284, frozen set)
- The 4 User-facing warnings are hidden by the ERROR-level user logger #284 sites. Done.
- bandsplot: checked live.
- FermiSlicePlotter scalars and vectors: the unit test calls the public class, and the no-pkg-skip mutation is caught.
- fermi2D
verbose: checked live, head vs dev. - The FermiHandler box-widget site: converted. No public call reaches it, because
from_ebsraises first, and the test pins that error.
- The rule applied to every
user_loggerwarning site and every rawwarnings.warnsite inpyprocar/. Done. - The enforcing check and the
CLAUDE.mdrow. Done. - Public-API tests fail on origin/dev. Done: 33 of 39 are red on base for the stated reason, and the other 6 are marked guards.
Notes (none blocking)
pyprocar/utils/log_utils.py:25-30: the thread fallback keeps the innermost non-pyprocar frame. SoThreadPoolExecutor().submit(pyprocar.bandsplot, code="elk", dirname=<elk dir without GEOMETRY.OUT>, fermi=0.0, show=False)namesfunctools.py:998, the round-1 location, notconcurrent/futures/thread.py:59. The comment says "name the line that called into pyprocar". No user frame exists on that stack, so this is not an acceptance failure. A 3-line fix resets the candidate on each pyprocar frame:
if filename.startswith(_PACKAGE_DIR): nearest_outside = None/elif nearest_outside is None and not filename.startswith("<"): nearest_outside = frame
With that fix, the case namesthread.py:59, and 81 of 81 warning tests (plus 1 skipped) still pass.- Two test gaps, shown by the mutations that survive. No test pins the
module=name, which module-scoped-W ...:modulefilters depend on. I checked that live. No test exercises the_SITE_DIRSexclusion either. - 29 package-logger
logger.warning/.errorcalls write only topyprocar.log. Some say a member is None, for exampleVaspParser.ebs,.dosand.structure(io/vasp/parser.py:237,242,313,330).VaspParser(empty).ebsreturns None silently, whileQEParser(empty).ebsnow warns.from_codestill raises loudly. This sits outside User-facing warnings are hidden by the ERROR-level user logger #284's user-logger scope, so it is a candidate follow-up. - A behaviour change:
fermi2D()with the defaultverbose=1now prints the parameter banner (about 43 lines), asdosplotdoes. It also leaves theuserlogger at DEBUG for the rest of the process. - Not checked: Python 3.13 and 3.14. The local env is 3.12.12, and
requires-python >= 3.12.
|
VERDICT: PASS+NOTES Reviewed SHA: 305023e (round 3, based on 5884b80). Since then origin/dev has moved to f243254 (#297, which changes only What I ran
Acceptance items
PR body claims
Notes (none blocking)
|
The user logger is set to ERROR on import, so user_logger.warning() prints nothing in a default call (#284). These tests fail on dev: - tests/test_user_warnings.py lists the 62 user_logger.warning calls in pyprocar/ and the 4 tests that lower the user logger with caplog to see them. - bandsplot without fermi, FermiHandler with no Fermi surface and FermiSlicePlotter with a missing field name emit no UserWarning. - fermi2D prints its verbose progress for neither verbose=0 nor verbose=1.
…ler line FermiSurface.from_ebs raises "No Fermi surfaces were generated" before FermiHandler's empty-surface check runs, so a call with no crossing is already loud; the test now guards that. A probe of 72 pockets (two lattices, six centres, six radii) gave a surface or that error, never an empty surface. The bandsplot test also checks that the warning names the caller's file.
The user logger is set to ERROR on import, so all 62 user_logger.warning calls in pyprocar/ printed nothing in a default call (#284). warn_user() in utils/log_utils.py raises a UserWarning attributed to the first frame outside pyprocar (skip_file_prefixes), so the message names the user's own line. Each site is now either: - warn_user (57 sites): the result differs from what the user asked for, or a member comes back None (fermi not set, ignored argument, missing or unreadable input, an assumed unit convention, an unwritten file). - user_logger.info/debug (5 sites): progress with nothing to act on. QE's missing scf.in/scf.out and rotations, Siesta's auto-detected .bands file (ebs reports its absence), and FermiHandler using the calculation's Fermi energy by default. Tests that lowered the user logger with caplog to see these messages now assert them with pytest.warns.
fermi2D documented verbose but never called set_verbose_level, so its progress output followed whatever level the user logger last had. It now calls it first, as dosplot, unfold and FermiHandler do.
…rness CLAUDE.md names the rule and tests/test_user_warnings.py as its enforcer. verify_steps no longer lowers the user logger, which now carries no warnings; it records each step's UserWarnings in summary.json instead.
…e probe - fs_plot and fermi2D raised their #281 warnings with warnings.warn and stacklevel=2, which blames a pyprocar line when FermiHandler is the caller. They now use warn_user like every other site. - LobsterParser probed the default DOSCAR.lobster and lobsterout in __init__ and warned when either was absent, so a bands-only run warned on every load. The probe logs at debug; ebs and dos warn when they return None, as Siesta's ebs does. - UserFriendlyFormatter styled WARNING and ERROR records the user logger no longer carries; it is gone. - The verbose test reads caplog instead of a hand-written handler.
Warnings raised inside a functools.cached_property name functools.py:998 instead of the user's line. The new user_warning helper asserts the warning's file, and every pytest.warns(UserWarning) test now uses it. BandStructure2DHandler gets the bandsplot fermi-not-set test.
The check now follows annotated and plain aliases, getLogger(name=...), an imported getLogger alias, a logger imported from another module, tuple targets and .log() at WARNING or above. In tests it also flags caplog levels given the logger by position, setLevel on the user logger, and pytest.warns(UserWarning) without the line check. A raw warnings.warn in pyprocar/ fails it: clusters.py:279 is the live case.
…ib wrappers skip_file_prefixes skipped only pyprocar/, so a warning raised inside a functools.cached_property named functools.py:998. warn_user now walks the frames itself past pyprocar and the standard library (not site-packages) and calls warn_explicit with the first caller frame. Clusters.hydrogenate and BandStructure2DHandler's fermi-not-set message now go through warn_user too.
… and aliased warnings calls
…catch aliased warnings calls
…ted code and repeats
…and names a thread's caller
…he caller's line
305023e to
5796327
Compare
…utput Every zone build called spglib.delaunay_reduce, which warns on each call while spglib's process-wide OLD_ERROR_HANDLING is on. Users saw the DeprecationWarning on every Fermi-surface plot, and #294's FermiHandler line test recorded it. The call now ignores exactly that message; the None check below it is the error handling spglib asks for.
…warn_user #294 removed user_logger from the Abinit parser and made warn_user the only channel for warnings a user must see, so the merge left a NameError at io/abinit/parser.py and a raw warnings.warn in io/vasp/parser.py. The Abinit test now asserts the warning names its own line.
…e every parser its orbital names (#298) * test(core): projections whose axes disagree with bands, total or structure are rejected Refs #293 * fix(core): check projection axes against the bands, total DOS and structure check_projected_layout compared only the number of axes, so swapped spin and atom axes passed. It now compares the leading axes with the bands or total DOS, the atom axis with the structure, and requires 1, 2 or 4 spin channels. Non-collinear projections may go with one band channel, as the QE parser stores them, or four, as VASP and Abinit do. Refs #293 * test(qe): non-collinear band structures carry total, Sx, Sy and Sz per orbital Refs #293 * fix(qe): give non-collinear band structures total, Sx, Sy and Sz per orbital projwfc.x projects a spinor run onto |l j m_j> (spin-orbit) or |l m s_z> states. The parser summed the j amplitudes into 32 slots on one spin channel and could not read s_z states. It now writes each shell in the real (l, m) harmonics and spin up/down with QE's own spinor, sph_ind and rot_ylm coefficients, and stores total, Sx, Sy and Sz per orbital. Both QE band structures and DOS now pass projwfc.x's orbital names. Refs #293, #219, #220 * test(io): every parser names the orbitals it projects Refs #293 * fix(io): pass the orbital names each parser projects VASP and Abinit read the names from the PROCAR header instead of cutting a fixed list, so a PROCAR that pyprocar.filter rewrote keeps its o0 column name. The Abinit, Elk and Lobster DOS now name their orbital columns too, so check_projected_layout compares them. Refs #293 * test: type the layout and QE spinor test inputs for basedpyright Refs #293 * refactor(qe): parse projwfc states into a SpinorState before the spinor transform Also format and lint the #293 changes. Refs #293 * docs(claude): state what check_projected_layout now enforces Refs #293 * style(abinit): name the angular momentum ang Refs #293 * test(abinit): a non-collinear DOS carries total, Sx, Sy and Sz Refs #293 * fix(abinit): give a non-magnetic spinor DOS total, Sx, Sy and Sz channels Abinit's DOS_AT files hold no magnetization components. With nspden 1 the spin-resolved DOS is zero by time reversal, so the parser adds three zero channels. With nspden 4 it keeps the total and warns, since the files cannot give the spin components. Refs #293 * refactor(io): simplify the #293 parser changes and pass the structure to every DOS - QE spin-orbit DOS names reuse OrbitalIndexer.soc_label, the format the label builder already renders. - Abinit DOS names are a constant: the kept lm columns are a fixed slice. - Procar.n_orbitals counts the header names instead of rescanning. - The spinor transform uses a matrix product and adds in place. - The QE, Abinit and Elk DOS pass their structure, so the atom axis is checked against it. Refs #293 * docs(verify-pyprocar): record the QE non-collinear projection end state Refs #293 * test: filtered PROCARs load, group rows and name orbitals as their header does An atom-filtered PROCAR holds one row per group of atoms, so it loads, plots each group, labels it by its row and refuses species selections. An orbital-filtered PROCAR labels its columns o0, o1 as its header does, and a single orbital selected by name raises whichever spelling the header uses. Refs #293 * fix(vasp): load a PROCAR filtered by atoms as groups of atoms and label filtered orbitals by name pyprocar.filter(atoms=...) writes one row per group of atoms, so the PROCAR has fewer rows than the POSCAR has atoms and check_projected_layout rejected it. The VASP parser now passes atom_groups, the number of PROCAR rows, when the counts differ. The layout check compares the atom axis with that count, so an axis swap still raises. Atom indices select groups, a selection with no atoms sums every group, and species selections raise, because a group can hold atoms of several species. The structure keeps the lattice and the symmetry operations, so Fermi surfaces unfold as before. Selection labels used the shell letter s for orbital 0 before they read the parser's names, so a filtered PROCAR's o0 column read (s). A shell letter now stands for orbitals only when their names make up that whole shell. Refs #293 * fix(scripts): raise a clear error for a single orbital selected by name orbitals accepts indices and the shell names s, p, d and f. A single orbital name such as x2-y2 or dx2, which VASP spells differently by version, raised KeyError. It now raises a ValueError that names what orbitals accepts. Refs #293 * chore(basedpyright): drop the two resolver comparisons the atom_groups change made necessary * docs(filter): say what the rows and columns of a filtered PROCAR mean when plotted Refs #293 * test(scripts): a shell name selects the columns a filtered PROCAR's header names Also copy only the four files the VASP parser reads and parse the unfiltered PROCAR once per module. Refs #293 * fix(scripts): resolve shell names from the orbital names, as labels do orbitals=['p'] and overlay_orbitals used the fixed table s=0, p=1-3, d=4-8, while labels now read the parser's names. Both now take shells from orbital_shells, so a shell name selects the columns its names make up and raises when no whole shell is there. unfold resolves species names through the selection resolver, as bandsplot does, so an atom-filtered PROCAR refuses them. Refs #293 * test(scripts): a shell letter selects the column a filtered PROCAR names by it Refs #293 * fix(scripts): a column named s, p, d or f is that shell for selections Elk's task 21 and pyprocar.filter(orbital_names=['s','p','d']) write one column per shell, named by its letter. orbitals=['d'] picked columns 4-8 there (IndexError, or a wrong sum when the columns existed). It now picks the column named d, and overlay_orbitals draws one curve per such column. Refs #293 * docs(verify-pyprocar): record the filtered PROCAR end states Refs #293 * test: mark the accepted spin layouts as guarding existing behaviour Refs #293 * test: a selection without atoms sums every row, a part shell is no shell, filtered IBZ PROCARs refuse to unfold A DensityOfStates without a structure (every Lobster DOS) gave zeros for compute_projected_sum and compute_magnetization without atoms, and dosplot parametric coloured a Lobster DOS 0. Columns py and pz must not form a p shell. fermi2D on an atom-filtered PROCAR of irreducible k-points failed with an IndexError once ibz2fbz started permuting atoms (#299). Refs #293 * test: an empty atom selection raises instead of summing nothing Refs #293 * fix(core): a selection without atoms resolves to every atom row With no structure the resolver returned atoms=(), which the band and Fermi surface callers read as every row but DensityOfStates passed on as no rows, so a Lobster DOS (no structure) summed to zero. The resolver now takes the source's row count and always returns explicit row indices, and every caller passes them as given. An empty atom selection raises. Refs #293 * fix(ebs): refuse to unfold an atom-filtered PROCAR from irreducible k-points ibz2fbz (#299) permutes atoms under each symmetry operation, so a PROCAR whose rows are groups of atoms failed with an IndexError in fermi2D and every other mesh. The file does not record which atoms a row holds, so no permutation of its rows is known to be right. It now raises an error that says to filter a full k-grid calculation or select atoms in the plot. Refs #293 * chore: annotate the resolver row count and type the filter groups in the test Refs #293 * test: name n_atoms in the guard reason of the selection label test Refs #293 * test: keep the guard reason within the line limit Refs #293 * refactor: check atom groups before ibz2fbz copies any property, and reuse the test helpers The atom-group guard ran inside _turn_projections, after ibz2fbz had already replaced the properties, and refused every symmetry operation. It now runs first and refuses only operations that move an atom. The fermi2D test builds its filtered calculation with _filtered_calc, and the DOS tests import VASP_ORBITALS instead of copying it (simplify review). Refs #293 * test: an empty spin selection raises instead of summing nothing The resolver returned spins=(), which band callers read as every spin and DensityOfStates as none. Refs #293 * fix(core): an empty spin selection raises, as an empty atom selection does Refs #293 * fix: send the abinit spinor-DOS and VASP atom-group warnings through warn_user #294 removed user_logger from the Abinit parser and made warn_user the only channel for warnings a user must see, so the merge left a NameError at io/abinit/parser.py and a raw warnings.warn in io/vasp/parser.py. The Abinit test now asserts the warning names its own line.
…utput Every zone build called spglib.delaunay_reduce, which warns on each call while spglib's process-wide OLD_ERROR_HANDLING is on. Users saw the DeprecationWarning on every Fermi-surface plot, and #294's FermiHandler line test recorded it. The call now ignores exactly that message; the None check below it is the error handling spglib asks for.
Why
pyprocar/utils/log_utils.pysets theuserlogger to ERROR, so all 62user_logger.warning(...)calls inpyprocar/printed nothing in a default call. A user never saw bandsplot's "fermiis not set", FermiSlicePlotter's missing field names, or a parser saying it guessed a unit convention.fermi2Dalso ignored itsverboseargument. This PR applies the rule the operator chose: a message the user must see is aUserWarningthat names the user's line, and theuserlogger keeps only verbose progress.What changed
warn_user()inpyprocar/utils/log_utils.pywalks the call stack past frames inpyprocar/, the standard library,<frozen ...>modules and generated<string>code (a dataclass__init__). It then callswarnings.warn_explicitwith the first frame left, its module name and its__warningregistry__. The warning names the user's own line at any depth: through a helper, afunctools.cached_property,FermiHandler, or a module import. Third-party frames in site-packages count as callers. In a thread, whose stack holds no caller frame, it names the nearest frame outsidepyprocar/: thefn(*args)line ofconcurrent/futures/thread.py, orThread.run.warn_userhas 65 call sites:info/debug. Lobster's default-file probe is one of the 6, and itsebsanddosnow warn when they returnNone(2 sites).warnings.warncalls: two from fix(fermi): fermi2D spin selection, exact unfolded k-grid and van Alphen follow-ups #281 (fs_plot,fermi2D) andClusters.hydrogenate(pyposcar/clusters.py:279).warnings.warncalls that fix(ebs): make ibz2fbz unfold magnetic groups, phases, atoms and orbitals correctly #299 added toibz2fbzinpyprocar/core/ebs.py(time-reversal fill-in, droppedprojected_phase, unrotated orbitals). Two of them usedstacklevel=3and namedebs.py:1669when the mesh constructor runsibz2fbz.BandStructure2DHandler.plot_band_structure, which sent bandsplot's "fermiis not set" message touser_logger.info.QEParser.symmetries_xmllogged "No rotations found" withuser_logger.warning. It is nowdebug, the same decision this PR made forQEParser.rotations: onlyibz2fbzuses the rotations, and it logs its own skip.fermi2Dcallsset_verbose_level(verbose), asdosplot,unfoldandFermiHandlerdo.tests/test_user_warnings.pyenforces the rule. TheCLAUDE.mdrow says exactly what it flags:pyprocar/:.warning,.error,.critical,.exception,.fatal,.warn, or.logat WARNING or above, called ongetLogger("user"), on a name bound to it in the same function or module, on aself.attribute bound to it in the same class, or on a name imported from another module that binds it (also through a package__init__). Alsowarnorwarn_explicitfrom thewarningsmodule, throughimport warnings as worfrom warnings import ..., outsidelog_utils.py.tests/:caplog.at_level/set_levelwith logger"user",setLevelon the user logger, andpytest.warns(UserWarning, ...)outside the helper.tests/utils/user_warning.pywrapspytest.warnsand also asserts that the warning names a line in the calling test file. Every warning test uses it, including fix(ebs): make ibz2fbz unfold magnetic groups, phases, atoms and orbitals correctly #299's threeibz2fbztests. The verify harness recordsUserWarnings per step.How warn_user chooses where a warning points (round 3)
Round 1 (
skip_file_prefixes=(pyprocar/,)) namedfunctools.py:998under a cached property. Round 2 (frame walk pluswarn_explicit(..., module_globals=...)) raisedValueError: Module globals is missing a __spec__.loaderin IPython and Jupyter, and added aDeprecationWarningto every warning in a plain script. Both rounds failed at the hand-off from our frame choice to CPython, not in the frame choice. So I measured every hand-off I could find against one matrix before choosing.The matrix runs each candidate as a separate interpreter on generated user scripts that call real pyprocar sites (
KPath,QEParser.alat,FermiHandler.plot_fermi_surface), plus a fake library for the<string>and import-time cases. Rerunnable:matrix.py WORKTREE OUTDIR [candidate ...]withcandidates.py, kept with the round's evidence.module_globals, old walkmodule_globals, new walk (chosen)stacklevelstacklevelskip_file_prefixesof walked fileswarnings.warn(message, UserWarning, stacklevel=n)and lets CPython build the context. It works only ifncounts frames the way CPython does. CPython skipsimportlib._bootstrapframes without counting them. The naive count sends an import-time warning tosys:1, silently. The corrected count copies that private rule into pyprocar.skip_file_prefixesentry against the filename minus its last character (PyUnicode_Tailmatch(filename, prefix, 0, -1, -1)), so a full filename never matches. Trimming each name works, but it depends on that quirk.warn_explicit: filename, line, module name and registry, which are its documented parameters. CPython'swarnings.warnpasses nomodule_globalseither, so the source lookup, the registry, the filters and-Whandling are the same code path. (a) and (b) give identical results in every scenario. (a) has no hidden contract with CPython, so I chose it.cli_W_errorrow usespython -W error. On any head,import pyprocaritself fails under-W errorwhen it compiles its sources, becausesplash.py,scriptDosplot.pyand others hold invalid escape sequences (aSyntaxWarning, raised asSyntaxError), anddownload_examples.pysetsHF_HUB_ENABLE_HF_TRANSFER, which makeshuggingface_hubraise aDeprecationWarning. Both exist ondev. The matrix runs it with a precompiled pycache and the Hugging Face warning ignored. The repo tests use an in-scriptsimplefilter("error")after the import instead.Scope
user_logger.warningsite. A site warns when the result differs from what the user asked for or a member comes backNone. It logs at debug when an optional source is absent and nothing degrades.FermiHandler's "No Fermi surface found" now goes throughwarn_user, but no public call reaches it.FermiSurface.from_ebsfirst raisesValueError: No Fermi surfaces were generated. The test pins the loud error and is markedguards_existing_behaviour.pyprocar/io/abinit/parser.pychanges only where User-facing warnings are hidden by the ERROR-level user logger #284 needs it. fix(core): check projection axes against bands and structure, and give every parser its orbital names #298 adds auser_logger.warningthere. Whichever of fix(warnings): show user-facing warnings through warnings.warn #294 and fix(core): check projection axes against bands and structure, and give every parser its orbital names #298 merges second converts it.except Exception: warn; return Noneblocks still swallow the exception. They now warn visibly. Making them raise changes behaviour, so it is a separate issue.Blast radius
Users now see warnings that were always meant for them, in scripts, IPython and Jupyter. In a plain script a warning prints once per call of
bandsplot,dosplotorunfold, even from the same line in a loop: matplotlib'sAxis.set_ticklabelsenterswarnings.catch_warnings(), and that resets the warning registry. Other calls print once per calling line, the default Python rule. Code that setlogging.getLogger("user")to WARNING to see these messages now gets them fromwarningsinstead. Under anerrorfilter the user gets theUserWarningraised from their own call.Verification
Real Jupyter kernel (
jupyter_client,pyprocar.bandsplot(code='vasp', dirname=<copy of data/examples/bands/non-spin-polarized>, show=False)):ERROR ValueError: Module globals is missing a __spec__.loader.bandsplot returned Axes, and.../ipykernel_2574016/1397239802.py:4: UserWarning: \fermi` is not set! ...` names the cell's line.ipython -cwith aKPathcall that has one name for two segments (__spec__ = None | __loader__ = None):RAISED ValueError Module globals is missing a __spec__.loader.recorded: [('UserWarning', '<ipython-input-1-ee06d37d50cd>', 1)].Python 3.12, 3.13 and 3.14 (
pixi exec -s python=3.1x,log_utils.pyloaded on its own with a fake library): direct call, cached property, dataclass__post_init__, import time, notebook globals, script globals, error filter, once-per-line repeat, executor thread and plain thread. All pass on each version.Red then green, new tests (
tests/pyprocar/utils/test_warn_user.py). On the round 2 head, 8 of 11 fail: the notebook cell (ValueError), script globals (extraDeprecationWarning), the error filter and the subprocess script (DeprecationWarningraised instead of theUserWarning), both threads (threading.pyself._bootstrap_inner()), and generated code (<string>:4). The other 3 (helper,FermiHandler, once-per-line) and the import-time test fail ondev, where noUserWarningis raised. All pass on this head.Mutations of
warn_user(8 warning test files, 252 tests):registry=Nonemodule_globalsback<string><frozen ...>Red then green, the check (
test_the_checks_flag_each_loud_call_and_each_lowered_level). On the new synthetic lines, the round 2 resolver flags24,36and39(a function-localgetLogger(__name__),self.logbound to a package logger in another class, and a lambda argument) and misses38(a logger re-exported throughpkg/__init__.py). The raw-call check finds[3, 4]of[3, 4, 7, 8, 10](it missesimport warnings as wm; wm.warn,warnings.warn_explicitandfrom warnings import warn_explicit). This head flags exactly the expected lines.Red then green, fix(ebs): make ibz2fbz unfold magnetic groups, phases, atoms and orbitals correctly #299's tests. With the helper,
test_phases_over_orbitals_without_real_harmonic_names_are_dropped_with_a_warningandtest_the_unrotated_orbital_warning_lists_the_orbitals_in_numeric_orderfail ondevwithgot ['UserWarning at pyprocar/core/ebs.py:1669']. The time-reversal test passes ondevbecauseibz2fbzis called directly, so it is markedguards_existing_behaviour.Red-green job. 39 added or changed tests. 32 fail on base 5884b80, and 7 pass on base, each marked
guards_existing_behaviourwith its reason.red/green: ok.Gates on 305023e (rebased onto
dev5884b80):pytest -m "not data" -n 41952 passed, 2 skipped.-m data -n 4382 passed, 1 skipped. basedpyright 0 errors, 0 warnings. The ruff new-violation gates are ok. F821/F822/F823/NPY201 are clean. CI run 37232173717 passed on 305023e.Closes #284