Skip to content

Symbolic differentiation of scalar/tensor expressions, with series substitution and Hartree-Fock derivatives - #812

Draft
zhihao-deng wants to merge 25 commits into
masterfrom
zhihao/feature/sym_deriv
Draft

zhihao-deng wants to merge 25 commits into
masterfrom
zhihao/feature/sym_deriv

Conversation

@zhihao-deng

Copy link
Copy Markdown
Contributor

This draft adds symbolic differentiation of any order, respecting the variable's permutational symmetry, adjoint and protoindices.

Differentiation engine SeQuant/core/deriv

deriv::diff(E, {x_1, ..., x_n}) returns ∂ⁿE/∂x_1…∂x_n, and deriv::at_zero(E, {x_1, ..., x_n}) returns E with the variables set to zero.

  1. Set up. Expand products over sums (symmetrizers stay factors), run every check, and rename the summed indices
  2. Differentiate. Apply the product rule over the factors of each term. The derivative of a tensor of x's label by x is a product of Kronecker deltas, one per slot. A delta on a summed index is summed away at once by renaming that index to the variable's; a delta on an external index stays as a factor (make_kronecker, never an overlap: a derivative pairs an element with itself in any basis).
  3. Clean up with rapid_simplify, which keeps every index name.
  • Differentiation commutes with SeQuant's symmetrizers, so the permutations of like slots are left to one  or Ŝ factor on the result, and the symmetrizers of E are never expanded.

Generators: SeQuant/domain/mbpt

  • mbpt::series(expr, label, strength, order) replaces every tensor of a label by its Taylor series in a strength.

The code has been tested on generating HF nuclear gradient

  • mbpt::hf::rotated_energy and mbpt::hf::energy give the Hartree-Fock energy under an orbital rotation κ̂.
  • CPHF is generated and verified symbolically
// orbital gradient and Hessian
const auto E = mbpt::hf::rotated_energy(2);
const auto x = deserialize(L"κ̂{a_1;i_1}:A-N-S");
const auto y = deserialize(L"κ̂{a_2;i_2}:A-N-S");
deriv::at_zero(deriv::diff(E, {x}), {x});  // f{i_1;a_1}
deriv::diff(E, {x, y});                    // g{i_1,i_2;a_1,a_2}

// nuclear gradient: the orbitals follow the displacement, κ̂(ε) = ε κ̂¹ + ...
const auto ε = ex<Variable>(L"ε");
const auto En = mbpt::hf::orthonormalized(mbpt::hf::energy(1), ε, 1);
const auto Et = deriv::at_zero(mbpt::series(En, L"κ̂", ε, 1), {x});
deriv::at_zero(deriv::diff(Et, {ε}), {ε});

Brillouin condition, stationarity are not applied since the engine only generates symbolic expression. It is user's responsibility to apply physical condition.

@evaleev

evaleev commented Nov 23, 2026

Copy link
Copy Markdown
Member

I reviewed this at 15ac96d207 and pushed four fix commits on top (fast-forward, 15ac96d207..971ef275de). Probing diff/at_zero with about 25 inputs outside the test suite, checked with the PR's own numerical judge, turned up no wrong derivative.

Pushed

Commit What
b3f4b3b1e4 Default member initializers for the test structs that designated initializers leave partly unset. -Werror=missing-field-initializers under g++-14 was failing every Linux job; besides evaluator.cpp, identities.cpp and test_deriv_identities.cpp had the same error (ninja stopped before reaching them).
3b6cb613b4 diff and at_zero throw on a null expression or variable instead of dereferencing it.
0d89ec99a4 A scalar Variable no longer triggers "an index of the function stands in more than two slots": the scalar rule reads no index, so a term with a hyperindex (THC/CP) can be differentiated by a strength. Tensor variables are unchanged. One consequence: diff(E, {x, t}) can succeed where diff(E, {t, x}) throws, when a hyperindex term lacks x; both accepted results are correct.
971ef275de The Valgrind CI step also runs the deriv rule and series tests (13 s natively in Debug). The job previously ran unit_tests-sequant only.

