Skip to content

fix moment calculation of arbitrary gradients without ADC - #61

Merged
J-Endres merged 2 commits into
MRsources:mainfrom
fglang:bugfix-arbgrad-integration
Oct 29, 2026
Merged

J-Endres merged 2 commits into
MRsources:mainfrom
fglang:bugfix-arbgrad-integration

Conversation

@fglang

@fglang fglang commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Currently, there are two different methods to calculate gradient moments when converting sequences to MRzero:

With ADC: integrate() calculates the integral of the piecewise-linear waveform, including its first and last endpoints.

Without ADC: parse_spoiler() uses grad.area, which simply sums the waveform samples multiplied by the gradient raster time.

These can give different results for the same arbitrary gradient. So adding an ADC event can change the gradient moment in MRzero, even though the gradient waveform is unchanged.

I've tried to make the conversion consistent by using the existing integrate() function for arbitrary gradients also in blocks without ADC, in both the cached and uncached conversion paths.

This small demo shows the difference:

import pulseqzero as pp
import numpy as np
import torch
from pulseqzero.seq_convert import integrate

# arbitrary gradient with explicit zero endpoints
waveform = torch.tensor([1., 2., 0., 1.], requires_grad=True)
gx = pp.make_arbitrary_grad(
    "x", waveform=waveform * 1e4, first=0., last=0.
)

# two different calculations of the gradient area
print("gx.area:   ", gx.area.item())
print("integrate: ", integrate(gx, torch.tensor([gx.duration])).item())

# compare MRzero conversion with/without ADC during the gradient
for with_adc in [False, True]:
    seq = pp.Sequence()
    seq.add_block(pp.make_block_pulse(
        flip_angle=np.pi/2, duration=1e-3
    ))

    if with_adc:
        seq.add_block(gx, pp.make_adc(4, duration=gx.duration))
    else:
        seq.add_block(gx)

    # check total accumulated moment AFTER the gradient
    seq.add_block(pp.make_adc(1, dwell=2e-6))

    k = seq.to_mr0().get_kspace()[-1, 0]
    print(f"MRzero, ADC during gradient = {with_adc}: {k.item():.4f}")

Felix Glang and others added 2 commits October 11, 2026 16:24
…er-type arbitrary gradients (.integrate instead of .area, taking first/last into account)
@J-Endres
J-Endres merged commit cac63ec into MRsources:main Oct 29, 2026
1 check passed
@J-Endres

Copy link
Copy Markdown
Collaborator

Thank you for the contribution! Maybe we should fix .area in the future to return identical results, but at the moment I think it is identical to what pypulseq computes (which as you discovered seems to be imprecise) so maybe the current state is the best we can do.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants