-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathADNode.m
More file actions
2603 lines (2424 loc) · 112 KB
/
ADNode.m
File metadata and controls
2603 lines (2424 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef ADNode < handle
%% Node in the function evalution graph
properties
value % function value at this node
grad % gradient accumulator
func % callback function to update gradient of the parent nodes
root % input node that holds the tape
tape % sequence of evaluation steps
end
methods (Static)
function b = isreal(x)
b = isreal(x.value);
end
function o = fftconvolve(x,y)
ax = numel(x);
ay = numel(y);
len = ax+ay-1;
x(length(x)+1:len) = 0;
y(length(y)+1:len) = 0;
x = fft(x);
y = fft(y);
o = x.*y;
o = real(ifft(o));
end
% Helper function to find the root of the computation graph
function root = find_ad_root(args)
root = [];
for i = 1:numel(args)
if isa(args{i}, 'ADNode')
root = args{i}.root;
return;
end
end
end
function paddedArray = padArray(inputArray, padSize, dim)
%% padArray: Pads an array with zeros on a specified dimension, or defaults to the first dimension.
%
% paddedArray = padArray(inputArray, padSize)
% paddedArray = padArray(inputArray, padSize, dim)
%
% Inputs:
% inputArray - The input array (can be 1D, 2D, 3D, or higher).
% padSize - The number of zeros to pad on each side of the relevant dimension(s).
% If padSize is a scalar, it applies to the specified 'dim'
% or to the first dimension if 'dim' is not provided.
% If padSize is a vector and 'dim' is NOT provided, its
% length must match the number of dimensions of inputArray,
% specifying padding for each.
% If padSize is a vector and 'dim' IS provided, only its
% first element will be used as the padding amount for 'dim'.
% dim - (Optional) The specific dimension along which to pad.
% If provided, only this dimension will be padded.
% If not provided, padding will be applied only to the
% first dimension of the array.
%
% Output:
% paddedArray - The input array padded with zeros.
%
% Examples:
% % Default behavior: Pads only the first dimension
% vec_row = [1 2 3 4 5];
% paddedVec_row = padArray(vec_row, 1); % Result will be 3x5 (pads dim 1)
% % [0 0 0 0 0]
% % [1 2 3 4 5]
% % [0 0 0 0 0]
%
% % Default behavior: Pads only the first dimension
% vec_col = [1; 2; 3];
% paddedVec_col = padArray(vec_col, 1); % Result will be 5x1 (pads dim 1)
% % [0]
% % [0]
% % [1]
% % [2]
% % [3]
% % [0]
%
% % Default behavior: 2D matrix pads only the first dimension (rows)
% mat = [1 2; 3 4];
% paddedMat = padArray(mat, 1);
% % Result:
% % [0 0]
% % [1 2]
% % [3 4]
% % [0 0]
%
% % 3D array: pads only along the 3rd dimension (explicit dim)
% arr3D = rand(2,3,2);
% paddedArr3D_dim3 = padArray(arr3D, 1, 3);
% % The output will be 2x3x4 (original 2x3x2, padded by 1 on dim 3)
%
% % 2D matrix: pads only along the 1st dimension (rows) (explicit dim)
% mat_pad_dim1 = padArray([1 2; 3 4], 1, 1);
% % Result:
% % [0 0]
% % [1 2]
% % [3 4]
% % [0 0]
%
% % 2D matrix: pads only along the 2nd dimension (columns) (explicit dim)
% mat_pad_dim2 = padArray([1 2; 3 4], 1, 2);
% % Result:
% % [0 1 2 0]
% % [0 3 4 0]
%
% % Different padding for different dimensions (explicit vector padSize, but still only pads dim 1 by default)
% % Note: If dim is NOT provided, a vector padSize will still only apply to the first dimension.
% % To pad multiple specific dimensions, you must call padArray multiple times or create a custom
% % padSizesPerDim array and pass it with dimProvided = true logic.
% mat2 = [1 2; 3 4];
% paddedMat2_default = padArray(mat2, [1 2]); % This will pad only dim 1 by 1.
% % Result:
% % [0 0]
% % [1 2]
% % [3 4]
% % [0 0]
inputSize = size(inputArray);
numDims = ndims(inputArray);
% Determine if 'dim' argument was provided
dimProvided = false;
if nargin == 3
dimProvided = true;
targetDim = dim; % Store the specified dimension
end
% Initialize padSizesPerDim array to all zeros
padSizesPerDim = zeros(1, numDims);
if dimProvided
% Validate the specified dimension
if ~isscalar(targetDim) || ~isnumeric(targetDim) || targetDim < 1 || targetDim > numDims || mod(targetDim, 1) ~= 0
error('padArray:InvalidDimension', 'Dimension (dim) must be a positive integer within the range of array dimensions.');
end
% If dim is specified, padSize should ideally be a scalar for that dim.
% If padSize is a vector, take its first element as the effective padding.
if isscalar(padSize)
effectivePadAmount = padSize;
else
warning('padArray:VectorPadSizeWithDim', 'When a specific dimension is provided, padSize should be a scalar. Using the first element of padSize vector.');
effectivePadAmount = padSize(1);
end
% Apply padding only for the specified dimension
padSizesPerDim(targetDim) = effectivePadAmount;
else % 'dim' argument was NOT provided, default to padding only the first dimension
% If padSize is a scalar, apply it to the first dimension.
% If padSize is a vector, take its first element for the first dimension.
if isscalar(padSize)
effectivePadAmount = padSize;
else
warning('padArray:VectorPadSizeNoDim', 'When no specific dimension is provided, padSize should be a scalar. Using the first element of padSize vector for the first dimension.');
effectivePadAmount = padSize(1);
end
% Apply padding only to the first dimension
padSizesPerDim(1) = effectivePadAmount;
end
% Calculate the new size for the padded array
newSize = zeros(1, numDims);
for i = 1:numDims
newSize(i) = inputSize(i) + 2 * padSizesPerDim(i);
end
% Create a new array of zeros with the calculated new size, preserving class
paddedArray = zeros(newSize, class(inputArray));
% Determine the indices to place the original array
startIndices = padSizesPerDim + 1;
endIndices = padSizesPerDim + inputSize;
% Construct the cell array for indexing
idx = cell(1, numDims);
for i = 1:numDims
idx{i} = startIndices(i):endIndices(i);
end
% Place the original array into the center of the new zero-padded array
paddedArray(idx{:}) = inputArray;
end
end
methods
function y = ADNode(x, root, func)
%% create new node
if nargin > 1
y.func = func;
y.root = root;
root.tape{end+1} = y;
else
y.root = y;
y.tape = {};
% y.grad = eye(numel(x));
end
y.value = x;
end
function dy = backprop(x, dy)
%% backpropagate the gradient by evaluating the tape backwards
if nargin > 1
x.grad = dy;
else
x.grad = 1;
end
for k = length(x.root.tape):-1:1
x.root.tape{k}.func(x.root.tape{k});
x.root.tape(k) = [];
end
dy = x.root.grad;
if size(dy) ~= size(x.root.value)
if size(dy) == ones(1, ndims(dy))
dy = repmat(dy, size(x.root.value));
elseif size(dy, 1) == 1 && size(x.root.value, 1) ~= 1
dy = repmat(dy, size(x.root.value, 1), 1);
elseif size(dy, 2) == 1 && size(x.root.value, 2) ~= 1
dy = repmat(dy, 1, size(x.root.value, 2));
end
end
end
function y = reshape(x, varargin)
y = ADNode(reshape(x.value, varargin{:}), x.root, @(y) x.add(reshape(y.grad, size(x.value))));
end
function y = tanh(x)
y = ADNode(tanh(x.value), x.root, @(y) x.add(bsxfun(@times, y.grad, sech((x.value)) .^ 2)));
end
function y = sum(x, dim, flag)
switch nargin
case 3
y = ADNode(sum(x.value, dim, flag), x.root, @(y) x.add(y.grad .* ones(size(x.value))));
case 2
y = ADNode(sum(x.value, dim), x.root, @(y) x.add(y.grad .* ones(size(x.value))));
otherwise
y = ADNode(sum(x.value), x.root, @(y) x.add(y.grad .* ones(size(x.value))));
end
end
function y = abs(x)
y = ADNode(abs(x.value), x.root, @(y) x.add(bsxfun(@times, y.grad, sign(x.value))));
end
function y = cabs(x)
y = ADNode(abs(x.value), x.root, @(y) x.add(bsxfun(@times, real(y.grad), bsxfun(@rdivide, x.value, abs(x.value)))));
end
function y = acos(x)
y = ADNode(acos(x.value), x.root, @(y) x.add(bsxfun(@rdivide, -y.grad, sqrt(1-x.value.^2))));
end
function y = asin(x)
y = ADNode(asin(x.value), x.root, @(y) x.add(bsxfun(@rdivide, y.grad, sqrt(1-x.value.^2))));
end
function y = atan(x)
y = ADNode(atan(x.value), x.root, @(y) x.add(bsxfun(@rdivide, y.grad, (1+x.value.^2))));
end
function y = cos(x)
y = ADNode(cos(x.value), x.root, @(y) x.add(bsxfun(@times, -y.grad, sin(x.value))));
end
function backprop_soft_well(x, lower, upper, scale, y, lg, d_low, d_high)
if lg == true
deriv = 2 * d_low ./ (scale^2 + d_low.^2) - 2*d_high ./ (scale^2 + d_high.^2);
else
deriv = -(2 * (lower + upper - 2 * x.value)) / scale^2;
end
x.add(y.grad .* deriv);
end
function y = soft_well(x, lower, upper, scale, lg)
xv = x.value;
mid_dist = (upper - lower) / 2;
d_low = xv - lower;
d_high = upper - xv;
if lg == true
bf_i = log(1 + (d_low / scale).^2) + log(1 + (d_high / scale).^2);
C_i = 2 * log(1 + (mid_dist / scale).^2);
else
bf_i = (1 + (d_low / scale).^2) + (1 + (d_high / scale).^2);
C_i = 2 * (1 + (mid_dist / scale).^2);
end
bf = bf_i - C_i;
y = ADNode(bf, x.root, @(y) backprop_soft_well(x, lower, upper, scale, y, lg, d_low, d_high));
end
function backprop_sinc(x, y, i)
val = cos(pi * x.value) ./ x.value - sin(pi * x.value) ./ ((x.value.^2) * pi);
val(i) = 0;
x.add(bsxfun(@times, y.grad, val));
end
function y = sinc(x)
tmp = x.value;
i = find(tmp == 0);
out = sin(pi*tmp)./(pi*tmp);
out(i) = 1;
y = ADNode(out, x.root, @(y) backprop_sinc(x, y, i));
end
function backprop_atan2(x1, x2, y)
x1.add(y.grad .* x2.value ./ (x1.value .* x1.value + x2.value .* x2.value));
x2.add(y.grad .* -x1.value ./ (x1.value .* x1.value + x2.value .* x2.value));
end
function y = atan2(x1, x2)
if isa(x1, 'ADNode')
if isa(x2, 'ADNode')
y = ADNode(atan2(x1.value, x2.value), x1.root, @(y) backprop_atan2(x1, x2, y));
else
y = ADNode(atan2(x1.value, x2), x1.root, @(y) x1.add(y.grad .* x2 ./ (x1.value .* x1.value + x2 .* x2)));
end
else
y = ADNode(atan2(x1, x2.value), x2.root, @(y) x2.add(y.grad .* -x1 ./ (x1 .* x1 + x2.value .* x2.value)));
end
end
function y = magPhaseCplx(mag, phi)
% f(mag,phi) = mag .* exp(1j*phi)
%
% This overload handles three cases:
% 1) both mag and phi are ADNode
% 2) only mag is ADNode (phi is constant)
% 3) only phi is ADNode (mag is constant)
%
% In all cases, the “root” pointer is taken from whichever input is an ADNode.
if isa(mag, 'ADNode') && isa(phi, 'ADNode')
% both are ADNode
E = exp(1j * phi.value);
val = mag.value .* E;
y = ADNode(val, mag.root, @(y) backprop_magPhaseCplx(mag, phi, y, E));
elseif isa(mag, 'ADNode')
% mag is ADNode, phi is a plain scalar (or array)
val = mag.value .* exp(1j * phi);
y = ADNode(val, mag.root, @(y) mag.add(y.grad .* exp(1j * phi)));
elseif isa(phi, 'ADNode')
% phi is ADNode, mag is a plain scalar (or array)
val = mag .* exp(1j * phi.value);
y = ADNode(val, phi.root, @(y) phi.add(y.grad .* (mag .* 1j .* exp(1j * phi.value))));
else
% neither is an ADNode → constant output; no gradients attached
y = mag .* exp(1j * phi);
end
end
function backprop_magPhaseCplx(mag, phi, y, E)
% “Push‐back” for y = mag .* exp(1j * phi)
% ∂y/∂mag = exp(jφ)
% ∂y/∂φ = mag .* j .* exp(jφ)
%
% y.grad is ∂L/∂y coming from upstream; we multiply by the local Jacobians
%
% Note: mag.value and phi.value are the stored forward values, so
% exp(1j*phi.value) was computed in the forward pass.
% ∂L/∂mag += (∂L/∂y) .* (∂y/∂mag) = y.grad .* E
mag.add(y.grad .* E);
% ∂L/∂φ += (∂L/∂y) .* (∂y/∂φ) = y.grad .* (mag.value .* j .* E)
phi.add(y.grad .* (mag.value .* 1j .* E));
end
%===============================================
% 1) Hard floor / round / ceil (zero‐gradient)
%===============================================
function y = floor(x)
xv = x.value;
out = floor(xv);
y = ADNode(out, x.root, @(y) backprop_floor(x, y));
end
function backprop_floor(x, y)
% d floor(x)/dx = 0 almost everywhere
x.add( zeros(size(x.value)) );
end
function y = round(x)
xv = x.value;
out = round(xv);
y = ADNode(out, x.root, @(y) backprop_round(x, y));
end
function backprop_round(x, y)
% d round(x)/dx = 0 almost everywhere
x.add( zeros(size(x.value)) );
end
function y = ceil(x)
xv = x.value;
out = ceil(xv);
y = ADNode(out, x.root, @(y) backprop_ceil(x, y));
end
function backprop_ceil(x, y)
% d ceil(x)/dx = 0 almost everywhere
x.add( zeros(size(x.value)) );
end
%===============================================
% 2) Smooth floor / round / ceil via trig‐saw
%===============================================
function y = floor_smooth(x, delta)
% wrapper for [yf, dyf] = floor_smooth_trig(x, delta)
xv = x.value;
[yf, dyf] = floor_smooth_trig(xv, delta);
y = ADNode(yf, x.root, @(y) backprop_floor_smooth(x, y, dyf));
end
function backprop_floor_smooth(x, y, dyf)
% x.add( y.grad .* dyf )
x.add( y.grad .* dyf );
end
function y = round_smooth(x, delta)
% round_smooth(x) = floor_smooth(x + 0.5)
xv = x.value;
[yf, dyf] = floor_smooth_trig(xv + 0.5, delta);
y = ADNode(yf, x.root, @(y) backprop_round_smooth(x, y, dyf));
end
function backprop_round_smooth(x, y, dyf)
% d/dx floor_smooth(x+0.5) = dyf * 1
x.add( y.grad .* dyf );
end
function y = ceil_smooth(x, delta)
% ceil_smooth(x) = -floor_smooth(-x)
xv = x.value;
[yf, dyf] = floor_smooth_trig(-xv, delta);
out = -yf;
y = ADNode(out, x.root, @(y) backprop_ceil_smooth(x, y, dyf));
end
function backprop_ceil_smooth(x, y, dyf)
% d/dx [ -floor_smooth(-x) ] = -[ dyf * (-1) ] = dyf
x.add( y.grad .* dyf );
end
%===============================================
% 1) Hard anti‐wrap
%===============================================
function y = anti_wrap(x)
% Forward: y = abs( x - round(x/(2π))⋅2π )
xv = x.value;
k = round(xv/(2*pi));
residual = xv - k*(2*pi);
out = abs(residual);
% Build ADNode, attach backprop
y = ADNode(out, x.root, @(y) backprop_anti_wrap(x, y));
end
function backprop_anti_wrap(x, y)
% Compute d/dx [ abs(x - round(x/(2π))⋅2π) ] = sign(residual)
xv = x.value;
k = round(xv/(2*pi));
residual = xv - k*(2*pi);
sgn = sign(residual); % MATLAB: sign(0)==0
% Chain rule
x.add( y.grad .* sgn );
end
%===============================================
% 2) Smooth anti‐wrap via floor_smooth_trig
%===============================================
function y = anti_wrap_smooth(x, delta)
xv = x.value;
two_pi = 2*pi;
z = xv / two_pi;
% 1) smooth‐round: k_smooth ≈ round(z)
[k_smooth, dk_smooth] = floor_smooth_trig(z + 0.5, delta);
% 2) residual = x - 2π*k_smooth
residual = xv - two_pi * k_smooth;
% 3) output = abs(residual)
out = abs(residual);
% Wrap into ADNode
y = ADNode(out, x.root, @(y) backprop_anti_wrap_smooth(x, y, dk_smooth, residual));
end
function backprop_anti_wrap_smooth(x, y, dk_smooth, residual)
% d(residual)/dx = 1 - dk_smooth
dres_dx = 1 - dk_smooth;
% d|r|/dr = sign(residual)
sgn = sign(residual);
% chain
x.add( y.grad .* (sgn .* dres_dx) );
end
% function y = ff2(x, y)
% x.add(conj(y.grad));
% end
% function y = conj(x)
% y = ADNode(conj(x.value), x.root, @(y) ff2(x, y));
% end
function halfSpectrumReflect(x, y, NFFT)
tmp = y.grad;
if mod(NFFT,2) == 0
halfLen = (NFFT/2)+1;
tmp(halfLen+1:NFFT, :) = 0;
tmp2 = fft(tmp);
tmp2 = flipud(circshift(tmp2, -1));
else
halfLen = (NFFT+1)/2;
tmp(halfLen+1:NFFT, :) = 0;
tmp2 = fft(tmp);
tmp2 = circshift(flipud(tmp2), 1);
end
tmp2 = real(tmp2);
x.add(tmp2);
end
function y = rfft(x, NFFT)
tmp = fft(x.value);
if mod(NFFT, 2)==0
halfLen = (NFFT/2)+1;
else
halfLen = (NFFT+1)/2;
end
y = ADNode(tmp(1 : halfLen, :), x.root, @(y) halfSpectrumReflect(x, y, NFFT));
end
function backprop_svfFilter(x, y, input, b0, d1, d2, c1, c2, y2, z1_A, z2_A, coeff_b0, coeff_d1, coeff_d2, coeff_c1, coeff_c2, initialValueZ1, initialValueZ2, ltv, parallelFilter, reverseFilter, reqGrad)
if reverseFilter
tmp2_grad = flipud(y.grad);
else
tmp2_grad = y.grad;
end
[~, nSections] = size(b0);
[m, nSigs] = size(input);
b0_grad = zeros(m, nSections);d1_grad = zeros(m, nSections);d2_grad = zeros(m, nSections);c1_grad = zeros(m, nSections);c2_grad = zeros(m, nSections);
z2_A_grad = zeros(nSections, nSigs);z1_A_grad = zeros(nSections, nSigs);y2_grad = zeros(nSections, nSigs);section_grad = zeros(nSections, nSigs);input_grad = zeros(m, nSigs);
for a = m : -1 : 2
gd = tmp2_grad(a, :);
for idx = nSections : -1 : 1
d2_grad(a, idx) = d2_grad(a, idx) + sum(gd .* z2_A(a, :, idx));
d1_grad(a, idx) = d1_grad(a, idx) + sum(gd .* z1_A(a, :, idx));
b0_grad(a, idx) = b0_grad(a, idx) + sum(gd .* y2(a, :, idx));
section_grad(idx, :) = y2_grad(idx, :) + gd .* b0(a, idx);
z2_A_grad(idx, :) = z2_A_grad(idx, :) + gd .* d2(a, idx) - section_grad(idx, :);
z1_A_grad(idx, :) = z1_A_grad(idx, :) + gd .* d1(a, idx) - section_grad(idx, :);
if parallelFilter == 0
gd = section_grad(idx, :);
end
c1_grad(a - 1, idx) = c1_grad(a - 1, idx) + sum(z1_A_grad(idx, :) .* y2(a - 1, :, idx));
y2_grad(idx, :) = z1_A_grad(idx, :) .* c1(a - 1, idx);
c2_grad(a - 1, idx) = c2_grad(a - 1, idx) + sum(z2_A_grad(idx, :) .* z1_A(a - 1, :, idx));
z1_A_grad(idx, :) = z1_A_grad(idx, :) + z2_A_grad(idx, :) .* c2(a - 1, idx);
end
if parallelFilter == 1
input_grad(a, :) = input_grad(a, :) + sum(section_grad, 1);
else
input_grad(a, :) = input_grad(a, :) + section_grad(1, :);
end
end
gd = tmp2_grad(1, :);
for idx = nSections : -1 : 1
d2_grad(1, idx) = d2_grad(1, idx) + sum(gd .* z2_A(1, :, idx));
d1_grad(1, idx) = d1_grad(1, idx) + sum(gd .* z1_A(1, :, idx));
b0_grad(1, idx) = b0_grad(1, idx) + sum(gd .* y2(1, :, idx));
section_grad(idx, :) = y2_grad(idx, :) + gd * b0(1, idx);
z2_A_grad(idx, :) = z2_A_grad(idx, :) + gd .* d2(1, idx) - section_grad(idx, :);
z1_A_grad(idx, :) = z1_A_grad(idx, :) + gd .* d1(1, idx) - section_grad(idx, :);
if parallelFilter == 0
gd = section_grad(idx, :);
end
end
if parallelFilter == 1
input_grad(1, :) = input_grad(1, :) + sum(section_grad, 1);
else
input_grad(1, :) = input_grad(1, :) + section_grad(1, :);
end
if reverseFilter
b0_grad = flipud(b0_grad);d1_grad = flipud(d1_grad);d2_grad = flipud(d2_grad);c1_grad = flipud(c1_grad);c2_grad = flipud(c2_grad);input_grad = flipud(input_grad);
end
if ~ltv
b0_grad = sum(b0_grad, 1);d1_grad = sum(d1_grad, 1);d2_grad = sum(d2_grad, 1);c1_grad = sum(c1_grad, 1);c2_grad = sum(c2_grad, 1);
end
z2_A_grad = z2_A_grad.';z1_A_grad = z1_A_grad.';
if reqGrad(1)
x.add(input_grad);
end
if reqGrad(2)
coeff_b0.add(b0_grad);
end
if reqGrad(3)
coeff_d1.add(d1_grad);
end
if reqGrad(4)
coeff_d2.add(d2_grad);
end
if reqGrad(5)
coeff_c1.add(c1_grad);
end
if reqGrad(6)
coeff_c2.add(c2_grad);
end
if reqGrad(7)
initialValueZ1.add(z1_A_grad);
end
if reqGrad(8)
initialValueZ2.add(z2_A_grad);
end
end
function y = svfFilter(x, coeff_b0, coeff_d1, coeff_d2, coeff_c1, coeff_c2, initialValueZ1, initialValueZ2, parallelFilter, reverseFilter)
reqGrad = [isa(x,'ADNode'),isa(coeff_b0,'ADNode'),isa(coeff_d1,'ADNode'),isa(coeff_d2,'ADNode'),...
isa(coeff_c1,'ADNode'),isa(coeff_c2,'ADNode'),isa(initialValueZ1,'ADNode'),isa(initialValueZ2,'ADNode')];
if reqGrad(1)
input = x.value;
else
input = x;
end
if reqGrad(2)
b0 = coeff_b0.value;
else
b0 = coeff_b0;
end
[nCoeff, nSections] = size(b0);
[m, nSigs] = size(input);
if nCoeff == m
ltv = 1;
elseif nCoeff == 1
ltv = 0;
else
error('Coefficient length must either be equal to signal length or equal to 1');
return;
end
if reqGrad(3)
d1 = coeff_d1.value;
else
d1 = coeff_d1;
end
if reqGrad(4)
d2 = coeff_d2.value;
else
d2 = coeff_d2;
end
if reqGrad(5)
c1 = coeff_c1.value;
else
c1 = coeff_c1;
end
if reqGrad(6)
c2 = coeff_c2.value;
else
c2 = coeff_c2;
end
if any(~([nCoeff, nSections] == size(d1))) || any(~([nCoeff, nSections] == size(d2))) || any(~([nCoeff, nSections] == size(c1))) || any(~([nCoeff, nSections] == size(c2)))
error('All IIR coefficients must has same size')
end
if ~ltv
b0 = repmat(b0, [m, 1]);
d1 = repmat(d1, [m, 1]);
d2 = repmat(d2, [m, 1]);
c1 = repmat(c1, [m, 1]);
c2 = repmat(c2, [m, 1]);
end
if reqGrad(7)
z1 = initialValueZ1.value;
else
z1 = initialValueZ1;
end
if reqGrad(8)
z2 = initialValueZ2.value;
else
z2 = initialValueZ2;
end
z1_A = zeros(m, nSigs, nSections);z2_A = zeros(m, nSigs, nSections);
if numel(z1) == 1 || numel(z1) == (m * nSigs * nSections)
z1_A(1, :, :) = z1;
else
for idx = 1 : nSections
z1_A(1, :, idx) = z1(:, idx);
end
end
if numel(z2) == 1 || numel(z2) == (m * nSigs * nSections)
z2_A(1, :, :) = z2;
else
for idx = 1 : nSections
z2_A(1, :, idx) = z2(:, idx);
end
end
y2 = zeros(m, nSigs, nSections);
if reverseFilter
input = flipud(input);b0 = flipud(b0);d1 = flipud(d1);d2 = flipud(d2);c1 = flipud(c1);c2 = flipud(c2);
end
% Forward filtering
tmp2 = zeros(m, nSigs);
if parallelFilter == 1
out = zeros(nSections, nSigs);
for a = 1 : m - 1
in = input(a, :);
for idx = 1 : nSections
y2(a, :, idx) = in - z1_A(a, :, idx) - z2_A(a, :, idx);
out(idx, :) = b0(a, idx) .* y2(a, :, idx) + d1(a, idx) .* z1_A(a, :, idx) + d2(a, idx) .* z2_A(a, :, idx);
z2_A(a + 1, :, idx) = z2_A(a, :, idx) + c2(a, idx) .* z1_A(a, :, idx);
z1_A(a + 1, :, idx) = z1_A(a, :, idx) + c1(a, idx) .* y2(a, :, idx);
end
tmp2(a, :) = sum(out, 1);
end
in = input(m, :);
for idx = 1 : nSections
y2(m, :, idx) = in - z1_A(m, :, idx) - z2_A(m, :, idx);
out(idx, :) = b0(m, idx) .* y2(m, :, idx) + d1(m, idx) .* z1_A(m, :, idx) + d2(m, idx) .* z2_A(m, :, idx);
end
tmp2(m, :) = sum(out, 1);
else
for a = 1 : m - 1
in = input(a, :);
for idx = 1 : nSections
y2(a, :, idx) = in - z1_A(a, :, idx) - z2_A(a, :, idx);
in = b0(a, idx) .* y2(a, :, idx) + d1(a, idx) .* z1_A(a, :, idx) + d2(a, idx) .* z2_A(a, :, idx);
z2_A(a + 1, :, idx) = z2_A(a, :, idx) + c2(a, idx) .* z1_A(a, :, idx);
z1_A(a + 1, :, idx) = z1_A(a, :, idx) + c1(a, idx) .* y2(a, :, idx);
end
tmp2(a, :) = in;
end
in = input(m, :);
for idx = 1 : nSections
y2(m, :, idx) = in - z1_A(m, :, idx) - z2_A(m, :, idx);
in = b0(m, idx) .* y2(m, :, idx) + d1(m, idx) .* z1_A(m, :, idx) + d2(m, idx) .* z2_A(m, :, idx);
end
tmp2(m, :) = in;
end
if reverseFilter
tmp2 = flipud(tmp2);
end
y = ADNode(tmp2, coeff_b0.root, @(y) backprop_svfFilter(x, y, input, b0, d1, d2, c1, c2, y2, z1_A, z2_A, coeff_b0, coeff_d1, coeff_d2, coeff_c1, coeff_c2, initialValueZ1, initialValueZ2, ltv, parallelFilter, reverseFilter, reqGrad));
end
function halfSpectrumFold2(xRe, xIm, y, NFFT)
tmp = ifft(y.grad);
if mod(NFFT, 2) == 0
halfLen = (NFFT/2)+1;
tmp = tmp(1 : halfLen, :, :);
tmp(2 : end - 1, :, :) = tmp(2 : end - 1, :, :) * 2;
else
halfLen = (NFFT+1)/2;
tmp = tmp(1 : halfLen, :, :);
tmp(2 : end, :, :) = tmp(2 : end, :, :) * 2;
end
tt = -imag(tmp);
tt(1, :, :) = 0;
tt(end, :, :) = 0;
xRe.add(real(tmp));
xIm.add(tt);
end
function y = separate_irfft(xRe, xIm, NFFT)
tmp1 = xRe.value;
tmp2 = xIm.value;
tmp2(1, :, :) = 0;
tmp2(end, :, :) = 0;
if mod(NFFT,2) == 0
halfLen = (NFFT/2)+1;
tmp1(halfLen+1:NFFT, :, :) = tmp1(halfLen-1:-1:2, :, :);
tmp2(halfLen+1:NFFT, :, :) = -tmp2(halfLen-1:-1:2, :, :);
else
halfLen = (NFFT+1)/2;
tmp1(halfLen+1:NFFT, :, :) = tmp1(halfLen:-1:2, :, :);
tmp2(halfLen+1:NFFT, :, :) = -tmp2(halfLen:-1:2, :, :);
end
y = ADNode(ifft(tmp1 + tmp2 * 1j), xRe.root, @(y) halfSpectrumFold2(xRe, xIm, y, NFFT));
end
function y = fft(x)
y = ADNode(fft(x.value), x.root, @(y) x.add(fft(y.grad)));
end
function y = ifft(x)
y = ADNode(ifft(x.value), x.root, @(y) x.add(ifft(y.grad)));
end
function y = real(x)
y = ADNode(real(x.value), x.root, @(y) x.add(real(y.grad)));
end
function y = imag(x)
y = ADNode(imag(x.value), x.root, @(y) x.add(complex(0, y.grad)));
end
function y = conj(x)
y = ADNode(conj(x.value), x.root, @(y) x.add(conj(y.grad)));
end
function y = revWndAcc(x, y, frameSize, hop)
tmp = y.grad;
rec = buffer(tmp, frameSize, frameSize - hop);
cutted = rec(:, frameSize / hop : end);
x.add(cutted);
end
function y = fold(x, frameSize, hop) % Sum sliding window
y = ADNode(overlapAdd(x.value, hop), x.root, @(y) revWndAcc(x, y, frameSize, hop));
end
function y = revWndAcc3D(x, y, frameSize, hop)
tmp = y.grad;
% idealBufferOutLen = ceil((size(tmp, 1)-(frameSize - hop))/(frameSize-(frameSize - hop)));
requiredBufferOutLen = size(x, 2);
cutLen = ceil(size(tmp, 1) / hop) - requiredBufferOutLen;
rec = zeros(frameSize, ceil(size(tmp, 1) / hop), size(tmp, 2));
for idx = 1 : size(tmp, 2)
rec(:, :, idx) = buffer(tmp(:, idx), frameSize, frameSize - hop);
end
% cutted = rec(:, frameSize / hop : end, :);
cutted = rec(:, cutLen + 1 : end, :);
x.add(cutted);
end
function y = fold3D(x, frameSize, hop) % Sum sliding window
y = ADNode(overlapAdd3D(x.value, hop), x.root, @(y) revWndAcc3D(x, y, frameSize, hop));
end
function backprop_logFourier(b0, b1, b2, a1, a2, y, phi, lg10, bSumV, aSumV, numerator, denominator, term2V, term3V, term6V, b0V, b1V, b2V, a1V)
numBands = length(b0.value);
reducedSumGrad = lg10 * repmat(y.grad, numBands, 1);
%% Logarithmic Fourier transform partial derivatives
term11Grad = reducedSumGrad ./ max(numerator, eps);
term20Grad = -reducedSumGrad ./ max(denominator, eps);
b0Grad = term11Grad .* bSumV * 2;
b1Grad = term11Grad .* bSumV * 2;
b2Grad = term11Grad .* bSumV * 2;
a1Grad = term20Grad .* aSumV * 2;
a2Grad = term20Grad .* aSumV * 2;
term5Grad = term11Grad .* phi;
term1Grad = term5Grad .* phi;
termGrad = term20Grad .* phi;
term5b1V = -term5Grad .* b1V;
b1.grad = b1Grad + -term5Grad .* term2V;
b0Grad = b0Grad + term5b1V + 4 * -term5Grad .* b2V;
b2Grad = b2Grad + term5b1V + -term5Grad .* term3V;
b0.grad = b0Grad + term1Grad .* b2V;
b2.grad = b2Grad + term1Grad .* b0V;
a1.grad = a1Grad + -termGrad .* term6V;
a2.grad = a2Grad + 4 * -termGrad + -termGrad .* a1V + termGrad .* phi;
end
function y = logFourier(b0, b1, b2, a1, a2, phi, lg10)
a1V = a1.value;
a2V = a2.value;
b0V = b0.value;
b1V = b1.value;
b2V = b2.value;
%%
aSumV = 1 + a1V + a2V;
bSumV = b0V + b1V + b2V;
term1 = b0V .* b2V;
term2V = b0V + b2V;
term3V = 4 * b0V;
term4 = term3V .* b2V;
numerator = bSumV .* bSumV + ((term1 .* phi - b1V .* term2V - term4) .* phi);
term6V = 1 + a2V;
denominator = aSumV .* aSumV + (a2V .* phi - (a1V .* term6V + a2V * 4)) .* phi;
numerator(numerator <= 0) = realmin; % eps? realmin?
denominator(denominator <= 0) = realmin; % eps? realmin?
eq_op = log(numerator) - log(denominator);
reducedSum = sum(eq_op * lg10, 1);
y = ADNode(reducedSum, b0.root, @(y) backprop_logFourier(b0, b1, b2, a1, a2, y, phi, lg10, bSumV, aSumV, numerator, denominator, term2V, term3V, term6V, b0V, b1V, b2V, a1V));
end
function backprop_logFourier2(b0V_node, b1V_node, b2V_node, a1V_node, a2V_node, reducedSum_node, ...
dreducedSum_db0V, dreducedSum_db1V, dreducedSum_db2V, dreducedSum_da1V, dreducedSum_da2V)
% Get the incoming gradient from the next layer (dL/d(reducedSum))
dL_dreducedSum = reducedSum_node.grad;
% Apply the chain rule: dL/d(input_i) += dL/d(reducedSum) * d(reducedSum)/d(input_i)
b0V_node.add(dL_dreducedSum .* dreducedSum_db0V);
b1V_node.add(dL_dreducedSum .* dreducedSum_db1V);
b2V_node.add(dL_dreducedSum .* dreducedSum_db2V);
a1V_node.add(dL_dreducedSum .* dreducedSum_da1V);
a2V_node.add(dL_dreducedSum .* dreducedSum_da2V);
end
function reducedSum_node = logFourier2(b0V_node, b1V_node, b2V_node, a1V_node, a2V_node, phi, lg10)
b0V_val = b0V_node.value;
b1V_val = b1V_node.value;
b2V_val = b2V_node.value;
a1V_val = a1V_node.value;
a2V_val = a2V_node.value;
aSumV = 1 + a1V_val + a2V_val;
bSumV = b0V_val + b1V_val + b2V_val;
term1 = b0V_val .* b2V_val;
term2V = b0V_val + b2V_val;
term3V = 4 * b0V_val;
term4 = term3V .* b2V_val;
a2v2 = 2 * a2V_val;
a2v4 = 2 * a2v2;
t1phi = term1 .* phi;
t2phi = a2V_val .* phi;
t3phi = b1V_val .* phi;
bbSum = bSumV .* bSumV;
b1t2 = b1V_val .* term2V;
numerator = bbSum + ((t1phi - b1t2 - term4) .* phi);
term6V = 1 + a2V_val;
denominator = aSumV .* aSumV + (t2phi - (a1V_val .* term6V + a2v4)) .* phi;
numerator(numerator <= 0) = realmin; % eps? realmin?
denominator(denominator <= 0) = realmin; % eps? realmin?
eq_op = log(numerator) - log(denominator);
reducedSumV = sum(eq_op * lg10, 1); % sum(scalar, 1) is just the scalar
pp4_2 = phi .* (phi - 4) + 2;
common_den_b = (phi.*(4 * term1 + b1t2 - t1phi) - bbSum) / lg10;
common_den_b = min(common_den_b, -eps);
twob0b1 = 2 * (b0V_val + b1V_val);
% Derivative with respect to b0V
dreducedSum_db0V = -((twob0b1 - t3phi) + b2V_val.* pp4_2)./common_den_b;
% Derivative with respect to b1V
dreducedSum_db1V = -((twob0b1 + 2*b2V_val) - phi.*term2V)./common_den_b;
% Derivative with respect to b2V
dreducedSum_db2V = -((2 * (b1V_val + b2V_val) - t3phi) + b0V_val.* pp4_2)./common_den_b;
% Common denominator for a-coefficient derivatives
common_den_a = ((a1V_val + term6V).^2 - phi .* (a2v4 - t2phi + a1V_val.*term6V)) / lg10;
common_den_a = max(common_den_a, eps);
% Derivative with respect to a1V
dreducedSum_da1V = -(2*a1V_val + a2v2 - phi .* term6V + 2)./common_den_a;
% Derivative with respect to a2V
dreducedSum_da2V = -((a2v2 + pp4_2) - a1V_val.*(phi - 2))./common_den_a;
reducedSum_node = ADNode(reducedSumV, b0V_node.root, @(y_node) backprop_logFourier2(b0V_node, b1V_node, b2V_node, a1V_node, a2V_node, y_node, ...
dreducedSum_db0V, dreducedSum_db1V, dreducedSum_db2V, dreducedSum_da1V, dreducedSum_da2V));
end
function gdB = grpdelay(b0_arg, b1_arg, b2_arg, a1_arg, a2_arg, sw, sw2, cw, cw2)
is_b0_node = isa(b0_arg, 'ADNode');
is_b1_node = isa(b1_arg, 'ADNode');
is_b2_node = isa(b2_arg, 'ADNode');
is_a1_node = isa(a1_arg, 'ADNode');
is_a2_node = isa(a2_arg, 'ADNode');
b0_val = b0_arg;
b1_val = b1_arg;
b2_val = b2_arg;
a1_val = a1_arg;
a2_val = a2_arg;
if is_b0_node, b0_val = b0_arg.value; end
if is_b1_node, b1_val = b1_arg.value; end
if is_b2_node, b2_val = b2_arg.value; end
if is_a1_node, a1_val = a1_arg.value; end
if is_a2_node, a2_val = a2_arg.value; end
% Numerator GD
u_b = b0_val .* sw2 + b1_val .* sw;
v_b = b0_val .* cw2 + b1_val .* cw + b2_val;
du_b = 2.0 .* b0_val .* cw2 + b1_val .* cw;
dv_b = -(2.0 .* b0_val .* sw2 + b1_val .* sw);
u2v2_b = (b0_val.^2) + (b1_val.^2) + (b2_val.^2) + 2.0 .* (b0_val.*b1_val + b1_val.*b2_val) .* cw + 2.0 .* (b0_val.*b2_val) .* cw2;
gdB_num = (2.0 - (v_b .* du_b - u_b .* dv_b) ./ u2v2_b);
% Denominator GD
u_a = sw2 + a1_val .* sw;
v_a = cw2 + a1_val .* cw + a2_val;
du_a = 2.0 .* cw2 + a1_val .* cw;
dv_a = -(2.0 .* sw2 + a1_val .* sw);
u2v2_a = 1.0 + (a1_val.^2) + (a2_val.^2) + 2.0 .* (a1_val + a1_val .* a2_val) .* cw + 2.0 .* a2_val .* cw2;
gdB_den = (2.0 - (v_a .* du_a - u_a .* dv_a) ./ u2v2_a);
% Final group delay is the difference
gdB_val = gdB_num - gdB_den;
% --- 3. Determine if we need to create an ADNode output ---
if ~is_b0_node && ~is_b1_node && ~is_b2_node && ~is_a1_node && ~is_a2_node
gdB = gdB_val;
return;
end
% --- 4. Get the root node from the ADNode inputs ---
ad_inputs = {b0_arg, b1_arg, b2_arg, a1_arg, a2_arg};
root_node = ADNode.find_ad_root(ad_inputs);
% --- 5. Create the ADNode output with the custom backprop function ---
gdB = ADNode(gdB_val, root_node, @(y_node) gd_backprop(...
b0_arg, b1_arg, b2_arg, a1_arg, a2_arg, y_node, ...
sw, sw2, cw, cw2, ...
u_b, v_b, du_b, dv_b, u2v2_b, ...
u_a, v_a, du_a, dv_a, u2v2_a));
end
function gd_backprop(b0_arg, b1_arg, b2_arg, a1_arg, a2_arg, y_node, ...
sw, sw2, cw, cw2, ...
u_b, v_b, du_b, dv_b, u2v2_b, ...
u_a, v_a, du_a, dv_a, u2v2_a)
% gd_backprop: Backpropagation function for the group delay calculation.
% Incoming gradient dL/d(gdB)
dL_d_gdB = y_node.grad;
% Pre-compute common terms from the symbolic derivations to improve readability
b0 = b0_arg.value;
b1 = b1_arg.value;
b2 = b2_arg.value;
a1 = a1_arg.value;
a2 = a2_arg.value;
% Numerator-specific terms
num_part1 = (b1 .* cw + 2 .* b0 .* cw2);
num_part2 = (b2 + b1 .* cw + b0 .* cw2);
num_part3 = (b1 .* sw + b0 .* sw2);
num_part4 = (b1 .* sw + 2 .* b0 .* sw2);
num_u2v2_denom = ( (2 .* b0 .* b1) + (2 .* b1 .* b2) ) .* cw + (b0.^2) + (b1.^2) + (b2.^2) + (2 .* b0 .* b2) .* cw2;
% Denominator-specific terms
den_u2v2_denom = (2 .* a1 + 2 .* a1 .* a2) .* cw + (2 .* a2) .* cw2 + a1.^2 + a2.^2 + 1;
den_part1 = (sw2 + a1 .* sw);
den_part2 = (2 .* sw2 + a1 .* sw);
den_part3 = (2 .* cw2 + a1 .* cw);
den_part4 = (a2 + cw2 + a1 .* cw);
% --- Gradients with respect to the b_i coefficients (Numerator) ---
if isa(b0_arg, 'ADNode')
% Correct derivative d(gdB)/db0
J_b0_sym_term1 = (num_part1 .* num_part2 + num_part3 .* num_part4) .* (2 .* b0 + 2 .* b1 .* cw + 2 .* b2 .* cw2);
J_b0_sym_term2 = (2 .* b2 .* cw2 + 3 .* b1 .* (cw .* cw2 + sw .* sw2) + 4 .* b0 .* (cw2.^2 + sw2.^2));
J_b0 = J_b0_sym_term1 ./ (num_u2v2_denom.^2) - J_b0_sym_term2 ./ num_u2v2_denom;
b0_arg.add(dL_d_gdB .* J_b0);
end
if isa(b1_arg, 'ADNode')
% Correct derivative d(gdB)/db1
J_b1_sym_term1 = (num_part1 .* num_part2 + num_part3 .* num_part4) .* (2 .* b1 + cw .* (2 .* b0 + 2 .* b2));
J_b1_sym_term2 = (b2 .* cw + 3 .* b0 .* (cw .* cw2 + sw .* sw2) + 2 .* b1 .* (cw.^2 + sw.^2));
J_b1 = J_b1_sym_term1 ./ (num_u2v2_denom.^2) - J_b1_sym_term2 ./ num_u2v2_denom;
b1_arg.add(dL_d_gdB .* J_b1);
end
if isa(b2_arg, 'ADNode')
% Correct derivative d(gdB)/db2
J_b2_sym_term1 = (num_part1 .* num_part2 + num_part3 .* num_part4) .* (2 .* b2 + 2 .* b1 .* cw + 2 .* b0 .* cw2);
J_b2_sym_term2 = (b1 .* cw + 2 .* b0 .* cw2);
J_b2 = J_b2_sym_term1 ./ (num_u2v2_denom.^2) - J_b2_sym_term2 ./ num_u2v2_denom;
b2_arg.add(dL_d_gdB .* J_b2);
end
% --- Gradients with respect to the a_i coefficients (Denominator) ---
if isa(a1_arg, 'ADNode')
% Correct derivative d(gdB)/da1
J_a1_sym_term1 = (den_part1 .* den_part2 + den_part3 .* den_part4) .* (2 .* a1 + 2 .* cw .* (a2 + 1));
J_a1_sym_term2 = (a2 .* cw + 3 .* cw .* cw2 + 3 .* sw .* sw2 + 2 .* a1 .* (cw.^2 + sw.^2));
J_a1 = J_a1_sym_term2 ./ den_u2v2_denom - J_a1_sym_term1 ./ (den_u2v2_denom.^2);
a1_arg.add(dL_d_gdB .* J_a1);
end
if isa(a2_arg, 'ADNode')
% Correct derivative d(gdB)/da2
J_a2_sym_term1 = (den_part1 .* den_part2 + den_part3 .* den_part4) .* (2 .* a2 + 2 .* cw2 + 2 .* a1 .* cw);
J_a2_sym_term2 = (2 .* cw2 + a1 .* cw);