forked from cran/mgcv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdi.c
executable file
·3183 lines (2628 loc) · 125 KB
/
gdi.c
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
/* Copyright (C) 2007-2015 Simon N. Wood simon.wood@r-project.org
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
(www.gnu.org/copyleft/gpl.html)
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA. */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <R.h>
#include "mgcv.h"
#ifdef OPENMP_ON
#include <omp.h>
#endif
#define ANSI
/*#define DEBUG*/
double trBtAB(double *A,double *B,int *n,int*m)
/* form tr(B'AB) where A is n by n and B is n by m, m < n,
basic point is that this is sum_ijk A_ik B_ij B_kj
*/
{ double tr=0.0,x,*p,*p1,*p2;
int j,k;
for (j=0;j<*m;j++)
for (k=0;k<*n;k++) {
p = A + *n * k;p2 = p + *n;
p1 = B + *n * j;
x = B[k + j * *n];
for (;p<p2;p++,p1++) tr += *p * *p1 * x;
}
return(tr);
}
void multSk(double *y,double *x,int *xcol,int k,double *rS,int *rSncol,int *q,double *work)
/* function to form y = Sk x, where a square root of Sk
is packed somewhere inside rS. x must be q by xcol. The
kth square root is q by rSncol[k]. The square roots are packed
one after another columnwise (R default).
work and y must be the same dimension as x.
*/
{ int i,off,nc,bt,ct;
double *rSk;
off=0; /* the start of the kth square root */
for (i=0;i<k;i++) off += *q * rSncol[i];
rSk = rS + off; /* pointer to the kth square root */
nc = rSncol[k];
bt=1;ct=0;
mgcv_mmult(work,rSk,x,&bt,&ct,&nc,xcol,q);
bt=0;
mgcv_mmult(y,rSk,work,&bt,&ct,q,xcol,&nc);
}
double diagABt(double *d,double *A,double *B,int *r,int *c)
/* obtain diag(AB') as efficiently as possible, and return tr(AB') A and B are
r by c stored column-wise.
Thread safety: Modifies d. rest unmodified
*/
{ int j;
double tr=0.0,*pa,*pb,*p1,*pd;
if (*c>0) {
for (pa=A,pb=B,p1=pa + *r,pd=d;pa<p1;pa++,pb++,pd++) *pd = *pa * *pb;
for (j=1;j < *c;j++)
for (p1=d + *r,pd=d;pd<p1;pa++,pb++,pd++) *pd += *pa * *pb;
/* d now contains diag(AB') */
for (pd=d,p1=d + *r;pd < p1;pd++) tr += *pd;
}
return(tr);
}
double trAB(double *A,double *B,int *n, int *m)
/* Get tr(AB) where A is n by m and B is m by n
*/
{ double *p,*pa,*pb,tr=0.0;
int i,j;
for (pa=A,pb=B,j=0;j<*m;j++,pb++)
for (p=pb,i=0;i<*n;i++,p += *m,pa++) tr+= *p * *pa;
return(tr);
}
void get_bSb(double *bSb,double *bSb1, double *bSb2,double *sp,double *E,
double *rS,int *rSncol,int *Enrow, int *q,int *M,int *M0,
double *beta, double *b1, double *b2,int *deriv)
/*
Routine to obtain beta'Sbeta and its derivatives w.r.t. the log smoothing
parameters, this is part of REML calculation...
sp is of length M, but b1 and b2 contain derivative w.r.t. to M0 + M
parameter [theta,log sp] where theta are parameters of the likelihood,
but not the penalties. The returned bSb1 and bSb2 should contain
derivatives w.r.t. theta as well as log sp (although these derivatives
will be zero).
b1 and b2 contain first and second derivatives of q-vector beta w.r.t.
\pho_k. They are packed as follows....
* b1 will contain dbeta/d\rho_0, dbeta/d\rho_1 etc. So, for example, dbeta_i/d\rho_j
(indices starting at zero) is located in b1[q*j+i].
* b2 will contain d^2beta/d\rho_0d\rho_0, d^2beta/d\rho_1d\rho_0,... but rows will not be
stored if they duplicate an existing row (e.g. d^2beta/d\rho_0d\rho_1 would not be
stored as it already exists and can be accessed by interchanging the sp indices).
So to get d^2beta_k/d\rho_id\rho_j:
i) if i<j interchange the indices
ii) off = (j*m-(j+1)*j/2+i)*q (m is number of sp's)
iii) v2[off+k] is the required derivative.
*/
{ double *Sb,*Skb,*work,*work1,*p1,*p0,*p2,xx;
int i,j,bt,ct,one=1,m,k,rSoff,mk,km,Mtot;
j = *q; for (i=0;i<*M;i++) if (rSncol[i]>j) j = rSncol[i];
j += *M0; /* work space needed */
work = (double *)CALLOC((size_t)j,sizeof(double));
Sb = (double *)CALLOC((size_t)*q,sizeof(double));
bt=0;ct=0;mgcv_mmult(work,E,beta,&bt,&ct,Enrow,&one,q);
bt=1;ct=0;mgcv_mmult(Sb,E,work,&bt,&ct,q,&one,Enrow); /* S \hat \beta */
for (*bSb=0.0,i=0;i<*q;i++) *bSb += beta[i] * Sb[i]; /* \hat \beta' S \hat \beta */
if (*deriv <=0) {FREE(work);FREE(Sb);return;}
work1 = (double *)CALLOC((size_t)j,sizeof(double));
Skb = (double *)CALLOC((size_t)*M * *q,sizeof(double));
for (p1=Skb,rSoff=0,i=0;i<*M;i++) { /* first part of first derivatives */
/* form S_k \beta * sp[k]... */
bt=1;ct=0;mgcv_mmult(work,rS + rSoff ,beta,&bt,&ct,rSncol+i,&one,q);
for (j=0;j<rSncol[i];j++) work[j] *= sp[i];
bt=0;ct=0;mgcv_mmult(p1,rS + rSoff ,work,&bt,&ct,q,&one,rSncol+i);
rSoff += *q * rSncol[i];
/* now the first part of the first derivative */
for (xx=0.0,j=0;j<*q;j++,p1++) xx += beta[j] * *p1;
bSb1[i + *M0] = xx;
}
for (i=0;i<*M0;i++) bSb1[i] = 0.0;
Mtot = *M + *M0;
if (*deriv>1) for (m=0;m < Mtot;m++) { /* Hessian */
bt=0;ct=0;mgcv_mmult(work1,E,b1 + m * *q,&bt,&ct,Enrow,&one,q);
bt=1;ct=0;mgcv_mmult(work,E,work1,&bt,&ct,q,&one,Enrow); /* S dbeta/drho_m */
for (k=m;k < Mtot;k++) {
km= k * Mtot + m ;
mk= m * Mtot + k ; /* second derivatives needed */
/* d2beta'/drho_k drho_m S beta */
for (xx=0.0,p0=Sb,p1=Sb + *q;p0<p1;p0++,b2++) xx += *b2 * *p0;
bSb2[km] = 2*xx;
/* dbeta'/drho_k S dbeta/drho_m */
for (xx=0.0,p0=b1+ k * *q,p1=p0 + *q,p2=work;p0<p1;p0++,p2++) xx += *p2 * *p0;
bSb2[km] += 2*xx;
/* dbeta'/drho_m S_k beta sp[k] */
if (k >= *M0) {
for (xx=0.0,p0=Skb + (k- *M0) * *q,p1=p0 + *q,p2= b1+ m * *q;p0<p1;p0++,p2++)
xx += *p2 * *p0;
bSb2[km] += 2*xx;
}
/* dbeta'/drho_k S_m beta sp[m] */
if (m >= *M0) {
for (xx=0.0,p0=Skb + (m - *M0) * *q,p1=p0 + *q,p2= b1 + k * *q;p0<p1;p0++,p2++)
xx += *p2 * *p0;
bSb2[km] += 2*xx;
}
if (k==m) bSb2[km] += bSb1[k]; else bSb2[mk] = bSb2[km];
}
} /* done Hessian */
/* Now finish off the first derivatives */
bt=1;ct=0;mgcv_mmult(work,b1,Sb,&bt,&ct,&Mtot,&one,q);
for (i=0;i<Mtot;i++) bSb1[i] += 2*work[i];
FREE(Sb);FREE(work);FREE(Skb);FREE(work1);
} /* end get_bSb */
double frobenius_norm(double *X,int *r, int *c)
/* The Frobenius norm of r by c matrix X. Interestingly, this gives an
upper bound on the two norm (largest singular value).
*/
{ double fnorm=0.0,*p1;
int n;
n = *r * *c;
for (p1=X+n;X<p1;X++) fnorm += *X * *X;
return(sqrt(fnorm));
}
void pivoter(double *x,int *r,int *c,int *pivot, int *col, int *reverse)
/* Routine for pivoting or unpivoting r by c matrix x
according to what's in `pivot'.
The ith pivoted element comes from the original element pivot[i]
i.e. pivot[i] is the unpivoted element that pivoted element i
should end up in.
If `reverse' is non-zero then x is unpivoted. Otherwise pivoting is
applied.
If `col' is non zero then columns are un/pivoted, otherwise rows.
Typical applications are to pivot matrices in the same way that a
qr decomposition has been pivoted, or to reverse such a pivoting.
*/
{ double *dum,*px,*pd,*pd1,*p,*p1;
int *pi,*pi1,i,j;
if (*col) { /* pivot columns */
dum = (double *) CALLOC((size_t)*c,sizeof(double));
if (*reverse) /* unpivot x */
for (i=0;i< *r;i++) {
for (px=x+i,pi=pivot,pi1=pi+*c;pi<pi1;pi++,px+=*r) dum[*pi]= *px; /*dum[pivot[j]] = x[j* *r + i] */
for (px=x+i,pd=dum,pd1=dum+*c;pd<pd1;pd++,px += *r) *px = *pd; /* x[j * *r + i] = dum[j]; */
} else /* pivot x */
for (i=0;i< *r;i++) {
for (px = x+i,pd=dum,pd1=dum + *c,j=0;pd < pd1;pd++,j++) *pd = px[pivot[j] * *r];
for (px=x+i,pd=dum,pd1=dum+*c;pd<pd1;pd++,px += *r) *px = *pd; /* x[j * *r + i] = dum[j]; */
}
} else { /* pivot rows */
dum = (double *) CALLOC((size_t)*r,sizeof(double));
if (*reverse) /* unpivot x */
for (p=x,j=0;j<*c;j++,p += *r) { /* work column by column using dum as working storage */
for (pi=pivot,pi1=pi+*r,p1=p;pi<pi1;pi++,p1++) dum[*pi] = *p1; /*dum[pivot[i]] = p[i]; ith row of pivoted -> pivot[i] row of unpivoted */
for (pd=dum,pd1=dum+*r,p1=p;pd<pd1;pd++,p1++) *p1 = *pd; /* store unpivoted column in x */
} else /* pivot x */
for (p=x,j=0;j<*c;j++,p += *r) { /* work column by column using dum as working storage */
for (pi=pivot,pi1=pi+*r,pd=dum;pi<pi1;pd++,pi++) *pd = p[*pi]; /* dum[i] = p[pivot[i]]; pivot[i] row of unpivoted -> ith row of pivoted */
for (pd=dum,pd1=dum+*r,p1=p;pd<pd1;pd++,p1++) *p1 = *pd; /* store pivoted column in x */
}
}
FREE(dum);
} /* end pivoter */
double qr_ldet_inv(double *X,int *r,double *Xi,int *get_inv)
/* Obtains the log|X| and the inverse of X (r by r), by pivoted QR decomposition.
The inverse is returned (unpivoted) in Xi.
The function returns log|X| as its value.
X is overwritten in the process
*/
{ double *tau,ldet,*p,*Qt;
int *pivot,i,TRUE=1,j,FALSE=0;
/* Allocated working storage ...*/
pivot = (int *)CALLOC((size_t)*r,sizeof(int));
tau = (double *)CALLOC((size_t)*r,sizeof(double));
mgcv_qr(X,r,r,pivot,tau); /* get QR=X itself */
/* evaluate log|X| = sum_i log(|R_ii|) ...*/
for (ldet=0.0,p=X,i=0;i<*r;i++,p += *r+1) ldet += log(fabs(*p));
if (*get_inv) {
/* Now get the inverse of X. X^{-1} = R^{-1}Q' */
Qt = (double *)CALLOC((size_t)*r * *r,sizeof(double));
for (p=Qt,i=0;i<*r;i++,p += *r+1) *p = 1.0;
mgcv_qrqy(Qt,X,tau,r,r,r,&TRUE,&TRUE); /* Extracting the orthogonal factor Q' */
mgcv_backsolve(X,r,r,Qt,Xi,r,&FALSE); /* Now Xi contains the row pivoted inverse of X */
/* Finally unpivot Xi.
pivot[i] is the unpivoted row that pivoted row i should end up in
*/
for (p=Xi,j=0;j<*r;j++,p += *r) { /* work column by column using tau as working storage */
for (i=0;i<*r;i++) tau[pivot[i]] = p[i]; /* ith row of pivoted -> pivot[i] row of unpivoted */
for (i=0;i<*r;i++) p[i] = tau[i]; /* store unpivoted column in Xi */
}
FREE(Qt);
} /* end if (*get_inv) */
FREE(pivot);FREE(tau);
return(ldet);
} /* end qr_ldet_inv */
void get_detS2(double *sp,double *sqrtS, int *rSncol, int *q,int *M, int * deriv,
double *det, double *det1, double *det2, double *d_tol,
double *r_tol,int *fixed_penalty)
/* Routine to evaluate log|S| and its derivatives wrt log(sp), in a stable manner, using
an orthogonal transformation strategy based on QR decomposition.
Inputs are:
`sp' the array of smoothing parameters.
`sqrtS' the `M' square root penalty matrices. The ith is `q' by `rSncol[i]'. They are
packed one after the other.
`deriv' is the order of derivatives required. 0,1 or 2.
`d_tol' is the tolerance to use for grouping dominant terms.
`r_tol' (<< d_tol) is the tolerance used for rank determination.
`fixed_penalty' non-zero indicates that there is a fixed component of
total penalty matrix S, the square root of which is in the final
q * rSncol[M+1] elements of sqrtS.
Outputs are:
`det' the log determinant.
`det1' M-array of derivatives of log det wrt log sp.
`det2' M by M Hessian of log det wrt log sp.
*/
{ double *R,*work,*tau,*rS1,*rS2, *S,*Si,*Sb,*B,*Sg,*p,*p1,*p2,*p3,*p4,*frob,max_frob,x,*spf,Rcond;
int *pivot,iter,i,j,k,bt,ct,rSoff,K,Q,Qr,*gamma,*gamma1,*alpha,r,max_col,Mf,tot_col=0,left,tp;
if (*fixed_penalty) {
Mf = *M + 1; /* total number of components, including fixed one */
spf = (double *)CALLOC((size_t)Mf,sizeof(double));
for (i=0;i<*M;i++) spf[i]=sp[i];
spf[*M]=1.0; /* includes sp for fixed term */
}
else {spf=sp;Mf = *M;} /* total number of components, including fixed one */
/* Create working copies of sqrtS, which can be modified:
rS1 is repeatedly orthogonally transformed, while rS2 is row pivoted.
*/
if (*deriv) { /* only need to modify if derivatives needed */
for (j=i=0;i<Mf;i++) j += rSncol[i];
tot_col=j;
j *= *q;
rS1 = (double *)CALLOC((size_t) j,sizeof(double));
rS2 = (double *)CALLOC((size_t) j,sizeof(double));
for (p=rS1,p3=rS2,p1=rS1+j,p2=sqrtS;p<p1;p++,p2++,p3++) *p3 = *p = *p2;
} else {rS1=rS2=NULL;}
/* Explicitly form the Si (stored in a single block), so S_i is stored
in Si + i * q * q (starting i from 0). As iteration progresses,
blocks are shrunk -- always q by Q */
max_col = *q; /* need enough storage just in case square roots are over-sized */
for (i=0;i<Mf;i++) if (rSncol[i]>max_col) max_col=rSncol[i];
p = Si = (double *)CALLOC((size_t)*q * max_col * Mf,sizeof(double));
for (rSoff=i=0;i<Mf;p+= *q * *q,rSoff+=rSncol[i],i++) {
bt=0;ct=1;mgcv_mmult(p,sqrtS+rSoff * *q,sqrtS+rSoff * *q,&bt,&ct,q,q,rSncol+i);
}
/* Initialize the sub-dominant set gamma and the counters */
K = 0;Q = *q;
frob = (double *)CALLOC((size_t)Mf,sizeof(double));
gamma = (int *)CALLOC((size_t)Mf,sizeof(int)); /* terms remaining to deal with */
gamma1 = (int *)CALLOC((size_t)Mf,sizeof(int)); /* new gamma */
alpha = (int *)CALLOC((size_t)Mf,sizeof(int)); /* dominant terms */
for (i=0;i<Mf;i++) gamma[i] = 1; /* no terms dealt with initially */
/* Other storage... */
S = (double *) CALLOC((size_t) Q * Q,sizeof(double)); /* Transformed S (total) */
Sb = (double *) CALLOC((size_t) Q * Q,sizeof(double)); /* summation storage */
pivot = (int *)CALLOC((size_t) Q,sizeof(int)); /* pivot storage */
tau = (double *) CALLOC((size_t) Q,sizeof(double)); /* working storage */
work = (double *)CALLOC((size_t)(4 * Q),sizeof(double));
Sg = (double *) CALLOC((size_t) Q * Q,sizeof(double)); /* summation storage */
B = (double *) CALLOC((size_t) Q * max_col,sizeof(double)); /* Intermediate storage */
R = (double *) CALLOC((size_t) Q * Q,sizeof(double)); /* storage for unpivoted QR factor */
/* Start the main orthogonal transform loop */
iter =0;
while(1) {
iter ++;
/* Find the Frobenius norms of the Si in set gamma */
max_frob=0.0;
for (p=Si,i=0;i<Mf;i++,p += *q * Q)
if (gamma[i]) { /* don't bother if already dealt with */
frob[i] = frobenius_norm(p,q,&Q);
if (frob[i] *spf[i] >max_frob) max_frob=frob[i] * spf[i];
}
/* Find sets alpha and gamma' */
for (i=0;i<Mf;i++) {
if (gamma[i]) { /* term is still to be dealt with */
if (frob[i] * spf[i] > max_frob * *d_tol) {
alpha[i] = 1;gamma1[i] = 0; /* deal with it now */
} else {
alpha[i] = 0;gamma1[i] = 1; /* put it off */
}
} else { /* wasn't in gamma, so not in alpha or gamma1 */
alpha[i] = gamma1[i] = 0;
}
}
/* Form the scaled sum of the Si in alpha and get its rank by pivoted QR
and condition estimation...
*/
for (p=Sb,p1=p + *q * Q;p<p1;p++) *p=0.0; /* clear Sb */
for (p=Si,i=0;i<Mf;i++,p += *q * Q) if (alpha[i]) {
x = frob[i];
for (p1=p,p2=Sb,p3=p + *q * Q;p1<p3;p1++,p2++) *p2 += *p1 / x;
}
for (i=0;i<*q;i++) pivot[i]=0;
mgcv_qr(Sb, &Q, q ,pivot,tau); /* obtain pivoted QR decomposition of Sb */
/* Now obtain the rank, r, of Sb (see Golub and van Loan, 1996, p.129 & p.260)... */
r = Q;
R_cond(Sb,&Q,&r,work,&Rcond);
while (*r_tol * Rcond > 1) { r--;R_cond(Sb,&Q,&r,work,&Rcond);}
Qr = Q-r;
/* ... r is the rank of Sb, or any other positively weighted sum over alpha */
/* printf("\n iter = %d, rank = %d, Q = %d",iter,r,Q);
printf("\n gamma = ");for (i=0;i<Mf;i++) printf(" %d",gamma[i]);
printf("\n alpha = ");for (i=0;i<Mf;i++) printf(" %d",alpha[i]);
printf("\n gamma1 = ");for (i=0;i<Mf;i++) printf(" %d",gamma1[i]);*/
/* If Q==r then terminate (form S first if it's the first iteration) */
if (Q==r) {
if (iter==1 ) { /* form S */
for (p=Si,i=0;i<Mf;i++,p += Q*Q) {
x = spf[i];
for (p1=p,p2=S,p3=p+Q*Q;p1<p3;p1++,p2++) *p2 += *p1 * x;
}
break;
} else break; /* just use current S */
} /* end if (Q==r) */
/* Form the dominant term and QR-decompose it */
for (p=Sb,p1=p + *q * Q;p<p1;p++) *p = 0.0; /* clear Sb */
for (p=Si,i=0;i<Mf;i++,p += *q * Q) if (alpha[i]) { /* summing S[[i]]*sp[i] over i in alpha */
x = spf[i];
for (p1=p,p2=Sb,p3=p+ *q * Q;p1<p3;p1++,p2++) *p2 += *p1 * x;
}
for (i=0;i<*q;i++) pivot[i]=0;
mgcv_qr(Sb, &Q, q ,pivot,tau); /* obtain pivoted QR decomposition of Sb */
/* unpivot R, which means that no further pivoting is needed */
for (p=R,p1=R + *q * r;p<p1;p++) *p=0.0; /* clear R */
for (i=0;i<r;i++) for (j=i;j<*q;j++) R[i + pivot[j] * r] = Sb[i + j * Q];
/* DEBUG ONLY... */
/* printf("\npivot = ");for (j=0;j<*q;j++) printf("%d ",pivot[j]);
printf("Current R...\n");
for (i=0;i<r;i++) { for (j=0;j<*q;j++) printf("%7.2g ",Sb[i + Q *j]); printf("\n");} */
/* Form the sum over the elements in gamma1, Sg */
for (p=Sg,p1=p + *q * Q;p<p1;p++) *p=0.0; /* clear Sg */
for (p=Si,i=0;i<Mf;i++,p += *q * Q) if (gamma1[i]) { /* summing S[[i]]*sp[i] over i in gamma1 */
x = spf[i];
for (p1=p,p2=Sg,p3=p+ *q * Q;p1<p3;p1++,p2++) *p2 += *p1 * x;
}
/* Form S' the orthogonal transform of S */
/* Form Q'Sg... */
left=1;tp=1;
mgcv_qrqy(Sg,Sb,tau,&Q,q,&Q,&left,&tp);
/* copy transformed Sg into remainder of transformed S */
for (i=0;i<Q;i++) for (j=0;j<*q;j++) S[i+K + j * *q] = Sg[i + j * Q];
/* and add R in the appropriate place ... */
for (i=0;i<r;i++) for (j=0;j<*q;j++) S[i+K + j * *q] += R[i + j * r];
/* transform remaining S_i in gamma1 */
for (p1=p=Si,i=0;i<Mf;i++,p += *q * Q,p1 += *q *Qr) if (gamma1[i]) {
left=1;tp=1;
mgcv_qrqy(p,Sb,tau,&Q,q,&Q,&left,&tp); /* Q'Si */
p2=p+r;p3=p1;
for (j=0;j<*q;j++,p2+=r) for (k=0;k<Qr;k++,p3++,p2++) *p3 = *p2; /* copy to correct place */
}
/* Transform the square roots of Si */
if (*deriv) { /* transformed rS1 only needed for derivatives */
/* copy last Q rows of rS1 into rS2 */
for (i=0;i<Q;i++) for (j=0;j<tot_col;j++) rS2[i+Q*j] = rS1[K + i + *q * j];
/* pre-multiply rS2 by Q */
left=1;tp=1;
mgcv_qrqy(rS2,Sb,tau,&Q,&tot_col,&Q,&left,&tp); /* Q'rS2 */
/* copy rS2 into last Q rows of rS1 */
for (i=0;i<Q;i++) for (j=0;j<tot_col;j++) rS1[K + i + *q * j] = rS2[i+Q*j];
/* zero the last Qr rows of the rS1 in alpha */
for (p=rS1,k=0;k<Mf;p +=rSncol[k] * *q, k++) if (alpha[k]) {
for (i=K+r;i<*q;i++) for (j=0;j<rSncol[k];j++) p[i + j * *q] = 0.0;
}
}
/* DEBUG ONLY... */
/* printf("Current S...\n");
for (i=0;i<*q;i++) { for (j=0;j<*q;j++) printf("%7.2g ",S[i + *q *j]); printf("\n");}*/
/* Update K, Q and gamma */
K = K + r; Q = Qr;
for (i=0;i<Mf;i++) gamma[i] = gamma1[i];
} /* end of Orthogonal Transform Loop */
/* transpose S */
for (i=0;i<*q;i++) for (j=0;j<*q;j++) R[i + *q * j] = S[j + *q * i];
/* DEBUG ONLY... */
/* printf("Final S...\n");
for (i=0;i<*q;i++) { for (j=0;j<*q;j++) printf("%7.2g ",S[i + *q *j]); printf("\n");}*/
/* Now get the determinant and inverse of the transformed S (stored in B) */
*det = qr_ldet_inv(R,q,B,deriv); /* R=S' here */
/* finally, the derivatives, based on transformed S inverse and transformed square roots */
if (*deriv) { /* get the first derivatives */
/* first accumulate S^{-T} sqrtS into Si */
bt=0;ct=0;mgcv_mmult(Si,B,sqrtS,&bt,&ct,q,&tot_col,q);
/* Now get the required derivatives */
for (p=Si,p1=rS1,i=0;i<*M;p += *q *rSncol[i],p1+= *q *rSncol[i],i++) {
for (x=0.0,p2=p1,p3=p,p4=p1+ *q*rSncol[i];p2<p4;p2++,p3++) x += *p2 * *p3;
det1[i] = x*sp[i]; /* tr(S^{-1}S_i) */
}
}
if (*deriv==2) { /* get second derivatives, as well */
for (p=Si,p1=rS2,p2 = p1 + *q * tot_col;p1<p2;p1++,p++) *p1 = *p; /* copy S^{-1} sqrtS into rS2 */
/* loop through creating S^{-1} S_i and storing in Si...*/
for (p1=Si,p=rS2,p2=rS1,i=0;i<*M;p2+= *q * rSncol[i], p += *q *rSncol[i],i++,p1 += *q * *q) {
bt=0;ct=1;mgcv_mmult(p1,p,p2,&bt,&ct,q,q,rSncol+i);
}
/* DEBUG ONLY...
for (i=0;i<*M;i++) { for (x=0.0,j=0;j<*q;j++) x += Si[i* *q * *q + j + j* *q];det1[i]=x*sp[i];}*/
for (i=0;i<*M;i++) for (j=i;j<*M;j++)
det2[i + *M * j] = det2[j + *M * i] = -sp[i]*sp[j]*trAB(Si + *q * *q *i,Si + *q * *q *j,q,q);
for (i=0;i<*M;i++) det2[i + *M * i] += det1[i];
}
FREE(R);
FREE(work);
FREE(frob);
FREE(gamma);
FREE(gamma1);
FREE(alpha);
FREE(S);
FREE(Sb);
FREE(Sg);
if (*deriv) { FREE(rS1);FREE(rS2);}
if (*fixed_penalty) {FREE(spf);}
FREE(Si);
FREE(B);
FREE(pivot);FREE(tau);
} /* end of get_detS2 */
void get_stableS(double *S,double *Qf,double *sp,double *sqrtS, int *rSncol, int *q,int *M, int * deriv,
double *det, double *det1, double *det2, double *d_tol,
double *r_tol,int *fixed_penalty)
/* Routine to similarity transform S = \sum_i \lambda_i S_i, to produce an S which facilitates
stable computation.
THEORETICAL NOTE: If the square-root of S is found by choleski on the diagonally pre-conditioned
S, then a well behaved root is obtained, with no `large-zero' leakage beyond
the range space of each component of S. This should be compared with `mroot'
(just pivoted Choleski, where some leakage does occur -- into the penalty null
space, but within the non-zero block of the penalty).
Also evaluates log|S| and its derivatives wrt log(sp), in a stable manner, using
a similarity transform strategy.
Inputs are:
`sp' the array of smoothing parameters.
`sqrtS' the `M' square root penalty matrices. The ith is `q' by `rSncol[i]'. They are
packed one after the other.
`deriv' is the order of derivatives required. 0,1 or 2.
`d_tol' is the tolerance to use for grouping dominant terms.
`r_tol' (<< d_tol) is the tolerance used for rank determination.
`fixed_penalty' non-zero indicates that there is a fixed component of
total penalty matrix S, the square root of which is in the final
q * rSncol[M+1] elements of sqrtS.
Outputs are:
`det' the log determinant.
`det1' M-array of derivatives of log det wrt log sp.
`det2' M by M Hessian of log det wrt log sp.
`S' - the similarity transformed total penalty matrix
`Qf' - the orthogonal factor of the similarity transform. If S0 is the
original total penalty then S = Qf' S0 Qf
sqrtS - the square roots of the components of S, transformed as S itself.
*/
{ double *rS, *Un, *U, *Si,*Sb,*B,*C,*Sg,*p,*p1,*p2,*p3,*frob,*ev,max_frob,x,*spf;
int iter,i,j,k,bt,ct,rSoff,K,Q,Qr,*gamma,*gamma1,*alpha,TRUE=1,FALSE=0,r,max_col,Mf,n_gamma1;
if (*fixed_penalty) {
Mf = *M + 1; /* total number of components, including fixed one */
spf = (double *)CALLOC((size_t)Mf,sizeof(double));
for (i=0;i<*M;i++) spf[i]=sp[i];
spf[*M]=1.0; /* includes sp for fixed term */
}
else {spf=sp;Mf = *M;} /* total number of components, including fixed one */
/* Create a working copy of sqrtS, which can be modified */
rS = sqrtS; /* this routine modifies sqrtS */
/* Explicitly form the Si (stored in a single block), so S_i is stored
in Si + i * q * q (starting i from 0). As iteration progresses,
blocks are shrunk -- always Q by Q */
p = Si = (double *)CALLOC((size_t)*q * *q * Mf,sizeof(double));
max_col = *q; /* need enough storage just in case square roots are over-sized */
for (rSoff=i=0;i<Mf;p+= *q * *q,rSoff+=rSncol[i],i++) {
bt=0;ct=1;mgcv_mmult(p,sqrtS+rSoff * *q,sqrtS+rSoff * *q,&bt,&ct,q,q,rSncol+i);
if (rSncol[i]>max_col) max_col=rSncol[i];
}
/* Initialize the sub-dominant set gamma and the counters */
K = 0; /* counter for coefs already deal with */
Q = *q; /* How many coefs left to deal with */
frob = (double *)CALLOC((size_t)Mf,sizeof(double));
gamma = (int *)CALLOC((size_t)Mf,sizeof(int)); /* terms remaining to deal with */
gamma1 = (int *)CALLOC((size_t)Mf,sizeof(int)); /* new gamma */
alpha = (int *)CALLOC((size_t)Mf,sizeof(int)); /* dominant terms */
for (i=0;i<Mf;i++) gamma[i] = 1; /* no terms dealt with initially */
/* Other storage... */
U=Sb = (double *) CALLOC((size_t) Q * Q,sizeof(double)); /* summation storage */
Sg = (double *) CALLOC((size_t) Q * Q,sizeof(double)); /* summation storage */
ev = (double *) CALLOC((size_t) Q,sizeof(double)); /* eigenvalue storage */
B = (double *) CALLOC((size_t) Q * max_col,sizeof(double)); /* Intermediate storage */
C = (double *) CALLOC((size_t) Q * max_col,sizeof(double)); /* Intermediate storage */
/* Start the main similarity transform loop */
iter =0;
while(1) {
iter ++;
/* Find the Frobenius norms of the Si in set gamma */
max_frob=0.0;
for (p=Si,i=0;i<Mf;i++,p += Q * Q)
if (gamma[i]) { /* don't bother if already dealt with */
frob[i] = frobenius_norm(p,&Q,&Q);
if (frob[i] *spf[i] >max_frob) max_frob=frob[i] * spf[i];
}
/* Find sets alpha and gamma' */
n_gamma1=0;
for (i=0;i<Mf;i++) {
if (gamma[i]) { /* term is still to be dealt with */
if (frob[i] * spf[i] > max_frob * *d_tol) {
alpha[i] = 1;gamma1[i] = 0; /* deal with it now */
} else {
alpha[i] = 0;gamma1[i] = 1; n_gamma1++; /* put it off */
}
} else { /* wasn't in gamma, so not in alpha or gamma1 */
alpha[i] = gamma1[i] = 0;
}
}
/* Form the scaled sum of the Si in alpha and eigen-decompose it to get its rank */
if (n_gamma1) { /* stuff left in gamma1, so have to work out rank of contents of alpha */
for (p=Sb,p1=p+Q*Q;p<p1;p++) *p=0.0; /* clear Sb */
for (p=Si,i=0;i<Mf;i++,p += Q*Q) if (alpha[i]) {
x = frob[i];
for (p1=p,p2=Sb,p3=p+Q*Q;p1<p3;p1++,p2++) *p2 += *p1 / x;
}
mgcv_symeig(Sb,ev,&Q,&FALSE,&FALSE,&FALSE); /* get eigenvalues (ascending) of scaled sum over alpha */
r=1;
while(r<Q&&(ev[Q-r-1]>ev[Q-1] * *r_tol)) r++;
} else { /* nothing left in gamma1, so... */
r=Q;
}
/* ... r is the rank of Sb, or any other positively weighted sum over alpha */
/* If Q==r then terminate (form S first if it's the first iteration) */
if (Q==r) {
if (iter==1 ) { /* form S and Qf*/
for (p=Si,i=0;i<Mf;i++,p += Q*Q) {
x = spf[i];
for (p1=p,p2=S,p3=p+Q*Q;p1<p3;p1++,p2++) *p2 += *p1 * x;
}
/* Qf is identity */
for (p=Qf,p1=p+Q*Q;p<p1;p++) *p=0.0;
for (p=Qf,i=0;i<Q;i++,p+=Q+1) *p=1.0;
break;
} else break; /* just use current S */
} /* end if (Q==r) */
/* Form the dominant term and eigen-decompose it */
for (p=Sb,p1=p+Q*Q;p<p1;p++) *p = 0.0; /* clear Sb */
for (p=Si,i=0;i<Mf;i++,p += Q*Q) if (alpha[i]) { /* summing S[[i]]*sp[i] over i in alpha */
x = spf[i];
for (p1=p,p2=Sb,p3=p+Q*Q;p1<p3;p1++,p2++) *p2 += *p1 * x;
}
mgcv_symeig(Sb,ev,&Q,&FALSE,&TRUE,&TRUE); /* get eigen decomposition of dominant term (ev descending) */
/* .... U points to Sb, which now contains eigenvectors */
if (iter==1) for (p=U,p1=Qf,p2 = p+Q*Q;p<p2;p++,p1++) *p1 = *p;
else {
bt=0;ct=0;mgcv_mmult(B,Qf+K * *q,U,&bt,&ct,q,&Q,&Q);
for (p=Qf + K * *q,p1=Qf + *q * *q,p2=B;p<p1;p++,p2++) *p = *p2;
}
/* Form the sum over the elements in gamma1, Sg */
for (p=Sg,p1=p+Q*Q;p<p1;p++) *p=0.0; /* clear Sg */
for (p=Si,i=0;i<Mf;i++,p += Q*Q) if (gamma1[i]) { /* summing S[[i]]*sp[i] over i in gamma1 */
x = spf[i];
for (p1=p,p2=Sg,p3=p+Q*Q;p1<p3;p1++,p2++) *p2 += *p1 * x;
}
/* Form S' the similarity transformed S */
if (K>0) { /* deal with upper right component B */
/* first copy out K by Q matrix B */
for (j=0;j<Q;j++) for (i=0;i<K;i++) C[i + K * j] = S[i + *q * (j+K)];
/* Now form BU (store in B)*/
bt=0;ct=0;mgcv_mmult(B,C,U,&bt,&ct,&K,&Q,&Q);
/* Replace B into S */
for (j=0;j<Q;j++) for (i=0;i<K;i++) S[i + *q * (j+K)]= S[j + K + *q * i] = B[i + K * j];
}
/* Now deal with the lower right component, C */
/* U'SgU */
bt=0;ct=0;mgcv_mmult(B,Sg,U,&bt,&ct,&Q,&Q,&Q); /* SgU is in B */
bt=1;ct=0;mgcv_mmult(C,U,B,&bt,&ct,&Q,&Q,&Q); /* U'SgU is in C */
for (i=0;i<r;i++) C[i+i * Q] += ev[i]; /* Adding in the non-zero eigenvalues */
/* Now copy U'SgU + D back into right part of S' */
for (j=0;j<Q;j++) for (i=0;i<Q;i++) S[i + K + *q * (j+K)] = C[i + Q * j];
/* Transform the square roots of Si in alpha and gamma1 (Can leave fixed term alone - not needed)*/
for (p=rS,k=0;k<*M;p += rSncol[k] * *q,k++) if (alpha[k]) { /* p points to the square root of S_i */
/* extract the part of rS_i to be modified */
for (i=0;i<Q;i++) for (j=0;j<rSncol[k];j++) C[i + Q * j] = p[i + K + *q * j];
bt=1;ct=0;mgcv_mmult(B,U,C,&bt,&ct,&r,rSncol+k,&Q);
for (i=0;i<r;i++) for (j=0;j<rSncol[k];j++) p[i + K + *q * j] = B[i + r * j];
for (i=K+r;i<K+Q;i++) for (j=0;j<rSncol[k];j++) p[i + *q * j] = 0.0;
} else if (gamma1[k]) {
for (i=0;i<Q;i++) for (j=0;j<rSncol[k];j++) C[i + Q * j] = p[i + K + *q * j];
bt=1;ct=0;mgcv_mmult(B,U,C,&bt,&ct,&Q,rSncol+k,&Q);
for (i=0;i<Q;i++) for (j=0;j<rSncol[k];j++) p[i + K + *q * j] = B[i + Q * j];
}
/* Transform the Si in gamma' */
Qr = Q - r;Un = U + r * Q;
for (p1=p=Si,i=0;i<Mf;i++,p += Q*Q,p1 +=Qr*Qr) if (gamma1[i]) { /* p points to old Si, and p1 to new */
bt=1;ct=0;mgcv_mmult(B,Un,p,&bt,&ct,&Qr,&Q,&Q);
bt=0;ct=0;mgcv_mmult(p1,B,Un,&bt,&ct,&Qr,&Qr,&Q);
}
/* Update K, Q and gamma */
K = K + r; Q = Qr;
for (i=0;i<Mf;i++) gamma[i] = gamma1[i];
} /* end of Similarity Transfrom Loop */
/* Now get the determinant and inverse of the transformed S (stored in C, which gets overwritten)
inverse of S returned in B */
for (p=S,p1=S + *q * *q,p2=C;p<p1;p++,p2++) *p2 = *p; /* copy S to C */
*det = qr_ldet_inv(C,q,B,deriv);
/* finally, the dervivatives, based on transformed S inverse and transformed square roots */
if (*deriv) { /* get the first derivatives */
for (p=rS,i=0;i<*M;p += *q *rSncol[i],i++) det1[i] = trBtAB(B,p,q,rSncol+i)*sp[i]; /* tr(S^{-1}S_i) */
}
if (*deriv==2) { /* get second derivatives, as well */
for (p1=Si,p=rS,i=0;i<*M;p += *q *rSncol[i],i++,p1 += *q * *q) { /* loop through creating S^{-1} S_i and storing in Si*/
bt=0;ct=0;mgcv_mmult(C,B,p,&bt,&ct,q,rSncol+i,q);
bt=0;ct=1;mgcv_mmult(p1,C,p,&bt,&ct,q,q,rSncol+i);
}
for (i=0;i<*M;i++) for (j=i;j<*M;j++)
det2[i + *M * j] = det2[j + *M * i] = -sp[i]*sp[j]*trAB(Si + *q * *q *i,Si + *q * *q *j,q,q);
for (i=0;i<*M;i++) det2[i + *M * i] += det1[i];
}
FREE(frob);
FREE(gamma);
FREE(gamma1);
FREE(alpha);
FREE(Sb);
FREE(Sg);
if (*fixed_penalty) {FREE(spf);}
FREE(Si);
FREE(ev);
FREE(B);
FREE(C);
}/* end get_stableS */
void get_ddetXWXpS(double *det1,double *det2,double *P,double *K,double *sp,
double *rS,int *rSncol,double *Tk,double *Tkm,int *n,int *q,int *r,int *M,int *M0,
int *deriv,int nthreads)
/* obtains derivatives of |X'WX + S| wrt the log smoothing parameters, as required for REML.
The determinant itself has to be obtained during intial decompositions: see gdi().
* P is q by r
* K is n by r
* sp is of length M, and there are M penalties, but derivatives are required w.r.t. M0 + M
parameters [theta,sp] and Tk, Tkm contain derivatives w.r.t. all of these. The parameters
theta are parameters of the likelihood, but are not involved in penalties.
* this routine assumes that sp contains smoothing parameters, rather than log smoothing parameters.
* Note that P and K are as in Wood (2008) JRSSB 70, 495-518.
* uses nthreads via openMP - assumes nthreads already set and nthreads already reset to 1
if openMP not present
*/
{ double *diagKKt,xx,*KtTK,*PtrSm,*PtSP,*trPtSP,*work,*pdKK,*p1,*pTkm;
int m,k,bt,ct,j,one=1,km,mk,*rSoff,deriv2,max_col,Mtot;
int tid;
if (nthreads<1) nthreads = 1;
Mtot = *M0 + *M; /* total length of sp */
if (*deriv==2) deriv2=1; else deriv2=0;
/* obtain diag(KK') */
if (*deriv) {
diagKKt = (double *)CALLOC((size_t)*n,sizeof(double));
xx = diagABt(diagKKt,K,K,n,r);
} else { /* nothing to do */
return;
}
/* set up work space */
work = (double *)CALLOC((size_t)*n * nthreads,sizeof(double));
tid=0; /* thread identifier defaults to zero if openMP not available */
/* now loop through the smoothing parameters to create K'TkK */
if (deriv2) {
KtTK = (double *)CALLOC((size_t)(*r * *r * Mtot),sizeof(double));
#ifdef OPENMP_ON
#pragma omp parallel private(k,j,tid) num_threads(nthreads)
#endif
{ /* open parallel section */
#ifdef OPENMP_ON
#pragma omp for
#endif
for (k=0;k < Mtot;k++) {
#ifdef OPENMP_ON
tid = omp_get_thread_num(); /* thread running this bit */
#endif
j = k * *r * *r;
getXtWX(KtTK+ j,K,Tk + k * *n,n,r,work + *n * tid);
}
} /* end of parallel section */
} else { KtTK=(double *)NULL;} /* keep compiler happy */
/* start first derivative */
bt=1;ct=0;mgcv_mmult(det1,Tk,diagKKt,&bt,&ct,&Mtot,&one,n); /* tr(TkKK') */
/* Finish first derivative and create create P'SmP if second derivs needed */
max_col = *q;
for (j=0;j<*M;j++) if (max_col<rSncol[j]) max_col=rSncol[j]; /* under ML can have q < max(rSncol) */
PtrSm = (double *)CALLOC((size_t)(*r * max_col * nthreads),sizeof(double)); /* storage for P' rSm */
trPtSP = (double *)CALLOC((size_t) *M,sizeof(double));
if (deriv2) {
PtSP = (double *)CALLOC((size_t)(*M * *r * *r ),sizeof(double));
} else { PtSP = (double *) NULL;}
rSoff = (int *)CALLOC((size_t)*M,sizeof(int));
if (*M>0) {
rSoff[0] = 0;for (m=0;m < *M-1;m++) rSoff[m+1] = rSoff[m] + rSncol[m];
}
tid = 0;
#ifdef OPENMP_ON
#pragma omp parallel private(m,bt,ct,tid) num_threads(nthreads)
#endif
{ /* parallel section start */
#ifdef OPENMP_ON
#pragma omp for
#endif
for (m=0;m < *M;m++) { /* loop through penalty matrices */
#ifdef OPENMP_ON
tid = omp_get_thread_num(); /* thread running this bit */
#endif
bt=1;ct=0;mgcv_mmult(PtrSm + tid * *r * max_col,P,rS+rSoff[m] * *q,&bt,&ct,r,rSncol+m,q);
/*rSoff += rSncol[m];*/
trPtSP[m] = sp[m] * diagABt(work + *n * tid,PtrSm + tid * *r * max_col,
PtrSm + tid * *r * max_col,r,rSncol+m); /* sp[m]*tr(P'S_mP) */
det1[m + *M0] += trPtSP[m]; /* completed first derivative */
if (deriv2) { /* get P'S_mP */
bt=0;ct=1;mgcv_mmult(PtSP+ m * *r * *r,PtrSm + tid * *r * max_col,
PtrSm+ tid * *r * max_col ,&bt,&ct,r,r,rSncol+m);
}
}
} /* end of parallel section */
FREE(rSoff);
/* Now accumulate the second derivatives */
// #ifdef OPENMP_ON
//#pragma omp parallel private(m,k,km,mk,xx,tid,pdKK,p1,pTkm) num_threads(nthreads)
//#endif
if (deriv2)
{ /* start of parallel section */
//if (deriv2)
#ifdef OPENMP_ON
#pragma omp parallel for private(m,k,km,mk,xx,tid,pdKK,p1,pTkm) num_threads(nthreads)
#endif
for (m=0;m < Mtot;m++) {
#ifdef OPENMP_ON
tid = omp_get_thread_num(); /* thread running this bit */
#endif
if (m==0) pTkm = Tkm; else pTkm = Tkm + (m * Mtot - (m*(m-1))/2) * *n;
for (k=m;k < Mtot;k++) {
km=k * Mtot + m;mk=m * Mtot + k;
/* tr(Tkm KK') */
/*for (xx=0.0,pdKK=diagKKt,p1=pdKK + *n;pdKK<p1;pdKK++,Tkm++) xx += *Tkm * *pdKK;*/
for (xx=0.0,pdKK=diagKKt,p1=pdKK + *n;pdKK<p1;pdKK++,pTkm++) xx += *pTkm * *pdKK;
det2[km] = xx;
/* - tr(KTkKK'TmK) */
det2[km] -= diagABt(work + *n * tid,KtTK + k * *r * *r,KtTK+ m * *r * *r,r,r);
/* sp[k]*tr(P'S_kP) */
if (k >= *M0 && k==m) det2[km] += trPtSP[m - *M0];
/* -sp[m]*tr(K'T_kKP'S_mP) */
if (m >= *M0) det2[km] -= sp[m - *M0]*diagABt(work + *n * tid,KtTK + k * *r * *r,PtSP + (m - *M0) * *r * *r,r,r);
/* -sp[k]*tr(K'T_mKP'S_kP) */
if (k >= *M0) det2[km] -= sp[k - *M0]*diagABt(work + *n * tid,KtTK + m * *r * *r,PtSP + (k - *M0) * *r * *r,r,r);
/* -sp[m]*sp[k]*tr(P'S_kPP'S_mP) */
if (k >= *M0 && m >= *M0) det2[km] -= sp[m - *M0]*sp[k - *M0]*
diagABt(work + *n * tid,PtSP + (k - *M0) * *r * *r,PtSP + (m - *M0) * *r * *r,r,r);
det2[mk] = det2[km];
}
}
} /* end of parallel section */
/* free up some memory */
if (deriv2) {FREE(PtSP);FREE(KtTK);}
FREE(diagKKt);FREE(work);
FREE(PtrSm);FREE(trPtSP);
} /* end get_ddetXWXpS */
void get_trA2(double *trA,double *trA1,double *trA2,double *P,double *K,double *sp,
double *rS,int *rSncol,double *Tk,double *Tkm,double *w,int *n,int *q,
int *r,int *M,int *deriv,int *nt)
/* obtains trA and its first two derivatives wrt the log smoothing parameters
* P is q by r
* K is n by r
* U1 is q by r
* this routine assumes that sp contains smoothing parameters, rather than log smoothing parameters.
* If deriv is 0 then only tr(A) is obtained here.
* This version uses only K and P, and is for the case where expressions involve weights which
are reciprocal variances, not the squares of weights which are reciprocal standard deviations.
* Note that tr(A) = tr(KK') and it is tempting to view diag(K'K) as giving the edfs
of the parameters, but this seems to be wrong. It gives the edfs for R \beta, where
R is (pseudo) inverse of P.
* uses nt threads via openMP. Assumes thread number already set on entry and nt already reset to
1 if no openMP support.
*/
{ double *diagKKt,*diagKKtKKt,xx,*KtTK,*KtTKKtK,*KKtK,*KtK,*work,*pTk,*pTm,*pdKKt,*pdKKtKKt,*p0,*p1,*p2,*p3,*pd,
*PtrSm,*PtSP,*KPtrSm,*diagKPtSPKt,*diagKPtSPKtKKt,*PtSPKtK, *KtKPtrSm, *KKtKPtrSm,*Ip,*IpK/*,lowK,hiK*/;
int i,m,k,bt,ct,j,one=1,km,mk,*rSoff,deriv2,neg_w=0,tid=0;
#ifdef OMP_REPORT
Rprintf("get_trA2 (d=%d)...",*deriv);
#endif
if (*deriv==2) deriv2=1; else deriv2=0;
/* Get the sign array for negative w_i */
Ip = (double *)CALLOC((size_t)*n,sizeof(double));
for (p0=w,p1=p0+ *n,p2=Ip;p0<p1;p0++,p2++) if (*p0 < 0) {*p2 = -1.0;neg_w=1;} else *p2 = 1.0;
/* obtain tr(A) and diag(A) = diag(KK'Ip) */
diagKKt = (double *)CALLOC((size_t)*n,sizeof(double));