seqeyes-python 0.4.2__py3-none-any.whl → 0.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
seqeyes/__init__.py CHANGED
@@ -29,4 +29,4 @@ from seqeyes._plot import set, reset
29
29
  from seqeyes._renderer import SeqEyesViewer
30
30
 
31
31
  __all__ = ["set", "reset", "SeqEyesViewer"]
32
- __version__ = "0.4.2"
32
+ __version__ = "0.4.3"
@@ -756,12 +756,15 @@ function serializeBlocks(blocks,cap){
756
756
  p:rawP?rawP.map(function(v){return((v%(2*Math.PI))+2*Math.PI)%(2*Math.PI)}):null,
757
757
  a:b.rf.amplitude,
758
758
  a0:b.rf.response.carrierAreaDeg,
759
- rb:b.rf.response.bands.map(function(v){return[v.frequencyOffsetHz,v.spectralAreaDeg,v.polarFlipDeg,v.mz]}),
759
+ rb:b.rf.response.bands.map(function(v){var band=[v.frequencyOffsetHz,v.spectralAreaDeg,v.polarFlipDeg,v.mz];if(b.rf.response.domain==='position')band.push(v.positionM);return band}),
760
760
  rs:b.rf.response.spectrumAnalyzed?1:0,
761
761
  rl:b.rf.response.limited?1:0,
762
762
  fo:b.rf.freqOffset,po:b.rf.phaseOffset,
763
763
  u:b.rf.use||'u'
764
764
  };
765
+ // As packRf in blockTransport.ts: how the response bands were resolved.
766
+ if(b.rf.response.domain==='position'){o.rf.rd='p';o.rf.rx=b.rf.response.axis||'s';}
767
+ else if(b.rf.response.domain==='unmodelled')o.rf.rd='u';
765
768
  }
766
769
  if(b.gx)o.gx=serializeGrad(b.gx,cap);
767
770
  if(b.gy)o.gy=serializeGrad(b.gy,cap);
@@ -2309,54 +2312,7 @@ function placeTooltip(cx,cy){
2309
2312
  var top=cy+12;if(top>maxY)top=cy-r.height-12;if(top<minY)top=minY;
2310
2313
  tt.style.left=(left-host.left)+'px';tt.style.top=(top-host.top)+'px';
2311
2314
  }