Verified locally with Apple Clang: 2863 assertions in Debug, 7933 in Release (long mode). All deriv test files pass a GCC 15 -Wall -Wextra -Wpedantic -Werror syntax check. Not verified: the new Valgrind step itself, which builds with SEQUANT_ASSERT_BEHAVIOR=IGNORE; a deriv test that depends on an assert throwing could fail there.

Left for the author

  1. Commit hygiene (before leaving draft). 15ac96d207 mixes a core refactor (utility/indices.cpp, wick_extended.cpp), the κₒ→κ̂ relabel and registry change, test trimming and docs in one commit; AGENTS.md asks for one logical change per commit. The message of f7fd33a645 still says the rotation is labelled κₒ.

  2. The judge never samples the diagonal of the variable in sampling mode. In for_each_sampled (tests/unit/deriv/evaluator.cpp), a label avoids every value an earlier label of its own group has taken, so two slots of the variable over one range are never equal once the element count exceeds sampling.count. Reproducer: check_rule(L"h{p_1;p_1}:N-N-N t{a_1;i_1}:N-N-N", L"h{p_3;p_4}:N-N-N", L"") fails with nonzero == 0, although diff returns the correct t{a_1;i_1} δ{p_4;p_3}; the trace alone passes because it is enumerated exhaustively. This is where the stabilizer factor of the convention matters. A second sampling pass that lets a label repeat an own-group value fixes it, but shifts the pinned "nonzero read by" counts at test_deriv_identities.cpp:237 (upward only) and breaks a case at test_deriv_judge.cpp:176, so I did not push it.

  3. Like terms are not collected, even identical ones. diff(B{p_1;p_2;i_1} B{p_2;p_1;i_1}, B{p_3;p_4;i_3}) returns B{p_4;p_3;i_3} + B{p_4;p_3;i_3}, and diff(x x^(2), x) returns x^(2) + 2 x^(2). Each further diff pays for the uncollected size, and simplify is not a substitute because it renames the indices Â/Ŝ carry. Merging summands that are equal as written would be cheap and keep every index name.

  4. Diagonal convention wording. The user guide states that the result is twice the derivative at an element its own symmetry partner, but deriv.hpp calls the result "the derivative with respect to the independent elements". For a bra-ket symmetric h{p_3;p_4} over one space that is off by 2 on the diagonal; the header should say so in the same sentence.

  5. κ̂ in both default registries. It is added to make_minimal_registry() and make_legacy_registry() for every user, for one model. Consider registering it where mbpt::hf needs it, or documenting why it belongs in the defaults.

  6. Readability of deriv.hpp. The contract of diff is one 40-line paragraph that relies on terms defined only in the developer guide ("spelling", "like slots", "meets"). A short definition of each, or a pointer to the developer page, would let the header stand alone.

  7. CI coverage. The closed-shell traced, CSV traced and open-shell identity families are compiled out in every Debug build and under SEQUANT_SKIP_LONG_TESTS, so only the plain Release jobs run them.

@evaleev

evaleev commented Nov 23, 2026

Copy link
Copy Markdown
Member

I pushed five commits on top of 971ef27 (head now db2a860). They add what analytic CCSD(T)/F12 gradients need from deriv::diff.

Additions

  • 3fa37ef accepts a column-symmetric variable with at most one slot per side, such as ε{;a} or ε{i;}. Column symmetry permutes nothing there.
  • 06b1aa3 adds two rules:
    • Power rule: a leaf of the variable under a TensorPower differentiates elementwise, e·x^(e−1).
    • Chain rule: a new overload diff(E, variables, definitions) takes a list of ResultExpr. A leaf whose label and ranks match a head, alone or under a TensorPower, is differentiated through its definition, recursively through nested definitions. That covers broadcast sums such as D{i,j;a,b} = ε{;a}+ε{;b}−ε{i;}−ε{j;}. So E_(T) ~ Σ L·R·D⁻¹ can be differentiated by ε without D (which is Symm) being a variable.
  • 548a2a8 treats an index in three or more slots as summed (a Hadamard product under a contraction) instead of rejecting it. diff() passes each variable's indices to the later derivatives as known externals, because the derivative of a Hadamard product holds them in two slots.

