Debian Codegraph @

cindex/src/cindex.cpp

raw
1 #include "include/plink2_base.h"
2 #include <algorithm>
3
4 #include <Rcpp.h>
5 using namespace Rcpp;
6
7 typedef struct CIndexRecStruct {
8 double key; // yhat on first sort, y on second sort
9 uint32_t status; // original pos on first sort
10 uint32_t yhat_int;
11 bool operator<(const struct CIndexRecStruct& rhs) const {
12 return (key < rhs.key);
13 }
14 } CIndexRec;
15
16 uint32_t PopcountLookup(const uintptr_t* new_yhat_present, const uint16_t* new_yhat_64b_popcounts, const uint16_t* new_yhat_2kib_popcounts, const uint32_t* new_yhat_64kib_popcounts, uint32_t widx);
17
18 double CIndexTieheavyMain(const CIndexRec* recs, uintptr_t size, unsigned char* wkspace, uintptr_t* new_yhat_present, uint16_t* new_yhat_64b_popcounts, uint16_t* new_yhat_2kib_popcounts, uint32_t* new_yhat_64kib_popcounts);
19
20 double CIndexWeighted(NumericVector yhat, NumericVector y, SEXP status, const double* weightsd, uintptr_t orig_size);
21
22 // [[Rcpp::export]]
23 double CIndex(NumericVector yhat, NumericVector y, SEXP status, Nullable<NumericVector> w = R_NilValue) {
24 if ((TYPEOF(status) != INTSXP) && (TYPEOF(status) != REALSXP)) {
25 // could support LGLSXP too
26 stop("Unsupported status type");
27 }
28 const uintptr_t size = yhat.size();
29 if (size == 0) {
30 stop("yhat cannot be empty");
31 }
32 if (size != static_cast<uintptr_t>(y.size())) {
33 stop("yhat and y must have the same length");
34 }
35 if (w.isNotNull()) {
36 NumericVector weights = w.get();
37 if (size != static_cast<uintptr_t>(weights.size())) {
38 stop("w must have the same length as yhat and y");
39 }
40 // May as well fall through if all weights are equal.
41 const double* weightsd = &(weights[0]);
42 const double first_wt = weightsd[0];
43 for (uintptr_t ulii = 1; ulii != size; ++ulii) {
44 if (first_wt != weightsd[ulii]) {
45 return CIndexWeighted(yhat, y, status, weightsd, size);
46 }
47 }
48 }
49
50 // We define unweighted C-index as:
51 // sum_{all j where status[j]=1} [#(m: y[m]>y[j], yhat[m]<yhat[j]) +
52 // 0.5 * #(m: y[m]>y[j], yhat[m]==yhat[j])]
53 // ------------------------------------------------------------------------
54 // sum_{all j where status[j]=1} #(m: y[m]>y[j])
55 //
56 // The computation is organized as follows:
57 // 1. Replace yhat with 0-based ranks ('yhat_int'); note that this has no
58 // effect on the expression above. Ties round down.
59 // 2. Sort records in order of nondecreasing y.
60 // 3. Iterate through records, starting from largest y. Incrementally update
61 // a data structure tracking which yhat_int values have been seen so far,
62 // and in case of ties, their multiplicity. This data structure supports
63 // fast insertion and number-of-smaller{-or-equal}-elements queries, which
64 // covers the operations we need to compute the numerator. Formally, the
65 // total query time is still O(N^2) if status==1 isn't sparse, but the
66 // constant multiplier is so small that the std::sort calls practically
67 // always dominate for R's N<2^31 domain. (Not literally true for current
68 // implementation, but it's trivial to branch on N and use another
69 // popcount index-levels for very large N once any application cares.)
70 // More precisely, the new_yhat data structure consists of a bitarray, and
71 // three index-arrays containing partial popcounts for intervals of 2^9,
72 // 2^14, and 2^19 bits.
73
74 // Intermediate data structures (all cacheline-aligned except maybe recs,
75 // which is vector-aligned):
76 // - recs: N CIndexRec
77 // - new_yhat_present: N bits
78 // - new_yhat_64b_popcounts: DivUp(N, 512) uint16s
79 // - new_yhat_2kib_popcounts: DivUp(N, 512*32) uint16s
80 // - new_yhat_64kib_popcounts: DivUp(N, 512*32*32) uint16s
81 const uintptr_t recs_vec_ct = plink2::DivUp(sizeof(CIndexRec) * size, plink2::kBytesPerVec);
82 const uintptr_t new_yhat_present_cacheline_ct = plink2::DivUp(size, plink2::kBitsPerCacheline);
83 const uintptr_t new_yhat_present_vec_ct = new_yhat_present_cacheline_ct * plink2::kVecsPerCacheline;
84 const uintptr_t new_yhat_64b_popcounts_cacheline_ct = plink2::DivUp(new_yhat_present_cacheline_ct, plink2::kInt16PerCacheline);
85 const uintptr_t new_yhat_64b_popcounts_vec_ct = new_yhat_64b_popcounts_cacheline_ct * plink2::kVecsPerCacheline;
86 const uintptr_t new_yhat_2kib_popcounts_cacheline_ct = plink2::DivUp(new_yhat_64b_popcounts_cacheline_ct, plink2::kInt16PerCacheline);
87 const uintptr_t new_yhat_2kib_popcounts_vec_ct = new_yhat_2kib_popcounts_cacheline_ct * plink2::kVecsPerCacheline;
88 const uintptr_t new_yhat_64kib_popcounts_vec_ct = plink2::DivUp(new_yhat_2kib_popcounts_cacheline_ct, plink2::kInt32PerVec);
89 const uintptr_t vec_ct = recs_vec_ct + new_yhat_present_vec_ct + new_yhat_64b_popcounts_vec_ct + new_yhat_2kib_popcounts_vec_ct + new_yhat_64kib_popcounts_vec_ct;
90 unsigned char* wkspace;
91 if (plink2::cachealigned_malloc(vec_ct * plink2::kBytesPerVec, &wkspace)) {
92 stop("Out of memory");
93 }
94 memset(wkspace, 0, (vec_ct - recs_vec_ct) * plink2::kBytesPerVec);
95 unsigned char* wkspace_iter = wkspace;
96 // Put new_yhat arrays first to guarantee cacheline alignment, since it
97 // matters there.
98 uintptr_t* new_yhat_present = reinterpret_cast<uintptr_t*>(wkspace_iter);
99 wkspace_iter = &(wkspace_iter[new_yhat_present_vec_ct * plink2::kBytesPerVec]);
100 uint16_t* new_yhat_64b_popcounts = reinterpret_cast<uint16_t*>(wkspace_iter);
101 wkspace_iter = &(wkspace_iter[new_yhat_64b_popcounts_vec_ct * plink2::kBytesPerVec]);
102 uint16_t* new_yhat_2kib_popcounts = reinterpret_cast<uint16_t*>(wkspace_iter);
103 wkspace_iter = &(wkspace_iter[new_yhat_2kib_popcounts_vec_ct * plink2::kBytesPerVec]);
104 uint32_t* new_yhat_64kib_popcounts = reinterpret_cast<uint32_t*>(wkspace_iter);
105 wkspace_iter = &(wkspace_iter[new_yhat_64kib_popcounts_vec_ct * plink2::kBytesPerVec]);
106 CIndexRec* recs = reinterpret_cast<CIndexRec*>(wkspace_iter);
107
108 uint64_t yhat_int_sum = 0;
109 {
110 const double* yhatd = &(yhat[0]);
111 for (uintptr_t ulii = 0; ulii != size; ++ulii) {
112 recs[ulii].key = yhatd[ulii];
113 recs[ulii].status = ulii;
114 }
115 std::sort(recs, &(recs[size]));
116 recs[recs[0].status].yhat_int = 0;
117 double prev_yhat = recs[0].key;
118 uint32_t prev_idx = 0;
119 for (uintptr_t ulii = 1; ulii != size; ++ulii) {
120 const double cur_yhat = recs[ulii].key;
121 if (cur_yhat != prev_yhat) {
122 prev_idx = ulii;
123 prev_yhat = cur_yhat;
124 }
125 recs[recs[ulii].status].yhat_int = prev_idx;
126 yhat_int_sum += prev_idx;
127 }
128 }
129 const double* yd = &(y[0]);
130 if (TYPEOF(status) == INTSXP) {
131 IntegerVector status_iv = as<IntegerVector>(status);
132 if (size != static_cast<uintptr_t>(status_iv.size())) {
133 plink2::aligned_free(wkspace);
134 stop("y and status must have the same length");
135 }
136 const int32_t* status_ivi = &(status_iv[0]);
137 for (uintptr_t ulii = 0; ulii != size; ++ulii) {
138 recs[ulii].key = yd[ulii];
139 const uint32_t uii = status_ivi[ulii];
140 if (uii & (~1)) {
141 plink2::aligned_free(wkspace);
142 stop("all status values must be 0 or 1");
143 }
144 recs[ulii].status = uii;
145 }
146 } else {
147 NumericVector status_nv = as<NumericVector>(status);
148 if (size != static_cast<uintptr_t>(status_nv.size())) {
149 plink2::aligned_free(wkspace);
150 stop("y and status must have the same length");
151 }
152 const double* status_nvd = &(status_nv[0]);
153 for (uintptr_t ulii = 0; ulii != size; ++ulii) {
154 recs[ulii].key = yd[ulii];
155 const double dxx = status_nvd[ulii];
156 if (dxx == 0.0) {
157 recs[ulii].status = 0;
158 } else if (dxx == 1.0) {
159 recs[ulii].status = 1;
160 } else {
161 plink2::aligned_free(wkspace);
162 stop("all status values must be 0 or 1");
163 }
164 }
165 }
166 std::sort(recs, &(recs[size]));
167
168 // With no ties, yhat_int_sum would be (size * (size - 1)) / 2.
169 // k-way ties decrease the sum by (k * (k-1)) / 2, which is conveniently
170 // proportional to the burden imposed by the ties (sequential scanning for
171 // the next unset bit in new_yhat_present) on our usual algorithm.
172 // With high enough tie-burden (threshold proportional to n log n), we switch
173 // to a slightly different approach, which is usually slower but avoids
174 // sequential scans in case of ties.
175 const uint64_t tie_burden = (static_cast<uint64_t>(size) * (size - 1)) / 2 - yhat_int_sum;
176 if (tie_burden > 512 * static_cast<uint64_t>(size)) {
177 return CIndexTieheavyMain(recs, size, wkspace, new_yhat_present, new_yhat_64b_popcounts, new_yhat_2kib_popcounts, new_yhat_64kib_popcounts);
178 }
179
180 // Main loop.
181 double prev_key = recs[size - 1].key;
182 uint32_t recs_block_end = size;
183 uint32_t new_yhat_entry_ct = 0;
184 uint64_t numer_x2 = 0;
185 uint64_t denom = 0;
186 for (uint32_t recs_idx = size; recs_idx; ) {
187 --recs_idx;
188 const double cur_key = recs[recs_idx].key;
189 if (cur_key != prev_key) {
190 const uint32_t next_block_end = recs_idx + 1;
191 for (uint32_t uii = next_block_end; uii != recs_block_end; ++uii) {
192 const uint32_t yhat_int = recs[uii].yhat_int;
193 // This is essentially an inlined AdvTo0Bit() call.
194 uintptr_t widx = yhat_int / plink2::kBitsPerWord;
195 {
196 const uintptr_t remainder_bit = plink2::k1LU << (yhat_int % plink2::kBitsPerWord);
197 uintptr_t cur_word = new_yhat_present[widx];
198 if (!(remainder_bit & cur_word)) {
199 // common case
200 new_yhat_present[widx] = cur_word | remainder_bit;
201 } else {
202 // There's a tie, and we've already seen at least one previous
203 // instance.
204 // Find the rightmost clear bit in cur_word after remainder_bit, if
205 // there is one. We use the bitarray property that cur_word +
206 // <bit> sets the first 0-bit in cur_word at or past the added bit,
207 // may clear some other bits, and doesn't do anything else.
208 uintptr_t ulii = cur_word + remainder_bit;
209 if (ulii < remainder_bit) {
210 // Addition 'carry' needed.
211 do {
212 cur_word = new_yhat_present[++widx];
213 } while (cur_word == ~plink2::k0LU);
214 ulii = cur_word + 1;
215 }
216 const uintptr_t new_word = ulii | cur_word;
217 new_yhat_present[widx] = new_word;
218 }
219 }
220 new_yhat_64b_popcounts[widx / plink2::kWordsPerCacheline] += 1;
221 new_yhat_2kib_popcounts[widx / (plink2::kWordsPerCacheline * plink2::kInt16PerCacheline)] += 1;
222 new_yhat_64kib_popcounts[widx / (plink2::kWordsPerCacheline * plink2::kInt16PerCacheline * plink2::kInt16PerCacheline)] += 1;
223 }
224 recs_block_end = next_block_end;
225 new_yhat_entry_ct = size - recs_block_end;
226 prev_key = cur_key;
227 }
228 if (!recs[recs_idx].status) {
229 continue;
230 }
231 denom += new_yhat_entry_ct;
232 const uint32_t yhat_int = recs[recs_idx].yhat_int;
233 // numer_x2 += 2 * <# of set bits before yhat_int> + <# of ties>
234 uint32_t widx = yhat_int / plink2::kBitsPerWord;
235 uint32_t n_set_bits_before = PopcountLookup(new_yhat_present, new_yhat_64b_popcounts, new_yhat_2kib_popcounts, new_yhat_64kib_popcounts, widx);
236 uint32_t remainder = yhat_int % plink2::kBitsPerWord;
237 uintptr_t cur_word = new_yhat_present[widx];
238 uintptr_t remainder_bit = plink2::k1LU << remainder;
239 n_set_bits_before += plink2::PopcountWord(cur_word & (remainder_bit - 1));
240 numer_x2 += 2 * n_set_bits_before;
241
242 if (!(cur_word & remainder_bit)) {
243 // common case
244 continue;
245 }
246 // Similar to the insertion tie-handling code above.
247 numer_x2 -= remainder;
248 uintptr_t ulii = cur_word + remainder_bit;
249 if (ulii < remainder_bit) {
250 uint32_t widx2 = widx;
251 do {
252 cur_word = new_yhat_present[++widx2];
253 } while (cur_word == ~plink2::k0LU);
254 numer_x2 += (widx2 - widx) * plink2::kBitsPerWord;
255 ulii = cur_word + 1;
256 }
257 numer_x2 += plink2::ctzw(ulii & (~cur_word));
258 }
259 plink2::aligned_free(wkspace);
260 return plink2::u63tod(numer_x2) / plink2::u63tod(denom * 2);
261 }
262
263 uint32_t PopcountLookup(const uintptr_t* new_yhat_present, const uint16_t* new_yhat_64b_popcounts, const uint16_t* new_yhat_2kib_popcounts, const uint32_t* new_yhat_64kib_popcounts, uint32_t widx) {
264 uint32_t result = 0;
265 const uint32_t idx_64kib = widx / (plink2::kWordsPerCacheline * plink2::kInt16PerCacheline * plink2::kInt16PerCacheline);
266 for (uint32_t uii = 0; uii != idx_64kib; ++uii) {
267 result += new_yhat_64kib_popcounts[uii];
268 }
269 const uint32_t idx_2kib = widx / (plink2::kWordsPerCacheline * plink2::kInt16PerCacheline);
270 for (uint32_t uii = idx_64kib * plink2::kInt16PerCacheline; uii != idx_2kib; ++uii) {
271 result += new_yhat_2kib_popcounts[uii];
272 }
273
274 // Each entry in the bottom-level-index array is <= 512, and we're adding
275 // at most 16 of them even when compiling as 32-bit, so there's no overflow
276 // danger if we add entire words at a time (effectively performing 2-4
277 // uint16 additions in parallel).
278 const uintptr_t* walias_64b_popcounts = reinterpret_cast<const uintptr_t*>(new_yhat_64b_popcounts);
279 const uint32_t widx_64b = widx / (plink2::kWordsPerCacheline * plink2::kInt16PerWord);
280 uintptr_t acc = 0;
281 for (uint32_t uii = idx_2kib * plink2::kWordsPerCacheline; uii != widx_64b; ++uii) {
282 acc += walias_64b_popcounts[uii];
283 }
284 const uint32_t idx_64b = widx / plink2::kWordsPerCacheline;
285 uint32_t remainder = idx_64b % plink2::kInt16PerWord;
286 if (remainder) {
287 acc += plink2::bzhi(walias_64b_popcounts[widx_64b], remainder * 16);
288 }
289 result += (acc * plink2::kMask0001) >> (plink2::kBitsPerWord - 16);
290
291 for (uint32_t uii = idx_64b * plink2::kWordsPerCacheline; uii != widx; ++uii) {
292 result += plink2::PopcountWord(new_yhat_present[uii]);
293 }
294 return result;
295 }
296
297 double CIndexTieheavyMain(const CIndexRec* recs, uintptr_t size, unsigned char* wkspace, uintptr_t* new_yhat_present, uint16_t* new_yhat_64b_popcounts, uint16_t* new_yhat_2kib_popcounts, uint32_t* new_yhat_64kib_popcounts) {
298 // Alternate tie-handling strategy: maintain an additional array which tracks
299 // the number of times we've seen each yhat_int value.
300 uint32_t* yhat_int_multiplicities = static_cast<uint32_t*>(calloc(size, sizeof(int32_t)));
301 if (!yhat_int_multiplicities) {
302 plink2::aligned_free(wkspace);
303 stop("Out of memory");
304 }
305
306 double prev_key = recs[size - 1].key;
307 uint32_t recs_block_end = size;
308 uint32_t new_yhat_entry_ct = 0;
309 uint64_t numer_x2 = 0;
310 uint64_t denom = 0;
311 for (uint32_t recs_idx = size; recs_idx; ) {
312 --recs_idx;
313 const double cur_key = recs[recs_idx].key;
314 if (cur_key != prev_key) {
315 const uint32_t next_block_end = recs_idx + 1;
316 for (uint32_t uii = next_block_end; uii != recs_block_end; ++uii) {
317 const uint32_t yhat_int = recs[uii].yhat_int;
318 const uint32_t multiplicity = yhat_int_multiplicities[yhat_int];
319 const uint32_t adj_yhat_int = yhat_int + multiplicity;
320 yhat_int_multiplicities[yhat_int] = multiplicity + 1;
321 const uintptr_t widx = adj_yhat_int / plink2::kBitsPerWord;
322 const uintptr_t remainder_bit = plink2::k1LU << (adj_yhat_int % plink2::kBitsPerWord);
323 new_yhat_present[widx] |= remainder_bit;
324 new_yhat_64b_popcounts[widx / plink2::kWordsPerCacheline] += 1;
325 new_yhat_2kib_popcounts[widx / (plink2::kWordsPerCacheline * plink2::kInt16PerCacheline)] += 1;
326 new_yhat_64kib_popcounts[widx / (plink2::kWordsPerCacheline * plink2::kInt16PerCacheline * plink2::kInt16PerCacheline)] += 1;
327 }
328 recs_block_end = next_block_end;
329 new_yhat_entry_ct = size - recs_block_end;
330 prev_key = cur_key;
331 }
332 if (!recs[recs_idx].status) {
333 continue;
334 }
335 denom += new_yhat_entry_ct;
336 const uint32_t yhat_int = recs[recs_idx].yhat_int;
337 uint32_t widx = yhat_int / plink2::kBitsPerWord;
338 uint32_t n_set_bits_before = PopcountLookup(new_yhat_present, new_yhat_64b_popcounts, new_yhat_2kib_popcounts, new_yhat_64kib_popcounts, widx);
339 uint32_t remainder = yhat_int % plink2::kBitsPerWord;
340 uintptr_t cur_word = new_yhat_present[widx];
341 uintptr_t remainder_bit = plink2::k1LU << remainder;
342 n_set_bits_before += plink2::PopcountWord(cur_word & (remainder_bit - 1));
343 numer_x2 += 2 * n_set_bits_before + yhat_int_multiplicities[yhat_int];
344 }
345 free(yhat_int_multiplicities);
346 plink2::aligned_free(wkspace);
347 return plink2::u63tod(numer_x2) / plink2::u63tod(denom * 2);
348 }
349
350 uint32_t WtSumLookup(const uint32_t* partial_wts, const uint32_t* partial_wts_64b, const uint32_t* partial_wts_1kib, const uint32_t* partial_wts_16kib, const uint32_t* partial_wts_256kib, const uint32_t* partial_wts_4mib, uint32_t yhat_int) {
351 uint32_t result = 0;
352 const uint32_t idx_4mib = yhat_int >> 20;
353 for (uint32_t uii = 0; uii != idx_4mib; ++uii) {
354 result += partial_wts_4mib[uii];
355 }
356 const uint32_t idx_256kib = yhat_int >> 16;
357 for (uint32_t uii = idx_4mib << 4; uii != idx_256kib; ++uii) {
358 result += partial_wts_256kib[uii];
359 }
360 const uint32_t idx_16kib = yhat_int >> 12;
361 for (uint32_t uii = idx_256kib << 4; uii != idx_16kib; ++uii) {
362 result += partial_wts_16kib[uii];
363 }
364 const uint32_t idx_1kib = yhat_int >> 8;
365 for (uint32_t uii = idx_16kib << 4; uii != idx_1kib; ++uii) {
366 result += partial_wts_1kib[uii];
367 }
368 const uint32_t idx_64b = yhat_int >> 4;
369 for (uint32_t uii = idx_1kib << 4; uii != idx_64b; ++uii) {
370 result += partial_wts_64b[uii];
371 }
372 for (uint32_t uii = idx_64b << 4; uii != yhat_int; ++uii) {
373 result += partial_wts[uii];
374 }
375 return result;
376 }
377
378 typedef struct CIndexWeightedRecStruct {
379 double key; // yhat on first sort, y on second sort
380 uint32_t status; // original pos on first sort
381 uint32_t yhat_int;
382 uint32_t wt;
383 bool operator<(const struct CIndexWeightedRecStruct& rhs) const {
384 return (key < rhs.key);
385 }
386 } CIndexWeightedRec;
387
388 #ifndef DBL_MAX
389 # define DBL_MAX 1.7976931348623157e308
390 #endif
391
392 double CIndexWeighted(NumericVector yhat, NumericVector y, SEXP status, const double* weightsd, uintptr_t orig_size) {
393 // Weighted C-index:
394 // sum_{j: status[j]=1} W[j] [sum_{m: y[m]>y[j]} [W[m] [1(yhat[m]<yhat[j]) +
395 // 0.5 * 1(yhat[m]==yhat[j])]]]
396 // ------------------------------------------------------------------------------
397 // sum_{j: status[j]=1} W[j] [sum_{m: y[m]>y[j]} W[m]]
398 //
399 // To compute the numerator efficiently, we want to be able to look up
400 // partial-weight-sums according to yhat ranks. This can be accomplished
401 // with a "stack of indexes" similar to that used in the unweighted
402 // computation.
403 // Since the main bottlenecks now revolve around the weights, we quantize
404 // them to 32 bits by multiplying them by (constant / |max_wt|) and
405 // rounding to the nearest integer, where the constant is chosen to have good
406 // divisibility properties without risking denom_x2 64-bit integer overflow.
407 // (Note that this tends to be more, not less, accurate than using
408 // double-precision floating-point values for weight arithmetic. In the
409 // unlikely event that more weight accuracy is actually important, 128-bit
410 // integers should be preferred to extended-precision floating-point.)
411 uintptr_t size = 0; // We remove all 0-weight samples before the main loop.
412 double wt_multiplier;
413 double wt_min;
414 {
415 double wt_sum = 0.0;
416 double min_nz_wt = DBL_MAX;
417 for (uintptr_t ulii = 0; ulii != orig_size; ++ulii) {
418 const double cur_wt = weightsd[ulii];
419 if (cur_wt < 0.0) {
420 stop("weights cannot be negative");
421 }
422 if (cur_wt != 0.0) {
423 ++size;
424 wt_sum += cur_wt;
425 if (cur_wt < min_nz_wt) {
426 min_nz_wt = cur_wt;
427 }
428 }
429 }
430 if (wt_sum != wt_sum) {
431 stop("weights cannot be NaN");
432 }
433 if (wt_sum > DBL_MAX) {
434 stop("weights are too large");
435 }
436 if (!size) {
437 stop("at least one weight must be nonzero");
438 }
439 if (size >= (1 << 24)) {
440 // Guarantee 8-bit or better precision for weights.
441 stop("too many nonzero-weight samples for current implementation");
442 }
443 // denom_x2 is guaranteed to be less than sum(quantized weights)^2, so we
444 // just need to ensure sum(quantized weights) < 2^32.
445 // magic constant = 2^32 - 2^24. Since we have less than 2^24 samples with
446 // nonzero weights, this guarantees the sum of the quantized weights is
447 // less than 2^32 regardless of rounding errors.
448 if (min_nz_wt * 4278190080.0 >= wt_sum) {
449 // By choosing wt_multiplier to be a multiple of 1/min_nz_wt, we have
450 // better odds of representing all weights perfectly.
451 // 720720 is the smallest positive integer divisible by 1..16, 360360 is
452 // the smallest positive integer divisible by 1..15, etc.
453 if (min_nz_wt * (4278190080.0 / 720720) >= wt_sum) {
454 wt_multiplier = 720720.0 / min_nz_wt;
455 } else if (min_nz_wt * (4278190080.0 / 360360) >= wt_sum) {
456 wt_multiplier = 360360.0 / min_nz_wt;
457 } else if (min_nz_wt * (4278190080.0 / 27720) >= wt_sum) {
458 wt_multiplier = 27720.0 / min_nz_wt;
459 } else if (min_nz_wt * (4278190080.0 / 2520) >= wt_sum) {
460 wt_multiplier = 2520.0 / min_nz_wt;
461 } else if (min_nz_wt * (4278190080.0 / 840) >= wt_sum) {
462 wt_multiplier = 840.0 / min_nz_wt;
463 } else if (min_nz_wt * (4278190080.0 / 420) >= wt_sum) {
464 wt_multiplier = 420.0 / min_nz_wt;
465 } else if (min_nz_wt * (4278190080.0 / 60) >= wt_sum) {
466 wt_multiplier = 60.0 / min_nz_wt;
467 } else if (min_nz_wt * (4278190080.0 / 12) >= wt_sum) {
468 wt_multiplier = 12.0 / min_nz_wt;
469 } else if (min_nz_wt * (4278190080.0 / 6) >= wt_sum) {
470 wt_multiplier = 6.0 / min_nz_wt;
471 } else if (min_nz_wt * (4278190080.0 / 2) >= wt_sum) {
472 wt_multiplier = 2.0 / min_nz_wt;
473 } else {
474 wt_multiplier = 1.0 / min_nz_wt;
475 }
476 wt_min = min_nz_wt;
477 } else {
478 wt_multiplier = 4278190080.0 / wt_sum;
479 // In this case, it's possible for some more samples to be quantized to
480 // weight-zero. May as well throw those out too.
481 wt_min = 0.5 / wt_multiplier;
482 size = 0;
483 for (uintptr_t ulii = 0; ulii != orig_size; ++ulii) {
484 if (weightsd[ulii] >= wt_min) {
485 ++size;
486 }
487 }
488 }
489 if (wt_multiplier > DBL_MAX) {
490 stop("weights too small");
491 }
492 }
493 const uintptr_t recs_vec_ct = plink2::DivUp(sizeof(CIndexWeightedRec) * size, plink2::kBytesPerVec);
494 // Tracking of partial-weight-sums worsens the constant factor by enough that
495 // there's little point in having a separate code path for the tie-light
496 // case.
497 const uintptr_t yhat_int_multiplicities_vec_ct = plink2::DivUp(size, plink2::kInt32PerVec);
498
499 const uintptr_t partial_wts_cacheline_ct = plink2::DivUp(size, plink2::kInt32PerCacheline);
500 const uintptr_t partial_wts_64b_cacheline_ct = plink2::DivUp(partial_wts_cacheline_ct, plink2::kInt32PerCacheline);
501 const uintptr_t partial_wts_1kib_cacheline_ct = plink2::DivUp(partial_wts_64b_cacheline_ct, plink2::kInt32PerCacheline);
502 const uintptr_t partial_wts_16kib_cacheline_ct = plink2::DivUp(partial_wts_1kib_cacheline_ct, plink2::kInt32PerCacheline);
503 const uintptr_t partial_wts_256kib_cacheline_ct = plink2::DivUp(partial_wts_16kib_cacheline_ct, plink2::kInt32PerCacheline);
504 const uintptr_t partial_wts_4mib_cacheline_ct = plink2::DivUp(partial_wts_256kib_cacheline_ct, plink2::kInt32PerCacheline);
505
506 const uintptr_t vec_ct = recs_vec_ct + 2 * yhat_int_multiplicities_vec_ct + (partial_wts_cacheline_ct + partial_wts_64b_cacheline_ct + partial_wts_1kib_cacheline_ct + partial_wts_16kib_cacheline_ct + partial_wts_256kib_cacheline_ct + partial_wts_4mib_cacheline_ct) * plink2::kVecsPerCacheline;
507 unsigned char* wkspace;
508 if (plink2::cachealigned_malloc(vec_ct * plink2::kBytesPerVec, &wkspace)) {
509 stop("Out of memory");
510 }
511 memset(wkspace, 0, (vec_ct - recs_vec_ct) * plink2::kBytesPerVec);
512 unsigned char* wkspace_iter = wkspace;
513 // Put partial_wts arrays first to guarantee cacheline alignment, since it
514 // matters there.
515 uint32_t* partial_wts = reinterpret_cast<uint32_t*>(wkspace_iter);
516 wkspace_iter = &(wkspace_iter[partial_wts_cacheline_ct * plink2::kCacheline]);
517 uint32_t* partial_wts_64b = reinterpret_cast<uint32_t*>(wkspace_iter);
518 wkspace_iter = &(wkspace_iter[partial_wts_64b_cacheline_ct * plink2::kCacheline]);
519 uint32_t* partial_wts_1kib = reinterpret_cast<uint32_t*>(wkspace_iter);
520 wkspace_iter = &(wkspace_iter[partial_wts_1kib_cacheline_ct * plink2::kCacheline]);
521 uint32_t* partial_wts_16kib = reinterpret_cast<uint32_t*>(wkspace_iter);
522 wkspace_iter = &(wkspace_iter[partial_wts_16kib_cacheline_ct * plink2::kCacheline]);
523 uint32_t* partial_wts_256kib = reinterpret_cast<uint32_t*>(wkspace_iter);
524 wkspace_iter = &(wkspace_iter[partial_wts_256kib_cacheline_ct * plink2::kCacheline]);
525 uint32_t* partial_wts_4mib = reinterpret_cast<uint32_t*>(wkspace_iter);
526 wkspace_iter = &(wkspace_iter[partial_wts_4mib_cacheline_ct * plink2::kCacheline]);
527
528 uint32_t* yhat_int_multiplicities = reinterpret_cast<uint32_t*>(wkspace_iter);
529 wkspace_iter = &(wkspace_iter[yhat_int_multiplicities_vec_ct * plink2::kBytesPerVec]);
530 uint32_t* tie_wt_sums = reinterpret_cast<uint32_t*>(wkspace_iter);
531 wkspace_iter = &(wkspace_iter[yhat_int_multiplicities_vec_ct * plink2::kBytesPerVec]);
532
533 CIndexWeightedRec* recs = reinterpret_cast<CIndexWeightedRec*>(wkspace_iter);
534
535 const double* yd = &(y[0]);
536 {
537 const double* yhatd = &(yhat[0]);
538 uintptr_t new_idx = 0;
539 for (uintptr_t old_idx = 0; old_idx != orig_size; ++old_idx) {
540 const double cur_wt = weightsd[old_idx];
541 if (cur_wt >= wt_min) {
542 recs[new_idx].key = yhatd[old_idx];
543 recs[new_idx].wt = static_cast<int32_t>(wt_multiplier * cur_wt + 0.5);
544 recs[new_idx].status = old_idx;
545 ++new_idx;
546 }
547 }
548 std::sort(recs, &(recs[size]));
549 recs[0].yhat_int = 0;
550 double prev_yhat = recs[0].key;
551 recs[0].key = yd[recs[0].status];
552 uintptr_t prev_idx = 0;
553 for (uintptr_t new_idx = 1; new_idx != size; ++new_idx) {
554 const double cur_yhat = recs[new_idx].key;
555 if (cur_yhat != prev_yhat) {
556 prev_idx = new_idx;
557 prev_yhat = cur_yhat;
558 }
559 recs[new_idx].yhat_int = prev_idx;
560 const uint32_t old_idx = recs[new_idx].status;
561 recs[new_idx].key = yd[old_idx];
562 }
563 }
564 if (TYPEOF(status) == INTSXP) {
565 IntegerVector status_iv = as<IntegerVector>(status);
566 if (orig_size != static_cast<uintptr_t>(status_iv.size())) {
567 plink2::aligned_free(wkspace);
568 stop("y and status must have the same length");
569 }
570 const int32_t* status_ivi = &(status_iv[0]);
571 for (uintptr_t new_idx = 0; new_idx != size; ++new_idx) {
572 const uint32_t old_idx = recs[new_idx].status;
573 const uint32_t cur_status = status_ivi[old_idx];
574 if (cur_status & (~1)) {
575 plink2::aligned_free(wkspace);
576 stop("all status values must be 0 or 1");
577 }
578 recs[new_idx].status = cur_status;
579 }
580 } else {
581 NumericVector status_nv = as<NumericVector>(status);
582 if (orig_size != static_cast<uintptr_t>(status_nv.size())) {
583 plink2::aligned_free(wkspace);
584 stop("y and status must have the same length");
585 }
586 const double* status_nvd = &(status_nv[0]);
587 for (uintptr_t new_idx = 0; new_idx != size; ++new_idx) {
588 const uint32_t old_idx = recs[new_idx].status;
589 const double dxx = status_nvd[old_idx];
590 if (dxx == 0.0) {
591 recs[new_idx].status = 0;
592 } else if (dxx == 1.0) {
593 recs[new_idx].status = 1;
594 } else {
595 plink2::aligned_free(wkspace);
596 stop("all status values must be 0 or 1");
597 }
598 }
599 }
600 std::sort(recs, &(recs[size]));
601
602 double prev_key = recs[size - 1].key;
603 uint32_t recs_block_end = size;
604 uintptr_t higher_y_wt_sum = 0;
605 uint64_t numer_x2 = 0;
606 uint64_t denom = 0;
607 for (uint32_t recs_idx = size; recs_idx; ) {
608 --recs_idx;
609 const double cur_key = recs[recs_idx].key;
610 if (cur_key != prev_key) {
611 const uint32_t next_block_end = recs_idx + 1;
612 for (uint32_t uii = next_block_end; uii != recs_block_end; ++uii) {
613 const uint32_t yhat_int = recs[uii].yhat_int;
614 const uint32_t multiplicity = yhat_int_multiplicities[yhat_int];
615 const uint32_t adj_yhat_int = yhat_int + multiplicity;
616 yhat_int_multiplicities[yhat_int] = multiplicity + 1;
617
618 const uintptr_t cur_wt = recs[uii].wt;
619 tie_wt_sums[yhat_int] += cur_wt;
620 partial_wts[adj_yhat_int] = cur_wt;
621 partial_wts_64b[adj_yhat_int >> 4] += cur_wt;
622 partial_wts_1kib[adj_yhat_int >> 8] += cur_wt;
623 partial_wts_16kib[adj_yhat_int >> 12] += cur_wt;
624 partial_wts_256kib[adj_yhat_int >> 16] += cur_wt;
625 partial_wts_4mib[adj_yhat_int >> 20] += cur_wt;
626 higher_y_wt_sum += cur_wt;
627 }
628 recs_block_end = next_block_end;
629 prev_key = cur_key;
630 }
631 if (!recs[recs_idx].status) {
632 continue;
633 }
634 const uintptr_t cur_wt = recs[recs_idx].wt;
635 denom += cur_wt * static_cast<uint64_t>(higher_y_wt_sum);
636 const uint32_t yhat_int = recs[recs_idx].yhat_int;
637 numer_x2 += cur_wt * (2 * static_cast<uint64_t>(WtSumLookup(partial_wts, partial_wts_64b, partial_wts_1kib, partial_wts_16kib, partial_wts_256kib, partial_wts_4mib, yhat_int)) + tie_wt_sums[yhat_int]);
638 }
639 plink2::aligned_free(wkspace);
640 return plink2::u63tod(numer_x2) / plink2::u63tod(denom * 2);
641 }