2312
- function fmtFlipAngle(value){
2313
- if(!isFinite(value))return null;
2314
- var absolute=Math.abs(value),digits=absolute<10?2:(absolute<100?1:0);
2315
- return value.toFixed(digits)+'\u00b0';
2316
- }
2317
- function fmtRfFrequency(value){
2318
- var absolute=Math.abs(value),sign=value<0?'\u2212':'+';
2319
- if(absolute>=1000)return sign+(absolute/1000).toFixed(absolute<10000?2:1)+' kHz';
2320
- return sign+absolute.toFixed(absolute<100?1:0)+' Hz';
2321
- }
2322
- function rfBandMetric(bands,index){
2323
- if(!bands.length)return null;
2324
- var min=Infinity,max=-Infinity,total=0;
2325
- for(var i=0;i<bands.length;i++){var value=bands[i][index];if(!isFinite(value))return null;min=Math.min(min,value);max=Math.max(max,value);total+=value;}
2326
- var mean=total/bands.length;
2327
- if(max-min<=Math.max(.25,Math.abs(mean)*.01))return fmtFlipAngle(mean);
2328
- return fmtFlipAngle(min)+'\u2013'+fmtFlipAngle(max);
2329
- }
2330
- function rfBandOffsets(bands){
2331
- if(!bands.length)return '';
2332
- if(bands.length===2){
2333
- var left=bands[0][0],right=bands[1][0],scale=Math.max(1,Math.abs(left),Math.abs(right));
2334
- if(Math.abs(left+right)<=.02*scale)return '\u00b1'+fmtRfFrequency(Math.abs(right)).slice(1);
2335
- }
2336
- if(bands.length<=3)return bands.map(function(v){return fmtRfFrequency(v[0]);}).join(',');
2337
- return fmtRfFrequency(bands[0][0])+'\u2026'+fmtRfFrequency(bands[bands.length-1][0]);
2338
- }
2339
- function rfResponseSummary(rf){
2340
- var bands=(rf.rb||[]).filter(function(v){return v&&v.length>=4&&isFinite(v[0])&&isFinite(v[1])&&isFinite(v[2])&&isFinite(v[3]);});
2341
- var area0=fmtFlipAngle(rf.a0),use=(rf.u||'u').toLowerCase();
2342
- if(!bands.length)return area0?' area\u2080='+area0:'';
2343
- var polar=rfBandMetric(bands,2),spectral=rfBandMetric(bands,1);
2344
- if(use==='i'||use==='inversion'){
2345
- var center=bands[0];for(var i=1;i<bands.length;i++)if(Math.abs(bands[i][0])<Math.abs(center[0]))center=bands[i];
2346
- var efficiency=Math.max(0,Math.min(1,-center[3]))*100;
2347
- return ' Inv\u2248'+efficiency.toFixed(1)+'% \u03b8z\u2248'+fmtFlipAngle(center[2])+(area0?' area\u2080='+area0:'');
2348
- }
2349
- if(bands.length>1){
2350
- var prefix=(use==='e'||use==='excitation')?'FA\u2248':'\u03b8z\u2248';
2351
- var summary=' MB'+bands.length+' '+prefix+polar;
2352
- var meanPolar=0,meanArea=0;for(var j=0;j<bands.length;j++){meanPolar+=bands[j][2];meanArea+=bands[j][1];}
2353
- if(Math.abs(meanArea-meanPolar)/bands.length>.5)summary+=' (area\u2248'+spectral+')';
2354
- return summary+' \u0394f='+rfBandOffsets(bands);
2355
- }
2356
- var single=' '+((use==='e'||use==='excitation')?'FA\u2248':'\u03b8z\u2248')+polar;
2357
- if(Math.abs(bands[0][0])>1)single+=' \u0394f='+fmtRfFrequency(bands[0][0]);
2358
- return single;
2359
- }
2315
+ // RF response formatting (fmtFlipAngle … rfResponseSummary) is the shared bundle's.
2360
2316
  function showTooltipAt(cx,cy,ct){
2361
2317
  var ch=cH(),vc=visChannels(),vi2=Math.floor((cy-mc.getBoundingClientRect().top-M.t)/ch);
2362
2318
  if(vi2>=0&&vi2<vc.length){
@@ -90,7 +90,7 @@ var Pulseq = (() => {
90
90
  });
91
91
 
92
92
  // package.json
93
- var version = "0.4.2";
93
+ var version = "0.4.3";
94
94
 
95
95
  // src/pulseq/decompressor.ts
96
96
  function decompressShape(compressed, numSamples) {
@@ -1683,11 +1683,20 @@ var Pulseq = (() => {
1683
1683
  const t0 = timeShape[k] * raster;
1684
1684
  const t1 = timeShape[k + 1] * raster;
1685
1685
  const u = t1 > t0 ? (mid - t0) / (t1 - t0) : 0;
1686
- const p0 = phaseCycles ? phaseCycles[k] : 0;
1687
- const p1 = phaseCycles ? phaseCycles[k + 1] : 0;
1688
- visit(start, width, magnitude[k] + u * (magnitude[k + 1] - magnitude[k]), p0 + u * (p1 - p0));
1686
+ const m0 = magnitude[k];
1687
+ const m1 = magnitude[k + 1];
1688
+ const phase = phaseCycles ? interpolatePhaseCycles(phaseCycles[k], phaseCycles[k + 1], m0, m1, u) : 0;
1689
+ visit(start, width, m0 + u * (m1 - m0), phase);
1689
1690
  }
1690
1691
  }
1692
+ function interpolatePhaseCycles(p0, p1, m0, m1, u) {
1693
+ if (m0 === 0) return p1;
1694
+ if (m1 === 0) return p0;
1695
+ const delta = p1 - p0;
1696
+ let arc = delta - Math.round(delta);
1697
+ if (Math.abs(arc) === 0.5) arc = Math.sign(delta) * 0.5;
1698
+ return p0 + u * arc;
1699
+ }
1691
1700
  function rasterCellsFromShapes(shapes) {
1692
1701
  const cells = allocate(rasterCellCount(shapes), !shapes.timeShape);
1693
1702
  let i = 0;
@@ -1747,6 +1756,116 @@ var Pulseq = (() => {
1747
1756
  };
1748
1757
  }
1749
1758
 
1759
+ // src/sim/program/pwl.ts
1760
+ function pieceCount(pieces) {
1761
+ return pieces.t.length - 1;
1762
+ }
1763
+ function mergeAxes(axes, ta, tb) {
1764
+ if (!(tb > ta)) {
1765
+ return { t: Float64Array.of(ta, ta), ga: new Float64Array(3), gb: new Float64Array(3) };
1766
+ }
1767
+ const cuts = [ta];
1768
+ for (const axis of axes) {
1769
+ for (let i = 0; i < axis.times.length; i++) {
1770
+ const time = axis.times[i];
1771
+ if (time > ta && time < tb) cuts.push(time);
1772
+ }
1773
+ }
1774
+ cuts.push(tb);
1775
+ cuts.sort((a, b) => a - b);
1776
+ const boundaries = [];
1777
+ for (const time of cuts) {
1778
+ if (!boundaries.length || time > boundaries[boundaries.length - 1]) boundaries.push(time);
1779
+ }
1780
+ const n = boundaries.length - 1;
1781
+ const t = Float64Array.from(boundaries);
1782
+ const ga = new Float64Array(3 * n);
1783
+ const gb = new Float64Array(3 * n);
1784
+ for (let axis = 0; axis < 3; axis++) {
1785
+ const { times, values } = axes[axis];
1786
+ let segment = 0;
1787
+ for (let piece = 0; piece < n; piece++) {
1788
+ const u = t[piece], v = t[piece + 1];
1789
+ while (segment + 1 < times.length - 1 && times[segment + 1] <= u) segment++;
1790
+ ga[3 * piece + axis] = interpolateWithin(times, values, segment, u);
1791
+ gb[3 * piece + axis] = interpolateWithin(times, values, segment, v);
1792
+ }
1793
+ }
1794
+ return { t, ga, gb };
1795
+ }
1796
+ function interpolateWithin(times, values, segment, time) {
1797
+ if (times.length === 0) return 0;
1798
+ if (times.length === 1) return values[0];
1799
+ const t0 = times[segment], t1 = times[segment + 1];
1800
+ const v0 = values[segment], v1 = values[segment + 1];
1801
+ if (!(t1 > t0)) return v1;
1802
+ return v0 + (v1 - v0) * (time - t0) / (t1 - t0);
1803
+ }
1804
+ function piecesKAt(pieces, times, out) {
1805
+ const n = pieceCount(pieces);
1806
+ let piece = 0;
1807
+ let kx = 0, ky = 0, kz = 0;
1808
+ for (let s = 0; s < times.length; s++) {
1809
+ const time = times[s];
1810
+ while (piece < n - 1 && pieces.t[piece + 1] <= time) {
1811
+ const h2 = pieces.t[piece + 1] - pieces.t[piece];
1812
+ const o2 = 3 * piece;
1813
+ kx += 0.5 * h2 * (pieces.ga[o2] + pieces.gb[o2]);
1814
+ ky += 0.5 * h2 * (pieces.ga[o2 + 1] + pieces.gb[o2 + 1]);
1815
+ kz += 0.5 * h2 * (pieces.ga[o2 + 2] + pieces.gb[o2 + 2]);
1816
+ piece++;
1817
+ }
1818
+ const h = pieces.t[piece + 1] - pieces.t[piece];
1819
+ const tau = Math.min(Math.max(time - pieces.t[piece], 0), h);
1820
+ const o = 3 * piece;
1821
+ if (h > 0) {
1822
+ const fx = (pieces.gb[o] - pieces.ga[o]) / h;
1823
+ const fy = (pieces.gb[o + 1] - pieces.ga[o + 1]) / h;
1824
+ const fz = (pieces.gb[o + 2] - pieces.ga[o + 2]) / h;
1825
+ out[3 * s] = kx + tau * (pieces.ga[o] + 0.5 * fx * tau);
1826
+ out[3 * s + 1] = ky + tau * (pieces.ga[o + 1] + 0.5 * fy * tau);
1827
+ out[3 * s + 2] = kz + tau * (pieces.ga[o + 2] + 0.5 * fz * tau);
1828
+ } else {
1829
+ out[3 * s] = kx;
1830
+ out[3 * s + 1] = ky;
1831
+ out[3 * s + 2] = kz;
1832
+ }
1833
+ }
1834
+ }
1835
+ function addPiecesIntegral(pieces, a, b, out, fromPiece = 0) {
1836
+ const n = pieceCount(pieces);
1837
+ let first = fromPiece;
1838
+ while (first < n - 1 && pieces.t[first + 1] <= a) first++;
1839
+ for (let piece = first; piece < n && pieces.t[piece] < b; piece++) {
1840
+ const u = Math.max(a, pieces.t[piece]);
1841
+ const v = Math.min(b, pieces.t[piece + 1]);
1842
+ if (!(v > u)) continue;
1843
+ const h = pieces.t[piece + 1] - pieces.t[piece];
1844
+ const o = 3 * piece;
1845
+ for (let axis = 0; axis < 3; axis++) {
1846
+ const g0 = pieces.ga[o + axis];
1847
+ const slope = (pieces.gb[o + axis] - g0) / h;
1848
+ const gu = g0 + slope * (u - pieces.t[piece]);
1849
+ const gv = g0 + slope * (v - pieces.t[piece]);
1850
+ out[axis] += 0.5 * (gu + gv) * (v - u);
1851
+ }
1852
+ }
1853
+ return first;
1854
+ }
1855
+ function cellMeanGradients(pieces, starts, widths, origin) {
1856
+ const count = starts.length;
1857
+ const grad = new Float64Array(3 * count);
1858
+ const area = new Float64Array(3);
1859
+ let piece = 0;
1860
+ for (let j = 0; j < count; j++) {
1861
+ area.fill(0);
1862
+ const a = starts[j] - origin, b = a + widths[j];
1863
+ piece = addPiecesIntegral(pieces, a, b, area, piece);
1864
+ for (let axis = 0; axis < 3; axis++) grad[3 * j + axis] = area[axis] / widths[j];
1865
+ }
1866
+ return grad;
1867
+ }
1868
+
1750
1869
  // src/pulseq/rfResponse.ts
1751
1870
  var MAX_RF_RESPONSE_FFT_POINTS = 131072;
1752
1871
  var MAX_RF_RESPONSE_SAMPLES = 131072;
@@ -1757,7 +1876,10 @@ var Pulseq = (() => {
1757
1876
  var MIN_DOMINANT_AREA_DEG = 0.01;
1758
1877
  var DEG_PER_CYCLE = 360;
1759
1878
  var TAU = 2 * Math.PI;
1760
- function analyzeRfResponse(rf, seq, classifiedUse = rf.use) {
1879
+ var SIGNIFICANT_B1_FRACTION = 0.05;
1880
+ var NEGLIGIBLE_K_SPAN = 1;
1881
+ var DIRECTION_TOLERANCE = 0.01;
1882
+ function analyzeRfResponse(rf, seq, classifiedUse = rf.use, gradient = null) {
1761
1883
  if (rfSampleCount(rf, seq) > MAX_RF_RESPONSE_SAMPLES) {
1762
1884
  return {
1763
1885
  carrierAreaDeg: estimateRfCarrierAreaDeg(rf, seq),
@@ -1770,6 +1892,15 @@ var Pulseq = (() => {
1770
1892
  const carrierAreaDeg = frequencyResolvedAreaDeg(samples, 0);
1771
1893
  const normalizedUse = classifiedUse.toLowerCase();
1772
1894
  const inversion = normalizedUse === "i" || normalizedUse === "inversion";
1895
+ let unmodelled = false;
1896
+ if (gradient && !inversion) {
1897
+ const trajectory = gradientTrajectory(samples, gradient);
1898
+ if (trajectory) {
1899
+ const response = trajectory.modelled ? positionResponse(samples, trajectory, gradient.freqOffsetHz, carrierAreaDeg) : null;
1900
+ if (response) return response;
1901
+ unmodelled = true;
1902
+ }
1903
+ }
1773
1904
  let offsets;
1774
1905
  let spectrumAnalyzed = false;
1775
1906
  let limited = false;
@@ -1792,7 +1923,13 @@ var Pulseq = (() => {
1792
1923
  mz: spinor.mz
1793
1924
  };
1794
1925
  });
1795
- return { carrierAreaDeg, bands, spectrumAnalyzed, limited };
1926
+ return {
1927
+ carrierAreaDeg,
1928
+ bands,
1929
+ spectrumAnalyzed,
1930
+ limited,
1931
+ ...unmodelled ? { domain: "unmodelled" } : {}
1932
+ };
1796
1933
  }
1797
1934
  function estimateRfCarrierAreaDeg(rf, seq) {
1798
1935
  const shapes = rfShapeArrays(rf, seq);
@@ -1834,12 +1971,13 @@ var Pulseq = (() => {
1834
1971
  imaginary[index] = finite2 ? amplitude * Math.sin(phaseRad) : 0;
1835
1972
  if (Math.abs(widths[index] - raster) > Math.max(1e-12, raster * 1e-6)) uniform = false;
1836
1973
  }
1837
- return { real, imaginary, times, widths, uniform, dwell: uniform ? raster : widths[0] };
1974
+ return { real, imaginary, starts: cells.start, times, widths, uniform, dwell: uniform ? raster : widths[0] };
1838
1975
  }
1839
1976
  function emptySamples(raster) {
1840
1977
  return {
1841
1978
  real: new Float64Array(0),
1842
1979
  imaginary: new Float64Array(0),
1980
+ starts: new Float64Array(0),
1843
1981
  times: new Float64Array(0),
1844
1982
  widths: new Float64Array(0),
1845
1983
  uniform: true,
@@ -1847,10 +1985,13 @@ var Pulseq = (() => {
1847
1985
  };
1848
1986
  }
1849
1987
  function frequencyResolvedAreaDeg(samples, frequencyOffsetHz) {
1988
+ return resolvedAreaDeg(samples, samples.times, frequencyOffsetHz);
1989
+ }
1990
+ function resolvedAreaDeg(samples, coordinates, conjugate) {
1850
1991
  let realArea = 0;
1851
1992
  let imaginaryArea = 0;
1852
1993
  for (let index = 0; index < samples.real.length; index++) {
1853
- const angle = -TAU * frequencyOffsetHz * samples.times[index];
1994
+ const angle = -TAU * conjugate * coordinates[index];
1854
1995
  const cosine = Math.cos(angle);
1855
1996
  const sine = Math.sin(angle);
1856
1997
  const width = samples.widths[index];
@@ -1862,34 +2003,36 @@ var Pulseq = (() => {
1862
2003
  function dominantBandOffsets(samples) {
1863
2004
  const sampleCount = samples.real.length;
1864
2005
  if (sampleCount === 0 || !Number.isFinite(samples.dwell) || samples.dwell <= 0) return [0];
1865
- const paddedTarget = sampleCount <= Math.floor(MAX_RF_RESPONSE_FFT_POINTS / ZERO_PAD_FACTOR) ? sampleCount * ZERO_PAD_FACTOR : sampleCount;
1866
- const fftPoints = nextPowerOfTwo(Math.max(MIN_FFT_POINTS, paddedTarget));
2006
+ const fftPoints = paddedFftPoints(sampleCount);
1867
2007
  if (fftPoints > MAX_RF_RESPONSE_FFT_POINTS) return [0];
1868
2008
  const real = new Float64Array(fftPoints);
1869
2009
  const imaginary = new Float64Array(fftPoints);
1870
2010
  real.set(samples.real);
1871
2011
  imaginary.set(samples.imaginary);
1872
2012
  fftInPlace(real, imaginary, fftPoints);
2013
+ const offsets = dominantCentres(real, imaginary, samples.dwell, 1 / (fftPoints * samples.dwell));
2014
+ return offsets.length > 0 ? offsets : [0];
2015
+ }
2016
+ function paddedFftPoints(count) {
2017
+ const paddedTarget = count <= Math.floor(MAX_RF_RESPONSE_FFT_POINTS / ZERO_PAD_FACTOR) ? count * ZERO_PAD_FACTOR : count;
2018
+ return nextPowerOfTwo(Math.max(MIN_FFT_POINTS, paddedTarget));
2019
+ }
2020
+ function dominantCentres(real, imaginary, areaScale, step) {
2021
+ const fftPoints = real.length;
2022
+ const half = fftPoints / 2;
2023
+ const areaAt = (bin) => DEG_PER_CYCLE * areaScale * Math.sqrt(real[bin] * real[bin] + imaginary[bin] * imaginary[bin]);
1873
2024
  let peakAreaDeg = 0;
1874
- for (let bin = 0; bin < fftPoints; bin++) {
1875
- peakAreaDeg = Math.max(
1876
- peakAreaDeg,
1877
- DEG_PER_CYCLE * samples.dwell * Math.hypot(real[bin], imaginary[bin])
1878
- );
1879
- }
1880
- if (!Number.isFinite(peakAreaDeg) || peakAreaDeg < MIN_DOMINANT_AREA_DEG) return [0];
2025
+ for (let bin = 0; bin < fftPoints; bin++) peakAreaDeg = Math.max(peakAreaDeg, areaAt(bin));
2026
+ if (!Number.isFinite(peakAreaDeg) || peakAreaDeg < MIN_DOMINANT_AREA_DEG) return [];
1881
2027
  const threshold = Math.max(MIN_DOMINANT_AREA_DEG, peakAreaDeg * DOMINANT_BAND_FRACTION);
1882
2028
  const clusters = [];
1883
2029
  let active = null;
1884
- const half = fftPoints / 2;
1885
- const frequencyStep = 1 / (fftPoints * samples.dwell);
1886
2030
  for (let signedBin = -half; signedBin < half; signedBin++) {
1887
- const bin = signedBin < 0 ? signedBin + fftPoints : signedBin;
1888
- const areaDeg = DEG_PER_CYCLE * samples.dwell * Math.hypot(real[bin], imaginary[bin]);
2031
+ const areaDeg = areaAt(signedBin < 0 ? signedBin + fftPoints : signedBin);
1889
2032
  if (areaDeg >= threshold) {
1890
- const weight = areaDeg * areaDeg;
2033
+ const weight = areaDeg * areaDeg - threshold * threshold;
1891
2034
  if (!active) active = { frequencySum: 0, weightSum: 0, peakAreaDeg: 0 };
1892
- active.frequencySum += signedBin * frequencyStep * weight;
2035
+ active.frequencySum += signedBin * step * weight;
1893
2036
  active.weightSum += weight;
1894
2037
  active.peakAreaDeg = Math.max(active.peakAreaDeg, areaDeg);
1895
2038
  } else if (active) {
@@ -1898,10 +2041,180 @@ var Pulseq = (() => {
1898
2041
  }
1899
2042
  }
1900
2043
  if (active) clusters.push(active);
1901
- const offsets = clusters.filter((cluster) => cluster.weightSum > 0).sort((left, right) => right.peakAreaDeg - left.peakAreaDeg).slice(0, MAX_RF_RESPONSE_BANDS).map((cluster) => cluster.frequencySum / cluster.weightSum).sort((left, right) => left - right);
1902
- return offsets.length > 0 ? offsets : [0];
2044
+ return clusters.filter((cluster) => cluster.weightSum > 0).sort((left, right) => right.peakAreaDeg - left.peakAreaDeg).slice(0, MAX_RF_RESPONSE_BANDS).map((cluster) => cluster.frequencySum / cluster.weightSum).sort((left, right) => left - right);
2045
+ }
2046
+ function gradientTrajectory(samples, context) {
2047
+ const count = samples.real.length;
2048
+ if (count === 0) return null;
2049
+ const ta = samples.starts[0];
2050
+ const tb = samples.starts[count - 1] + samples.widths[count - 1];
2051
+ const pieces = mergeAxes(
2052
+ [covering(context.axes[0], ta, tb), covering(context.axes[1], ta, tb), covering(context.axes[2], ta, tb)],
2053
+ ta,
2054
+ tb
2055
+ );
2056
+ const cellGradient = cellMeanGradients(pieces, samples.starts, samples.widths, 0);
2057
+ const cellK = new Float64Array(3 * count);
2058
+ piecesKAt(pieces, samples.times, cellK);
2059
+ const magnitude = b1Magnitudes(samples);
2060
+ let peak = 0;
2061
+ for (let n = 0; n < count; n++) peak = Math.max(peak, magnitude[n]);
2062
+ if (!(peak > 0)) return null;
2063
+ let first = -1;
2064
+ let last = -1;
2065
+ for (let n = 0; n < count; n++) {
2066
+ if (magnitude[n] < SIGNIFICANT_B1_FRACTION * peak) continue;
2067
+ if (first < 0) first = n;
2068
+ last = n;
2069
+ }
2070
+ let span = 0;
2071
+ let peakGradient = 0;
2072
+ for (let n = first; n <= last; n++) {
2073
+ span = Math.max(span, norm3(
2074
+ cellK[3 * n] - cellK[3 * first],
2075
+ cellK[3 * n + 1] - cellK[3 * first + 1],
2076
+ cellK[3 * n + 2] - cellK[3 * first + 2]
2077
+ ));
2078
+ peakGradient = Math.max(peakGradient, norm3(cellGradient[3 * n], cellGradient[3 * n + 1], cellGradient[3 * n + 2]));
2079
+ }
2080
+ if (span < NEGLIGIBLE_K_SPAN) return null;
2081
+ const direction = [0, 1, 2].map((axis2) => cellK[3 * last + axis2] - cellK[3 * first + axis2]);
2082
+ const length = norm3(direction[0], direction[1], direction[2]);
2083
+ let axis = "s";
2084
+ let modelled = length > 0;
2085
+ if (modelled) {
2086
+ let major = 0;
2087
+ for (let a = 1; a < 3; a++) if (Math.abs(direction[a]) > Math.abs(direction[major])) major = a;
2088
+ const sign = Math.sign(direction[major]);
2089
+ for (let a = 0; a < 3; a++) direction[a] *= sign / length;
2090
+ if (Math.abs(direction[major]) > 1 - 1e-9) {
2091
+ axis = ["x", "y", "z"][major];
2092
+ direction.fill(0);
2093
+ direction[major] = 1;
2094
+ }
2095
+ }
2096
+ const k = new Float64Array(count);
2097
+ const gradient = new Float64Array(count);
2098
+ for (let n = 0; n < count; n++) {
2099
+ k[n] = cellK[3 * n] * direction[0] + cellK[3 * n + 1] * direction[1] + cellK[3 * n + 2] * direction[2];
2100
+ gradient[n] = cellGradient[3 * n] * direction[0] + cellGradient[3 * n + 1] * direction[1] + cellGradient[3 * n + 2] * direction[2];
2101
+ }
2102
+ if (modelled) {
2103
+ const travel = Math.sign(k[last] - k[first]);
2104
+ const tolerance = DIRECTION_TOLERANCE * peakGradient;
2105
+ for (let n = first; n <= last && modelled; n++) {
2106
+ const along = gradient[n];
2107
+ const off = norm3(
2108
+ cellGradient[3 * n] - along * direction[0],
2109
+ cellGradient[3 * n + 1] - along * direction[1],
2110
+ cellGradient[3 * n + 2] - along * direction[2]
2111
+ );
2112
+ if (off > tolerance || travel * along < -tolerance) modelled = false;
2113
+ }
2114
+ }
2115
+ return { k, gradient, axis, first, last, modelled };
1903
2116
  }
1904
- function propagateSpinor(samples, frequencyOffsetHz) {
2117
+ function covering(points, ta, tb) {
2118
+ const count = Math.min(points.times.length, points.values.length);
2119
+ if (count === 0) return { times: [ta, tb], values: [0, 0] };
2120
+ const firstTime = points.times[0];
2121
+ const lastTime = points.times[count - 1];
2122
+ if (firstTime <= ta && lastTime >= tb) return points;
2123
+ const times = [];
2124
+ const values = [];
2125
+ if (firstTime > ta) times.push(ta, firstTime), values.push(0, 0);
2126
+ for (let i = 0; i < count; i++) {
2127
+ times.push(points.times[i]);
2128
+ values.push(points.values[i]);
2129
+ }
2130
+ if (lastTime < tb) times.push(lastTime, tb), values.push(0, 0);
2131
+ return { times, values };
2132
+ }
2133
+ function positionResponse(samples, trajectory, freqOffsetHz, carrierAreaDeg) {
2134
+ const b1 = freqOffsetHz !== 0 ? withFrequencyRamp(samples, freqOffsetHz) : samples;
2135
+ const positions = dominantPositions(b1, trajectory);
2136
+ if (!positions) return null;
2137
+ const magnitude = b1Magnitudes(b1);
2138
+ let weightedGradient = 0;
2139
+ let weight = 0;
2140
+ for (let n = 0; n < b1.real.length; n++) {
2141
+ const w = magnitude[n] * b1.widths[n];
2142
+ weightedGradient += w * trajectory.gradient[n];
2143
+ weight += w;
2144
+ }
2145
+ const meanGradient = weight > 0 ? weightedGradient / weight : 0;
2146
+ const bands = positions.map((positionM) => {
2147
+ const spinor = propagateSpinor(samples, -freqOffsetHz, trajectory.gradient, positionM);
2148
+ return {
2149
+ frequencyOffsetHz: meanGradient * positionM - freqOffsetHz,
2150
+ positionM,
2151
+ spectralAreaDeg: resolvedAreaDeg(b1, trajectory.k, positionM),
2152
+ polarFlipDeg: spinor.polarFlipDeg,
2153
+ mz: spinor.mz
2154
+ };
2155
+ });
2156
+ return {
2157
+ carrierAreaDeg,
2158
+ bands,
2159
+ spectrumAnalyzed: true,
2160
+ limited: false,
2161
+ domain: "position",
2162
+ axis: trajectory.axis
2163
+ };
2164
+ }
2165
+ function withFrequencyRamp(samples, frequencyHz) {
2166
+ const real = new Float64Array(samples.real.length);
2167
+ const imaginary = new Float64Array(samples.real.length);
2168
+ for (let n = 0; n < real.length; n++) {
2169
+ const angle = TAU * frequencyHz * samples.times[n];
2170
+ const cosine = Math.cos(angle);
2171
+ const sine = Math.sin(angle);
2172
+ real[n] = samples.real[n] * cosine - samples.imaginary[n] * sine;
2173
+ imaginary[n] = samples.real[n] * sine + samples.imaginary[n] * cosine;
2174
+ }
2175
+ return { ...samples, real, imaginary };
2176
+ }
2177
+ function dominantPositions(samples, trajectory) {
2178
+ const { k, gradient, first, last } = trajectory;
2179
+ let maxStep = 0;
2180
+ for (let n = first; n <= last; n++) maxStep = Math.max(maxStep, Math.abs(gradient[n]) * samples.widths[n]);
2181
+ if (!(maxStep > 0)) return null;
2182
+ const spacing = maxStep;
2183
+ let range = kRange(k, 0, k.length - 1);
2184
+ let bins = Math.floor((range.high - range.low) / spacing) + 2;
2185
+ if (bins > MAX_RF_RESPONSE_FFT_POINTS) {
2186
+ range = kRange(k, first, last);
2187
+ bins = Math.floor((range.high - range.low) / spacing) + 2;
2188
+ }
2189
+ const fftPoints = paddedFftPoints(bins);
2190
+ if (fftPoints > MAX_RF_RESPONSE_FFT_POINTS) return null;
2191
+ const real = new Float64Array(fftPoints);
2192
+ const imaginary = new Float64Array(fftPoints);
2193
+ for (let n = 0; n < k.length; n++) {
2194
+ if (k[n] < range.low || k[n] > range.high) continue;
2195
+ const position = (k[n] - range.low) / spacing;
2196
+ const bin = Math.min(Math.floor(position), bins - 2);
2197
+ const upper = position - bin;
2198
+ const width = samples.widths[n];
2199
+ real[bin] += (1 - upper) * samples.real[n] * width;
2200
+ imaginary[bin] += (1 - upper) * samples.imaginary[n] * width;
2201
+ real[bin + 1] += upper * samples.real[n] * width;
2202
+ imaginary[bin + 1] += upper * samples.imaginary[n] * width;
2203
+ }
2204
+ fftInPlace(real, imaginary, fftPoints);
2205
+ const positions = dominantCentres(real, imaginary, 1, 1 / (fftPoints * spacing));
2206
+ return positions.length > 0 ? positions : null;
2207
+ }
2208
+ function kRange(k, from, to) {
2209
+ let low = Infinity;
2210
+ let high = -Infinity;
2211
+ for (let n = from; n <= to; n++) {
2212
+ low = Math.min(low, k[n]);
2213
+ high = Math.max(high, k[n]);
2214
+ }
2215
+ return { low, high };
2216
+ }
2217
+ function propagateSpinor(samples, frequencyOffsetHz, gradientHz = null, positionM = 0) {
1905
2218
  let stateAReal = 1;
1906
2219
  let stateAImaginary = 0;
1907
2220
  let stateBReal = 0;
@@ -1909,12 +2222,13 @@ var Pulseq = (() => {
1909
2222
  for (let index = 0; index < samples.real.length; index++) {
1910
2223
  const bx = samples.real[index];
1911
2224
  const by = samples.imaginary[index];
1912
- const norm = Math.hypot(bx, by, frequencyOffsetHz);
2225
+ const offset = gradientHz ? frequencyOffsetHz + gradientHz[index] * positionM : frequencyOffsetHz;
2226
+ const norm = Math.sqrt(bx * bx + by * by + offset * offset);
1913
2227
  const width = samples.widths[index];
1914
2228
  if (!(norm > 0) || !(width > 0)) continue;
1915
2229
  const sine = Math.sin(Math.PI * norm * width);
1916
2230
  const localAReal = Math.cos(Math.PI * norm * width);
1917
- const localAImaginary = -frequencyOffsetHz / norm * sine;
2231
+ const localAImaginary = -offset / norm * sine;
1918
2232
  const localBReal = by / norm * sine;
1919
2233
  const localBImaginary = -bx / norm * sine;
1920
2234
  const nextAReal = localAReal * stateAReal - localAImaginary * stateAImaginary - localBReal * stateBReal - localBImaginary * stateBImaginary;
@@ -1932,6 +2246,16 @@ var Pulseq = (() => {
1932
2246
  const mz = normalization > 0 ? clamp((aMagnitudeSquared - bMagnitudeSquared) / normalization, -1, 1) : 1;
1933
2247
  return { mz, polarFlipDeg: Math.acos(mz) * 180 / Math.PI };
1934
2248
  }
2249
+ function b1Magnitudes(samples) {
2250
+ const magnitude = new Float64Array(samples.real.length);
2251
+ for (let n = 0; n < magnitude.length; n++) {
2252
+ magnitude[n] = Math.sqrt(samples.real[n] * samples.real[n] + samples.imaginary[n] * samples.imaginary[n]);
2253
+ }
2254
+ return magnitude;
2255
+ }
2256
+ function norm3(x, y, z) {
2257
+ return Math.sqrt(x * x + y * y + z * z);
2258
+ }
1935
2259
  function clamp(value, minimum, maximum) {
1936
2260
  return Math.max(minimum, Math.min(maximum, value));
1937
2261
  }
@@ -1991,10 +2315,11 @@ var Pulseq = (() => {
1991
2315
  const rf = seq.rfs.get(block.rfId);
1992
2316
  if (rf) {
1993
2317
  const use = context.classifiedRfUses[i];
1994
- let response = context.rfResponseCache.get(rf.id);
2318
+ const key = `${rf.id}:${block.gxId}:${block.gyId}:${block.gzId}`;
2319
+ let response = context.rfResponseCache.get(key);
1995
2320
  if (!response) {
1996
- response = context.skipRfResponse ? UNANALYZED_RF_RESPONSE : analyzeRfResponse(rf, seq, use);
1997
- context.rfResponseCache.set(rf.id, response);
2321
+ response = context.skipRfResponse ? UNANALYZED_RF_RESPONSE : analyzeRfResponse(rf, seq, use, rfGradientContext(seq, block, rf, dur));
2322
+ context.rfResponseCache.set(key, response);
1998
2323
  }
1999
2324
  db.rf = decodeRF(seq, rf, cumulative, dur, use, response);
2000
2325
  }
@@ -2026,6 +2351,18 @@ var Pulseq = (() => {
2026
2351
  if (seq.versionCombined < VER_PRE_14) return block.dur * 1e-6;
2027
2352
  return block.dur * seq.rasterTimes.blockDurationRaster;
2028
2353
  }
2354
+ function rfGradientContext(seq, block, rf, blockDur) {
2355
+ if (block.gxId <= 0 && block.gyId <= 0 && block.gzId <= 0) return null;
2356
+ const origin = -rf.delay * 1e-6;
2357
+ const axis = (gradId, channel) => {
2358
+ const decoded = decodeGradient(seq, gradId, origin, blockDur, channel);
2359
+ return { times: decoded.timePoints, values: decoded.waveform };
2360
+ };
2361
+ return {
2362
+ axes: [axis(block.gxId, "gx"), axis(block.gyId, "gy"), axis(block.gzId, "gz")],
2363
+ freqOffsetHz: effFreqOff(rf.freqOffset, rf.freqPPM, getB02(seq))
2364
+ };
2365
+ }
2029
2366
  function decodeRF(seq, rf, blockStart, _blockDur, classifiedUse, response) {
2030
2367
  const raster = seq.rasterTimes.rfRaster;
2031
2368
  const rfDelay = rf.delay * 1e-6;
@@ -2819,12 +3156,12 @@ var Pulseq = (() => {
2819
3156
  }
2820
3157
  function packRf(rf, magnitude, phase) {
2821
3158
  const metrics = waveformMagnitudeMetrics(rf.timePoints, rf.magnitude);
2822
- const responseBands = rf.response.bands.map((band) => [
2823
- band.frequencyOffsetHz,
2824
- band.spectralAreaDeg,
2825
- band.polarFlipDeg,
2826
- band.mz
2827
- ]);
3159
+ const position = rf.response.domain === "position";
3160
+ const responseBands = rf.response.bands.map((band) => {
3161
+ const packed2 = [band.frequencyOffsetHz, band.spectralAreaDeg, band.polarFlipDeg, band.mz];
3162
+ if (position) packed2.push(band.positionM ?? NaN);
3163
+ return packed2;
3164
+ });
2828
3165
  const packed = {
2829
3166
  s: rf.startTime,
2830
3167
  d: rf.duration,
@@ -2848,6 +3185,12 @@ var Pulseq = (() => {
2848
3185
  u: rf.use || "u"
2849
3186
  // 'e'=excitation, 'r'=refocusing, 'i'=inversion, 's'=saturation, 'u'=undefined
2850
3187
  };
3188
+ if (position) {
3189
+ packed.rd = "p";
3190
+ packed.rx = rf.response.axis ?? "s";
3191
+ } else if (rf.response.domain === "unmodelled") {
3192
+ packed.rd = "u";
3193
+ }
2851
3194
  if (magnitude.r) packed.r = 1;
2852
3195
  return packed;
2853
3196
  }
@@ -12001,8 +12001,26 @@ function rfBandOffsets(bands){
12001
12001
  if(bands.length<=3)return bands.map(function(v){return fmtRfFrequency(v[0]);}).join(',');
12002
12002
  return fmtRfFrequency(bands[0][0])+'\u2026'+fmtRfFrequency(bands[bands.length-1][0]);
12003
12003
  }
12004
+ // One decimal: the band centroid is good to a few hundredths of a millimetre.
12005
+ function fmtRfPosition(value){
12006
+ var mm=value*1e3,text=Math.abs(mm).toFixed(1);
12007
+ return text==='0.0'?text:(mm<0?'\u2212':'+')+text;
12008
+ }
12009
+ /** Band positions [m] (each band's fifth entry) along `axis`, in mm. */
12010
+ function rfBandPositions(bands,axis){
12011
+ var positions=bands.length<=3
12012
+ ?bands.map(function(v){return fmtRfPosition(v[4]);}).join(',')
12013
+ :fmtRfPosition(bands[0][4])+'\u2026'+fmtRfPosition(bands[bands.length-1][4]);
12014
+ return (axis||'s')+'='+positions+' mm';
12015
+ }
12016
+ /**
12017
+ * `rd` says how the bands were resolved: absent against a static frequency
12018
+ * offset, 'p' along the gradient played with the pulse (positions in `rx`),
12019
+ * 'u' under a gradient the analysis cannot represent, so areas only.
12020
+ */
12004
12021
  function rfResponseSummary(rf){
12005
- var bands=(rf.rb||[]).filter(function(v){return v&&v.length>=4&&isFinite(v[0])&&isFinite(v[1])&&isFinite(v[2])&&isFinite(v[3]);});
12022
+ var position=rf.rd==='p';
12023
+ var bands=(rf.rb||[]).filter(function(v){return v&&v.length>=4&&isFinite(v[0])&&isFinite(v[1])&&isFinite(v[2])&&isFinite(v[3])&&(!position||isFinite(v[4]));});
12006
12024
  var area0=fmtFlipAngle(rf.a0),use=(rf.u||'u').toLowerCase();
12007
12025
  if(!bands.length)return area0?' area\u2080='+area0:'';
12008
12026
  var polar=rfBandMetric(bands,2),spectral=rfBandMetric(bands,1);
@@ -12011,16 +12029,21 @@ function rfResponseSummary(rf){
12011
12029
  var efficiency=Math.max(0,Math.min(1,-center[3]))*100;
12012
12030
  return ' Inv\u2248'+efficiency.toFixed(1)+'% \u03b8z\u2248'+fmtFlipAngle(center[2])+(area0?' area\u2080='+area0:'');
12013
12031
  }
12014
- if(bands.length>1){
12015
- var prefix=(use==='e'||use==='excitation')?'FA\u2248':'\u03b8z\u2248';
12016
- var summary=' MB'+bands.length+' '+prefix+polar;
12017
- var meanPolar=0,meanArea=0;for(var j=0;j<bands.length;j++){meanPolar+=bands[j][2];meanArea+=bands[j][1];}
12018
- if(Math.abs(meanArea-meanPolar)/bands.length>.5)summary+=' (area\u2248'+spectral+')';
12019
- return summary+' \u0394f='+rfBandOffsets(bands);
12020
- }
12021
- var single=' '+((use==='e'||use==='excitation')?'FA\u2248':'\u03b8z\u2248')+polar;
12022
- if(Math.abs(bands[0][0])>1)single+=' \u0394f='+fmtRfFrequency(bands[0][0]);
12023
- return single;
12032
+ if(rf.rd==='u'){
12033
+ var area=' area\u2248'+spectral;
12034
+ if(bands.length>1||Math.abs(bands[0][0])>1)area+=' @ \u0394f='+rfBandOffsets(bands);
12035
+ return area+' (gradient not modelled)';
12036
+ }
12037
+ var summary=' '+(bands.length>1?'MB'+bands.length+' ':'')+((use==='e'||use==='excitation')?'FA\u2248':'\u03b8z\u2248')+polar;
12038
+ var meanPolar=0,meanArea=0;for(var j=0;j<bands.length;j++){meanPolar+=bands[j][2];meanArea+=bands[j][1];}
12039
+ meanPolar/=bands.length;meanArea/=bands.length;
12040
+ if(bands.length>1&&Math.abs(meanArea-meanPolar)>.5)summary+=' (area\u2248'+spectral+')';
12041
+ // The carrier-frame area only where it says something the band does not:
12042
+ // a slice written as phase leaves almost nothing at the carrier.
12043
+ if(position)return summary+' @ '+rfBandPositions(bands,rf.rx)+(area0&&Math.abs(rf.a0-meanArea)>.5?' area\u2080='+area0:'');
12044
+ if(bands.length>1)return summary+' \u0394f='+rfBandOffsets(bands);
12045
+ if(Math.abs(bands[0][0])>1)summary+=' \u0394f='+fmtRfFrequency(bands[0][0]);
12046
+ return summary;
12024
12047
  }
12025
12048
  function showTooltipAt(cx,cy,ct){
12026
12049
  var ch=cH(),vc=visChannels(),vi2=Math.floor((cy-mc.getBoundingClientRect().top-M.t)/ch);
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: seqeyes-python
3
- Version: 0.4.2
3
+ Version: 0.4.3
4
4
  Summary: Interactive Pulseq MRI sequence viewer for Jupyter — lightweight, beautiful, replaces seq.plot() in pypulseq.
5
5
  Project-URL: Homepage, https://github.com/bughht/seqeyes_plugin
6
6
  Project-URL: Repository, https://github.com/bughht/seqeyes_plugin
@@ -0,0 +1,10 @@
1
+ seqeyes/__init__.py,sha256=GBnGwrqBVikfxyC2vm-uLcw5Q4NQg_3rakiSZ6Rq9nw,944
2
+ seqeyes/_plot.py,sha256=mkjkl-o1LOkVauPdjtujKHgfOQpzZGvpO4tcrjaY6Qk,8114
3
+ seqeyes/_renderer.py,sha256=whzHZuCLwInhxh9BzLzbz_6HOL7Rf26ibQzXvfsJDSI,12631
4
+ seqeyes/resources/index.html,sha256=0tXTif88xw8SP9tCsBveNqeu5QMfBEVeLx3_Lm-5KLc,182098
5
+ seqeyes/resources/pulseq-bundle.js,sha256=9WZQrEZ0PyzPSjpY4CMAfot6bIVsQ271UaJf2Noz4n0,250843
6
+ seqeyes/resources/styles.css,sha256=5RiDaip6nR2DnXRnxmBliA3qYbZB7MQ1MRlWySdzH-A,26934
7
+ seqeyes/resources/webview-bundle.js,sha256=E06iYp-ulnptx3Z1wQpI9rHc9BXP6TRNWE5jwm6hAC0,554026
8
+ seqeyes_python-0.4.3.dist-info/METADATA,sha256=UbRnklTaHFwSNblm5iWTSCAmuSK_Z8DONfRj_mJD6WU,6350
9
+ seqeyes_python-0.4.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ seqeyes_python-0.4.3.dist-info/RECORD,,
@@ -1,10 +0,0 @@
1
- seqeyes/__init__.py,sha256=viHJ5KiamSRnnhJN8JB_39JOZ8sZHUllz4HtFIgHEu4,944
2
- seqeyes/_plot.py,sha256=mkjkl-o1LOkVauPdjtujKHgfOQpzZGvpO4tcrjaY6Qk,8114
3
- seqeyes/_renderer.py,sha256=whzHZuCLwInhxh9BzLzbz_6HOL7Rf26ibQzXvfsJDSI,12631
4
- seqeyes/resources/index.html,sha256=Q6292zzOEdYcauPFue5xTZarDAh6pzENXth6l4sV9fc,184289
5
- seqeyes/resources/pulseq-bundle.js,sha256=vltFkoowothgwPSRGxUfOoFNxLqCGZPyVXSYKD_sdX0,236914
6
- seqeyes/resources/styles.css,sha256=5RiDaip6nR2DnXRnxmBliA3qYbZB7MQ1MRlWySdzH-A,26934
7
- seqeyes/resources/webview-bundle.js,sha256=sXIF0P-OZOcvqpSI1o24pottjZ8jv1f6xQXfiktyw9I,552768
8
- seqeyes_python-0.4.2.dist-info/METADATA,sha256=nS-wD1PqJalFQ1-j8dnNYmK8FFfo9pjxT0oSzOjZDps,6350
9
- seqeyes_python-0.4.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
- seqeyes_python-0.4.2.dist-info/RECORD,,