Fixes found in review

  • 337c646 fixes how definitions are checked and instantiated:
    • a head may use the variable's index names;
    • an unexpanded expression is expanded first;
    • the protoindices of renamed summed indices follow the rename;
    • rejected now: a defined leaf with protoindices, a head that repeats an index, and an expression with a free index its head lacks.
  • db2a860 makes the indices of Â/Ŝ always external. Before, diff(·t·D⁻¹, t) renamed them away because two other factors hold them. This predates the commits above; the power rule only makes the case easier to hit.

Tests and docs

  • New test cases: deriv/rules/powers-and-definitions and deriv/rules/hadamard, plus regression tests for the review findings.
  • The elementwise results need AssertStrictBraKetSymmetry::No.
  • The test evaluator reads an index in three slots as free, so Hadamard sums are checked through Euler's identity with require_same(..., free = {}) instead of compare_tangents.
  • The user guide (new section "Powers and definitions"), the developer guide, the header docs and the compiled example (snippet-12) are updated.
  • All 21 test cases of unit_tests-sequant-deriv pass.

@ajay-mk ajay-mk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

General comment: several names here are not self-explanatory: judge, family, own-equations, spelling. Could they say what they check, e.g. numerical_check, cc_variants?

run: |
valgrind --error-exitcode=1 --leak-check=full ./tests/unit/unit_tests-sequant '~[valgrind_skip]'
# the rule and series tests of SeQuant-deriv; its identity and finite-difference tests take too long here
valgrind --error-exitcode=1 --leak-check=full ./tests/unit/deriv/unit_tests-sequant-deriv '[rules],[series]~deriv/series/cc-lagrangian'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do these tests need their own executable? They could go into unit_tests-sequant as a unit_tests-sequant-deriv-obj, like the other modules. Then the slow tests could be tagged [valgrind_skip], and this extra CI line would not be needed.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The slow tests should use the existing SKIP_LONG_TEST macro mechanism, unless they are fine in Debug build and only problematic for Valgrind

mbpt::CC cc{2};
auto L = mbpt::op::ref_av((1 + mbpt::op::Λ(2)) * cc.hbar(),
{.connect = cc.hbar_connections()});
simplify(L);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This simplify call is probably not needed. ref_av should return a simplified version.

}

{
// start-snippet-2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the ease of reading (since this is part of documentation), I suggest the following pattern for this snippet and elsewhere:

const auto t1 = deserialize(L"t{a_2;i_2}:N-N-N");
const auto expr1 = deserialize(L"f{i_1;a_1}:N-N-N t{a_1;i_1}:N-N-N");
const auto result1 = deserialize(L"f{i_2;a_2}:N-N-N");
require_equivalent(diff(expr1, {t1}), result1);

Comment on lines +117 to +121
auto registry = mbpt::make_min_sr_spaces();
std::vector<std::wstring> keys;
for (const auto& space : *registry) keys.push_back(space.base_key());
for (const auto& key : keys)
if (!key.empty()) registry->field(key, Field::Real);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: not necessarily part of this PR, but logic for setting field is a repeating pattern in tests and example. We should introduce a helper or utility function.

/// Symmetrizers are never expanded: those of @p E stay factors, and that of
/// x is put on the result as a factor.
/// @throw Exception for a null argument and for an input that is rejected
[[nodiscard]] ExprPtr diff(const ExprPtr& E,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think calling this diff is okay and I know that sympy also uses diff. But there is also vimdiff, git diff etc which usually means difference.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We also have exprdiff in SeQuant so calling this diff is kinda confusing (given that an actual diff utility exists as well)

/// @p order above 9, an mbpt::Operator or a Variable labelled @p label in
/// @p expr , a leaf of @p label under a TensorPower, or a tensor in @p expr
/// labelled like a coefficient p⁽ᵏ⁾ (or its adjoint), 1 ≤ k ≤ @p order
[[nodiscard]] ExprPtr series(const ExprPtr& expr, std::wstring_view label,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we call this taylor_series? Just series is a bit ambiguous?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also like taylor_series more than just plain series. In mathematical literature, the act of approximating something as a Taylor series is often referred to as expanding (as a series) but that is even more ambiguous in the context of SeQuant. Maybe taylor_expansion?

Comment thread AGENTS.md
Note that "core" is both the source directory (`SeQuant/core/`, which feeds
`symb`, `eval`, `optimize` and `export`) and the small umbrella target. Backend
`symb`, `deriv`, `eval`, `optimize` and `export`) and the small umbrella
target, which links all of those but `deriv`. Backend

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the rationale behind keeping deriv out of core? deriv depends only on SeQuant-symb and it could even be part of SeQuant-symb. That would also drop this exception, the extra CMake and config entries.

}

{
// start-snippet-7

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This should be moved down in the file or renumbered.

@ajay-mk ajay-mk added the feature New feature label Nov 23, 2026
@evaleev

evaleev commented Nov 23, 2026

Copy link
Copy Markdown
Member

Correction: db2a860 accidentally overwrote doc/user/guide/differentiation.rst with the developer page (a file-copy mistake while splitting commits). fcdba5d restores the user guide as of 337c646, plus the one sentence db2a860 was meant to add. The developer page and all code were unaffected.

@Krzmbrzl Krzmbrzl left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mostly only read and reviewed (via) the docs

Comment on lines +7 to +8
symbolic form. Both are declared in ``SeQuant/core/deriv/deriv.hpp`` and built as the CMake target ``SeQuant::deriv``,
which ``SeQuant::SeQuant`` links (``SeQuant::core`` does not).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does core not do?

Comment on lines +24 to +25
derivative of any order. A variable is a scalar :class:`sequant::Variable` or a single tensor, a *leaf* of the
expression tree: one :class:`sequant::Tensor`, not a product or a sum, and neither a symmetrizer nor a Kronecker delta.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is a leaf in the expression tree different from the requirement of being a Variable or a Tensor? Just naming these two seems exhaustive together with the exception of symmetrizers and Kronecker deltas.

Comment on lines +30 to +35
For a tensor variable, that factor is an occurrence of it (defined below), whatever its index names, that lies inside
the variable: in a spelling of the variable that it matches, each of its slots runs within the index space of the
spelling's slot. A leaf that holds elements of the variable and elements outside it, such as ``k{p_1;i_1}`` for the
variable ``k{a_2;i_2}``, would be neither zero nor unchanged, and is rejected. With several variables, a leaf must lie
inside one of them: ``k{p_1;i_1}`` is rejected for the variables ``k{m_2;i_2}`` and ``k{e_3;i_3}`` together, although
together they hold all of its elements.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand what this paragraph is describing 👀

Comment on lines +37 to +38
A scalar variable is complex: ``x`` and its adjoint ``x^*`` (:func:`sequant::adjoint`) are independent variables, so
the derivative by ``x`` treats ``x^*`` as a constant.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about complex-conjugate tensors?

The docs should mention that the presence of a quantity and its complex-conjugate in the same expression makes the expression non-holomorphic and that what we are computing are so-called Wirtinger derivatives.

Comment on lines +49 to +50
In a term of ``E`` (a product of factors), an index is *summed* if it stands in exactly two slots of the term's
factors, not counting the symmetrizers ``Â`` and ``Ŝ``; every other index of the term is *external*, including one

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should not use this definition. This does not hold in general (think of THC expressions). Named/External indices must be given explicitly. Probably the easiest way to enforce this would be to restrict these functions to work on ResultExpr objects only.

``diff`` takes the dependence on a variable from ``E`` as written. To differentiate with respect to the strength
:math:`\varepsilon` of a perturbation, write every quantity that depends on it as its series in :math:`\varepsilon`,
differentiate, and set :math:`\varepsilon = 0` with ``at_zero``. The :math:`n`-th derivative at zero is :math:`n!`
times the coefficient of :math:`\varepsilon^n`. The example writes the series by hand; ``mbpt::series`` writes it for

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does series live in mbpt? It seems a to perform a contex-independent (purely mathematical) series expansion.

kinds:

- **What a variable is.** A variable is a ``Variable`` or a single tensor leaf, not a symmetrizer or a Kronecker delta,
and a tensor variable puts each index in one slot only.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is that required? Wouldn't the machinery also work if I were to take the derivative w.r.t. a matrix's diagonal?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be good if we found a different term than variable for the thing we perform the derivative with. I find this rather confusing with the Variable type.


How ``diff`` computes the result is described in :doc:`the developer guide </developer/differentiation>`.

Series substitution

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could/should be its independent documentation as it seems useful in its own right. Maybe the same applies to the at_zero function 🤔

Comment thread tests/unit/CMakeLists.txt
build_test_as_needed(unit_tests-sequant "sequant/unit" TEST_NAMES)
endif()

# symbolic differentiation (SeQuant-deriv) has its own executable

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why?

zhihao-deng and others added 23 commits December 4, 2026 18:42
A new library, SeQuant::deriv, on top of SeQuant-symb. deriv::diff(E,
variables) differentiates an explicit expression by each variable in
turn; this commit handles a scalar Variable (x and x^* are independent).

The result is cleaned up with rapid_simplify, not simplify: simplify
renames or reorders the indices a symmetrizer carries, and in a
derivative those are free indices.
A derivative can be written in many equivalent ways, so the tests do not
rely on its text alone. The judge gives every tensor random data with
exactly its declared symmetry and compares the result, element by
element, with the exact change of the function when one element of the
variable is raised. It shares no code with the engine, and its own tests
show that each of its checks can fail.
The variable may now be a tensor leaf, read here as an array without
symmetry.

The derivative of a leaf by the variable is a Kronecker delta for every
label the two pair, never an overlap: a derivative pairs a coordinate
with itself, whatever the basis. A protoindex labels the element just as
a slot index does, so it is paired as well. Where the leaf's label is
summed the delta is contracted away by renaming; an external label keeps
its delta.

All pairing of a leaf's indices with the variable's is in one function,
elementary().
A symmetric variable has fewer independent elements than positions, so
the derivative by an independent element is the positional gradient
summed over the variable's symmetry operations. Differentiation commutes
with that sum: for slots that are alike it is SeQuant's  or Ŝ, put on
the result as one factor and never expanded. Â and Ŝ are normalized,
hence the factor counting the permutations.

With this convention the derivative of a coupled-cluster Lagrangian by a
multiplier is SeQuant's amplitude equation with no extra constant.
A symmetrizer only permutes slots that are alike. The variable's other
operations (permuting slots over different spaces, exchanging bra and
ket) write its indices in another slot order, a spelling. A tensor of
the function over a larger space holds the variable's elements in
several of these orders: with a bra-ket symmetric h, sum_pq G_qp h_pq
holds h_ia both as h_pq and as h_qp, so its derivative by h_ia is
G_ai + G_ia. The derivative is therefore summed over the spellings, each
with its sign.

Leaves are compared as written, not brought to a canonical slot order
first: canonicalizing a bra-ket symmetric leaf exchanges its bra and
ket, which the symmetrizer on the result would not follow.

Over real spaces a variable and its adjoint hold the same elements, so
the adjoint's spellings are included; over complex spaces x and x^+ stay
independent.
An input the rule cannot differentiate correctly is refused before any
derivative is taken, with a fixed message, rather than detected case by
case afterwards. The rejections are of four kinds: the variable is not a
well-formed Variable or tensor leaf; its symmetry is one a symmetrizer
over like slots cannot express; protoindex lists of the variable or of
one of its leaves do not identify an element unambiguously; the function
is not a valid expression, holds operators, or holds the variable where
the rule does not reach (under a TensorPower, or with a protoindex label
that is not summed).
at_zero(E, variables) drops the terms that hold a listed variable: a
derivative is usually wanted at a reference point, such as zero
perturbation strength.

A leaf that holds elements both inside and outside a tensor variable's
block is neither zero nor unchanged, so it is rejected.
The rule tests pin chosen inputs. These tests run diff over the
equations SeQuant generates for coupled-cluster singles and doubles
(spin-orbital, closed-shell and open-shell; canonical and CSV) and check
identities every correct derivative satisfies: the numerical definition,
the Taylor expansion, the equality of mixed partials, and that the
derivatives of the Lagrangian are SeQuant's own amplitude and λ
equations.

The numbers of checked and of rejected variables are pinned, so a loss
of coverage fails.
A user guide page for deriv::diff and deriv::at_zero and a developer
page on how the engine works. The code samples come from an example that
is compiled and run with the tests.
mbpt::series replaces every leaf of a label (or its adjoint) by its Taylor
series in a scalar or tensor strength, the coefficients labelled by order.
Core replace is not used: it matches leaves of one block of spaces only and
puts an index the replacement adds (a perturbation index) unchanged into
every match, so two perturbed leaves of one term would share it.
mbpt::hf::rotated_energy(order) is <0|e^(-κ) H e^(κ)|0> through the given
order in the rotation κ = K - K⁺, K exciting every reference-occupied orbital
into its complement; its derivatives are the orbital gradient and Hessian.
K is labelled κₒ because κ is core's cumulant label. H is normal ordered, so
the reference energy is not part of the result.
…rmalized orbitals

hf::energy writes the energy under an orbital rotation in h and g;
hf::orthonormalized expands h and g in symmetrically orthonormalized
orbitals as a series in a perturbation strength. In those orbitals the
operators, and so the form of the energy, stay the same at every geometry:
all dependence on the perturbation is in the integrals.
…ences

The second-order forms are too long to write by hand. The reference is the
exact energy of a small model built from the evaluator's own data, differenced
in the perturbation strength and in the orbital rotation; no Hartree-Fock
equation is solved and no term is assumed zero.
The user guide gains mbpt::series and the Hartree-Fock orbital gradient and
Hessian, nuclear gradient and response equation as worked uses of diff and
at_zero, with compiled and checked examples.
…documentation

- core: one unused_label_validator() (utility/indices) names indices apart
  from an expression; extended Wick, the engine's renaming apart and series'
  fresh indices use it. Each keeps its own counter: the engine and series
  draw from Index::make_tmp_index so that separate calls never share a name.
- tests: drop the test that fails once core's open-shell CSV spin tracing is
  fixed; the exclusion and its reason stay with family_models().
- tests: SEQUANT_SKIP_LONG_TESTS (and Debug) runs the identities over the two
  spin-orbital models and the strength-tensor finite differences at one
  value of z and one pair of values; Debug drops from 9.4 min to 2.7 min.
  The identity tests pin the models of the family in either setting.
- tests: check_rule() requires a nonzero element read or a zero derivative.
- tests: the judge names its dummies apart from f's indices too.
- hf: assert that the k-body part of op::H() holds one tensor.
- hf: label the rotation κ̂, which to_latex() renders (κₒ gave \kappaₒ).
- doc: the reorderings of a protoindex list count as operations of the
  variable; at_zero() lists every rejection; AGENTS.md names
  unit_tests-sequant-deriv.
…efault

GCC's -Wextra warns (-Wmissing-field-initializers) where a designated
initializer leaves out a member that has no default member initializer,
and the tests are built with -Werror: evaluator.cpp, identities.cpp and
test_deriv_identities.cpp did not compile with g++-14, which failed every
Linux job. The members of Slot, Factor, Perturbation, Projection, Term,
Family and OwnEquation now have one.
diff() and at_zero() dereferenced a null expression or variable; they now
throw, as mbpt::series does.
… scalar

The external indices of a term decide, for a tensor variable, which labels
are renamed and which keep a Kronecker delta, and finding them rejects an
index in more than two slots. The scalar rule reads no index, so by_one()
no longer finds them for a Variable: a term with a hyperindex, as in a
THC or CP factorization, can be differentiated by a perturbation strength.
For a tensor variable nothing changes.
The valgrind job ran unit_tests-sequant only, so no code of SeQuant-deriv
or mbpt::series was checked there. The rule and series cases take 13 s
natively in a Debug build; the identity and finite-difference cases are
left out as too long under valgrind.
Column symmetry permutes nothing when neither side has two slots, so such a
variable, e.g. an orbital-energy vector ε{;a}, is differentiated as a
nonsymmetric one. Needed to differentiate broadcast-sum denominators by ε.
A leaf of the variable under a TensorPower of exponent e is differentiated
element by element, e x^(e-1); the result is a Hadamard product.

diff(E, variables, definitions) takes a list of ResultExpr: a leaf whose
label and ranks are those of a head, alone or under a TensorPower, stands
for the definition's expression, its slots renamed to the leaf's, and the
chain rule is applied through it (recursively through other definitions).
A definition holds for every element of its head, so a broadcast sum such as
the perturbative denominator D{i;a} = ε{;a} - ε{i;} qualifies: a function of
D⁻¹ can be differentiated by the orbital energies without D being a variable
(D is totally symmetric, which diff does not accept as a variable).
A Kronecker delta that the chain leaves between a summed index of the term
and one of the variable is summed away, as for a leaf of the variable.

Rejected: a head that is not a labeled tensor, has protoindices or the
variable's label; two definitions of one head; a cycle among definitions.
A term with an index in three or more slots was rejected for a tensor
variable. Such an index is summed: it is a Hadamard product under a
contraction, the shape of a perturbative correction L ⊙ D⁻¹ · R or of a
hyperindex of a factorized integral, and renaming it to the variable's label
throughout the term, as for an index in two slots, sums the Kronecker delta
away.

The derivative of a Hadamard product holds the variable's indices in two
slots, where the count alone reads them as summed, so diff() passes the
indices of each variable to the derivatives by later ones as external.
A free index of the function itself must stand in one slot.
- the leaves of a definition are checked with its head renamed apart from
  the variable: a head named like the variable is valid (its names are
  dummies), and an unexpanded expression is expanded first;
- instantiating a definition renames the protoindices of its summed
  indices along with the slots they name;
- a leaf with a definition and protoindices is rejected (its summed
  protoindices would need renaming beyond the definition), as are a head
  that repeats an index and an expression with a free index the head lacks.
An index of  or Ŝ was counted only by the other factors, so an external
index of a residual that two other factors hold, as in the elementwise
residual  D⁻¹ t, was read as summed and renamed to the variable's label,
losing the free indices of the function. The indices of a symmetrizer are
those of the residual, so they are external whatever the other slots.
db2a860 overwrote doc/user/guide/differentiation.rst with the developer
page. This restores it as of 337c646 and adds the sentence that commit
meant to add: an index of  or Ŝ is a free index of the function.
@evaleev
evaleev force-pushed the zhihao/feature/sym_deriv branch from fcdba5d to c7c23c8 Compare December 5, 2026 00:03

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants