| 1 | /* SlopeSelector.cpp |
| 2 | * |
| 3 | * Copyright (C) 2025 David Weenink |
| 4 | * |
| 5 | * This code is free software; you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation; either version 2 of the License, or (at |
| 8 | * your option) any later version. |
| 9 | * |
| 10 | * This code is distributed in the hope that it will be useful, but |
| 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | * General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | #include <limits> |
| 20 | #include "NUMselect.h" |
| 21 | #include "PermutationInversionCounter.h" |
| 22 | #include "SlopeSelector.h" |
| 23 | |
| 24 | #include "oo_DESTROY.h" |
| 25 | #include "SlopeSelector_def.h" |
| 26 | #include "oo_COPY.h" |
| 27 | #include "SlopeSelector_def.h" |
| 28 | #include "oo_EQUAL.h" |
| 29 | #include "SlopeSelector_def.h" |
| 30 | #include "oo_CAN_WRITE_AS_ENCODING.h" |
| 31 | #include "SlopeSelector_def.h" |
| 32 | #include "oo_WRITE_TEXT.h" |
| 33 | #include "SlopeSelector_def.h" |
| 34 | #include "oo_READ_TEXT.h" |
| 35 | #include "SlopeSelector_def.h" |
| 36 | #include "oo_WRITE_BINARY.h" |
| 37 | #include "SlopeSelector_def.h" |
| 38 | #include "oo_READ_BINARY.h" |
| 39 | #include "SlopeSelector_def.h" |
| 40 | #include "oo_DESCRIPTION.h" |
| 41 | #include "SlopeSelector_def.h" |
| 42 | |
| 43 | #include "enums_getText.h" |
| 44 | #include "SlopeSelector_enums.h" |
| 45 | #include "enums_getValue.h" |
| 46 | #include "SlopeSelector_enums.h" |
| 47 | |
| 48 | static void randomInteger_INTVEC_inout (INTVEC iv, integer ilow, integer ihigh) { |
| 49 | for (integer i = 1; i <= iv.size; i ++) |
| 50 | iv [i] = NUMrandomInteger (ilow, ihigh); |
| 51 | } |
| 52 | |
| 53 | Thing_implement (SlopeSelector, Daata, 1); |
| 54 | |
| 55 | void structSlopeSelector :: newDataPoints (constVEC const& x, constVEC const& y) { |
| 56 | Melder_assert (x.size == y.size); |
| 57 | Melder_assert (x.size == numberOfPoints); |
| 58 | xp = x; |
| 59 | yp = y; |
| 60 | } |
| 61 | |
| 62 | void structSlopeSelector :: getSlopeAndIntercept_leastSquares (double &slope, double& intercept) { |
| 63 | const double xsum = NUMsum (xp); |
| 64 | const double xmean = xsum / numberOfPoints; |
| 65 | longdouble variance = 0.0; |
| 66 | slope = 0; |
| 67 | for (integer i = 1; i <= numberOfPoints; i ++) { |
| 68 | const double ti = xp [i] - xmean; |
| 69 | variance += ti * ti; |
| 70 | slope += ti * yp [i]; |
| 71 | } |
| 72 | slope /= variance; |
| 73 | const double ysum = NUMsum (yp); |
| 74 | intercept = (ysum - xsum * slope) / numberOfPoints; |
| 75 | } |
| 76 | |
| 77 | double structSlopeSelector :: getIntercept (double slope) { |
| 78 | buffer.resize (numberOfPoints); |
| 79 | for (integer i = 1; i <= numberOfPoints; i ++) { |
| 80 | buffer [i] = yp [i] - slope * xp [i]; |
| 81 | } |
| 82 | return num::NUMquantile_e (buffer.get(), 0.5); |
| 83 | } |
| 84 | |
| 85 | double structSlopeSelector :: getSlope_Siegel () { |
| 86 | integer numberOfMedians = 0; |
| 87 | /* reuse buffer*/ |
| 88 | buffer.resize (buffer._capacity); |
| 89 | const integer siegelSize = numberOfPoints - 1; |
| 90 | VEC siegelSlopes = buffer.part (1, siegelSize); |
| 91 | VEC siegelMedians = buffer.part (siegelSize + 1, 2 * siegelSize); |
| 92 | for (integer i = 1; i <= numberOfPoints; i ++) { |
| 93 | integer iline = 0; |
| 94 | for (integer j = 1; j <= numberOfPoints; j ++) { |
| 95 | if (i != j) |
| 96 | siegelSlopes [++ iline] = (yp [i] - yp [j]) / (xp [i] - xp [j]); |
| 97 | } |
| 98 | Melder_assert (iline == siegelSize); |
| 99 | siegelMedians [++ numberOfMedians] = num::NUMquantile_e (siegelSlopes, 0.5); |
| 100 | } |
| 101 | Melder_assert (numberOfMedians == numberOfPoints); |
| 102 | return num::NUMquantile_e (siegelMedians, 0.5); |
| 103 | } |
| 104 | |
| 105 | /* |
| 106 | Given point (X[i],Y[I]), where I=1..n. |
| 107 | In the dual space the n lines are given by y = X[I]x - Y[I]. Our X[I] are ordered, i.e., |
| 108 | if I < J then X[I] < X[J]. This means that at -infinity the line with X[1] has the largest |
| 109 | y-values while the line with X[n] has the lowest y-values. We will number the dual line |
| 110 | with X[n] as line number 1 and the line with X[1] as line number n. |
| 111 | Therefore the indices i of the lines in dual space are reverse to the indices I of the |
| 112 | points: i = n - I + 1 |
| 113 | Equation of line i: y(i) = X [I].x - Y [I] = X [n-i+1].x - Y [n-i+1]. |
| 114 | Line i and line j cross each other at the x where y(i) = y(j) |
| 115 | This gives x = (Y[I]-Y[J])/(X[I]-X[J]) = slope[i,j]! |
| 116 | |
| 117 | By using infinitesimals on the Y[I] we can guarantee that all x's are different |
| 118 | and also that all values at x of y(x) = X [I].x - Y [I] are different too! |
| 119 | |
| 120 | */ |
| 121 | void structSlopeSelector :: getKth_TheilSen (integer k, double& kth, double& kp1th) { |
| 122 | try { |
| 123 | const integer maxNumberOfIntervalCrossings = numberOfPoints * (numberOfPoints - 1) / 2; |
| 124 | const integer krt = Melder_iroundDown (/* 1.5 */ sqrt (sampleSize)); // smaller than in the paper |
| 125 | const double sampleSize_real = sampleSize; |
| 126 | integer currentNumberOfIntervalCrossings = maxNumberOfIntervalCrossings; |
| 127 | integer numberOfCrossingsAtLowX = 0, numberOfCrossingsAtLowXPrevious = 0; |
| 128 | integer numberOfCrossingsAtHighX = maxNumberOfIntervalCrossings, numberOfCrossingsAtHighXPrevious = maxNumberOfIntervalCrossings; |
| 129 | integer kappa = k, ilow, ihigh; |
| 130 | structExtendedCrossing lowXPrevious, lowX = {- std::numeric_limits<double>::infinity(), 0, 0}; |
| 131 | |
| 132 | auto approximatelyEqual = [&] (double lhs, double rhs, double numericalEqualityPrecision) { |
| 133 | if (std::fabs (lhs) < numericalEqualityPrecision || std::fabs (rhs) < numericalEqualityPrecision) { |
| 134 | return std::fabs (lhs - rhs) < numericalEqualityPrecision; |
| 135 | } |
| 136 | // Use relative difference otherwise |
| 137 | return std::fabs (lhs - rhs) <= numericalEqualityPrecision * std::fmax (std::fabs (lhs), std::fabs (rhs)); |
| 138 | }; |
| 139 | |
| 140 | auto getSlopes = [&] (integer numberOfSlopes) { |
| 141 | Melder_assert (numberOfSlopes <= maximumContractionSize); |
| 142 | xslopes.resize (numberOfSlopes); |
| 143 | for (integer j = 1, i = 1; i <= numberOfSlopes; i ++, j += 2) { |
| 144 | ilow = currentInversions [j]; |
| 145 | ihigh = currentInversions [j + 1]; |
| 146 | const integer ipoint = numberOfPoints + 1 - ilow; // ilow |
| 147 | const integer jpoint = numberOfPoints + 1 - ihigh; // ihigh; |
| 148 | xslopes [i].real = (yp [ipoint] - yp [jpoint]) / (xp [ipoint] - xp [jpoint]); // the slope |
| 149 | xslopes [i].low = ilow; |
| 150 | xslopes [i].high = ihigh; |
| 151 | } |
| 152 | }; |
| 153 | |
| 154 | auto getPermutationAtX = [&](structExtendedCrossing& x, mutablePermutation p) { |
| 155 | for (integer iline = 1; iline <= numberOfPoints; iline ++) { |
| 156 | const integer ipoint = numberOfPoints + 1 - iline; |
| 157 | xcrossings [iline].real = x.real * xp [ipoint] - yp [ipoint]; // the dual line's y-value |
| 158 | xcrossings [iline].low = iline; // k or l |
| 159 | xcrossings [iline].high = x.high; // j |
| 160 | p -> p [iline] = iline; |
| 161 | } |
| 162 | std::sort (p -> p.begin(), p -> p.end(), |
| 163 | [&] (integer& leftLineNumber, integer& rightLineNumber) { |
| 164 | const structExtendedCrossing& lhs = xcrossings [leftLineNumber]; |
| 165 | const structExtendedCrossing& rhs = xcrossings [rightLineNumber]; |
| 166 | // Y[k]<Y[l]= if y[k]!=y[l] then (y[k]<y[l]) else (if k<l then (j>l) else (j<k)) |
| 167 | const bool r = ( !approximatelyEqual (lhs.real, rhs.real, 1e-12) ? (lhs.real < rhs.real) : |
| 168 | (lhs.low < rhs.low ? (lhs.high > rhs.low) : (lhs.high < lhs.low)) ); |
| 169 | return r; |
| 170 | } |
| 171 | ); |
| 172 | return inversionCounter -> getNumberOfInversions (p); |
| 173 | }; |
| 174 | |
| 175 | |
| 176 | /* |
| 177 | In Matoušek's paper the following loop has to be run until the currentNumberOfIntervalCrossings <= samplingSize. |
| 178 | We changed this to a number 10 times larger to reduce the number of iterations of this loop because |
| 179 | the selection of a random sample of the inversions in the interval [xlow,xHigh] with the function |
| 180 | 'getSelectedInversionsNotInOther' is by far the most computational expensive part in the loop. |
| 181 | Reducing the number of iterations of this loop therefore saves more time than calculating somewhat more slopes. |
| 182 | */ |
| 183 | numberOfTries = 0; |
| 184 | currentInversions.resize (2 * sampleSize); |
| 185 | sortedRandomCrossingCodes.resize (sampleSize); // during the loop |
| 186 | while (currentNumberOfIntervalCrossings > std::min (maximumContractionSize, maxNumberOfIntervalCrossings)) { // sampleSize*10 |
| 187 | |
| 188 | /* |
| 189 | Pick a random sample of size sampleSize from the intersections in the interval (lowX, highX) |
| 190 | and store these in the vector 'currentInversions'. |
| 191 | The first time we have the maximum number of slopes in our interval (-inf, +inf) and |
| 192 | therefore the current inversions can be sampled directly. |
| 193 | In the other cases we have n' < n(n-1)/2 slopes and pick sampleSize random numbers from the |
| 194 | interval [1,n']. We then search the corresponding slopes in O(n log(n)) time. |
| 195 | */ |
| 196 | if (numberOfTries == 0) { |
| 197 | for (integer i = 1; i <= sampleSize; i ++) { |
| 198 | const integer irandom = NUMrandomInteger (1_integer, currentNumberOfIntervalCrossings); |
| 199 | getInversionFromCode (irandom, ilow, ihigh); |
| 200 | currentInversions [2 * i - 1] = ilow; |
| 201 | currentInversions [2 * i ] = ihigh; |
| 202 | } |
| 203 | } else { |
| 204 | randomInteger_INTVEC_inout (sortedRandomCrossingCodes.get(), 1_integer, currentNumberOfIntervalCrossings); |
| 205 | sort_INTVEC_inout (sortedRandomCrossingCodes.get()); |
| 206 | inversionCounter -> getSelectedInversionsNotInOther ( |
| 207 | lineRankingAtHighX.get(), inverseOfLineRankingAtLowX.get(), sortedRandomCrossingCodes.get(), currentInversions.get() |
| 208 | ); |
| 209 | } |
| 210 | |
| 211 | getSlopes (sampleSize); |
| 212 | |
| 213 | const double kappar = sampleSize_real / currentNumberOfIntervalCrossings * (k - numberOfCrossingsAtLowX); |
| 214 | kappa = std::max (1_integer, Melder_iroundDown (kappar)); |
| 215 | const integer kb = std::max (1_integer, kappa - krt); |
| 216 | const integer ke = std::min (sampleSize, kappa + krt); |
| 217 | lowXPrevious = lowX; |
| 218 | lowX = num::NUMget_kth (xslopes.get(), kb); |
| 219 | structExtendedCrossing highX = num::NUMget_kth (xslopes.get(), ke); |
| 220 | trace (U"lowX:", lowX.real, U" highX:", highX.real); |
| 221 | /* |
| 222 | We have one of the following five situations for k, when lpX & hpX are the previous interval borders, |
| 223 | lowX & highX the current interval borders and nlow and nhigh the number of inversions at the |
| 224 | current borders. |
| 225 | | | |
| 226 | lowXPrevious highXPrevious |
| 227 | | | |
| 228 | lowX (?==?) highX |
| 229 | nlow nhigh |
| 230 | k k k k k |
| 231 | (1) (2) (3) (4) (5) |
| 232 | (1) k < nlow, we make lowX the new upper border |
| 233 | (2) k == nlow, we know that kth == lowX |
| 234 | (3) nlow < k < nhigh , next |
| 235 | (4) k == nhigh |
| 236 | (5) k > nhigh, make highX the new lowX |
| 237 | */ |
| 238 | if (numberOfTries > 0) { // for the first try the history is already there |
| 239 | numberOfCrossingsAtLowXPrevious = numberOfCrossingsAtLowX; |
| 240 | lineRankingAtLowXPrevious -> p.get() <<= lineRankingAtLowX -> p.get(); |
| 241 | } |
| 242 | numberOfCrossingsAtLowX = getPermutationAtX (lowX, lineRankingAtLowX.get()); |
| 243 | trace (U"k:", k, U" kb:", kb, U" ke:", ke, U" ss:", sampleSize, U" ", numberOfCrossingsAtLowX, U" tries:", numberOfTries); |
| 244 | if (k < numberOfCrossingsAtLowX) { // (1) interval lp, lc |
| 245 | Permutations_swap (lineRankingAtHighX.get(), lineRankingAtLowX.get()); // first set lineRankingAtHighX |
| 246 | numberOfCrossingsAtHighX = numberOfCrossingsAtLowX; |
| 247 | trace (U"k<l ", lowX.real, U" ", lowX.low, U" ", highX.real, U" ", highX.low); |
| 248 | Permutations_swap (lineRankingAtLowX.get(), lineRankingAtLowXPrevious.get()); // then lineRankingAtLowX |
| 249 | numberOfCrossingsAtLowX = numberOfCrossingsAtLowXPrevious; |
| 250 | highX = lowX; |
| 251 | lowX = lowXPrevious; |
| 252 | // inverseOfLineRankingAtLowX is still valid!! |
| 253 | } else if (k == numberOfCrossingsAtLowX) { |
| 254 | kth = lowX.real; |
| 255 | const integer kbp1 = kb + 1; |
| 256 | highX = num::NUMget_kth (xslopes.get(), kbp1); |
| 257 | numberOfCrossingsAtHighX = getPermutationAtX (highX, lineRankingAtHighX.get()); |
| 258 | trace (U"k=l ", lowX.real, U" ", highX.real, U" ", numberOfCrossingsAtHighX); |
| 259 | } else { // (3,4,5}) k > numberOfCrossingsAtLowX) |
| 260 | if (numberOfTries > 0) { |
| 261 | numberOfCrossingsAtHighXPrevious = numberOfCrossingsAtHighX; |
| 262 | lineRankingAtHighXPrevious -> p.get() <<= lineRankingAtHighX -> p.get(); |
| 263 | } |
| 264 | numberOfCrossingsAtHighX = getPermutationAtX (highX, lineRankingAtHighX.get()); |
| 265 | if (k < numberOfCrossingsAtHighX) { // (3) |
| 266 | trace (U"k<h "); |
| 267 | if (approximatelyEqual (lowX.real, highX.real, 1e-14)) { |
| 268 | kth = kp1th = lowX.real; |
| 269 | return; |
| 270 | } |
| 271 | // ok new interval |
| 272 | } else if (k == numberOfCrossingsAtHighX) { // (4) |
| 273 | kth = highX.real; |
| 274 | const integer kep1 = ke + 1; |
| 275 | if (kep1 <= sampleSize) { |
| 276 | highX = num::NUMget_kth (xslopes.get(), kep1); |
| 277 | if (kth == highX.real) { |
| 278 | kp1th = kth; |
| 279 | return; |
| 280 | } |
| 281 | trace (U"highX2:", highX.real); |
| 282 | } else { |
| 283 | Permutations_swap (lineRankingAtLowX.get(), lineRankingAtHighX.get()); |
| 284 | numberOfCrossingsAtLowX = numberOfCrossingsAtHighX; |
| 285 | } |
| 286 | numberOfCrossingsAtHighX = getPermutationAtX (highX, lineRankingAtHighX.get()); |
| 287 | trace (U"k=h ", numberOfCrossingsAtHighX); |
| 288 | } else { // (5) k > numberOfCrossingsAtHighX |
| 289 | Permutations_swap (lineRankingAtLowX.get(), lineRankingAtHighX.get()); |
| 290 | numberOfCrossingsAtLowX = numberOfCrossingsAtHighX; |
| 291 | Permutations_swap (lineRankingAtHighX.get(), lineRankingAtHighXPrevious.get()); |
| 292 | numberOfCrossingsAtHighX = numberOfCrossingsAtHighXPrevious; |
| 293 | trace (U"k>h"); |
| 294 | } |
| 295 | Permutation_invert_into (lineRankingAtLowX.get(), inverseOfLineRankingAtLowX.get()); |
| 296 | } |
| 297 | currentNumberOfIntervalCrossings = numberOfCrossingsAtHighX - numberOfCrossingsAtLowX; |
| 298 | ++ numberOfTries; |
| 299 | if (numberOfTries > maximumNumberOfTries) { // escape |
| 300 | getSlope_Siegel (); |
| 301 | return; |
| 302 | } |
| 303 | } |
| 304 | /* |
| 305 | Finish with the remaining inversions. (We don't need the xcrossings anymore.) |
| 306 | */ |
| 307 | sortedRandomCrossingCodes.resize (currentNumberOfIntervalCrossings); |
| 308 | currentInversions.resize (2 * currentNumberOfIntervalCrossings); |
| 309 | for (integer i = 1; i <= currentNumberOfIntervalCrossings; i ++) |
| 310 | sortedRandomCrossingCodes [i] = i; |
| 311 | (void) inversionCounter -> getSelectedInversionsNotInOther (lineRankingAtHighX.get(), |
| 312 | inverseOfLineRankingAtLowX.get(), sortedRandomCrossingCodes.get(), currentInversions.get()); |
| 313 | Melder_assert (currentNumberOfIntervalCrossings == inversionCounter -> numberOfInversionsRegistered); |
| 314 | getSlopes (currentNumberOfIntervalCrossings); |
| 315 | kappa = k - numberOfCrossingsAtLowX; |
| 316 | if (kappa > 0) { // or should we avoid this situation |
| 317 | num::NUMselect (xslopes.get(), kappa); |
| 318 | kth = xslopes [kappa].real; |
| 319 | } |
| 320 | trace (kappa, U" ", numberOfCrossingsAtLowX, U" ", currentNumberOfIntervalCrossings); |
| 321 | kp1th = xslopes [kappa + 1].real; |
| 322 | for (integer i = kappa + 2; i <= currentNumberOfIntervalCrossings; i ++) |
| 323 | if (xslopes [i].real < kp1th) |
| 324 | kp1th = xslopes [i].real; |
| 325 | } catch (MelderError) { |
| 326 | Melder_throw (U"kth slope could not be selected."); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | double structSlopeSelector :: slopeQuantile_TheilSen (double factor) { |
| 331 | const integer numberOfLines = xp.size * (xp.size - 1) / 2; |
| 332 | const double place = factor * numberOfLines + 0.5; |
| 333 | const integer left = Melder_clipped (1_integer, Melder_ifloor (place), numberOfLines); |
| 334 | Melder_assert (numberOfLines - 1 >= 1); |
| 335 | double kleft, kright; |
| 336 | getKth_TheilSen (left, kleft, kright); |
| 337 | const double dif = kright - kleft; |
| 338 | if (dif == 0.0) |
| 339 | return kleft; |
| 340 | return kleft + (place - left) * dif; |
| 341 | } |
| 342 | |
| 343 | double structSlopeSelector :: getSlope_TheilSen () { |
| 344 | return slopeQuantile_TheilSen (0.5); |
| 345 | } |
| 346 | |
| 347 | // buffer.size == xp.size * (xp.size - 1) / 2 |
| 348 | double structSlopeSelector :: slopeQuantile_orderNSquaredWithBuffer (double factor, VEC const& buffer) { |
| 349 | const integer numberOfLines = xp.size * (xp.size - 1) / 2; |
| 350 | Melder_assert (numberOfLines == buffer.size); |
| 351 | integer index = 0; |
| 352 | for (integer i = 1; i < xp.size; i ++) |
| 353 | for (integer j = i + 1; j <= xp.size; j ++) |
| 354 | buffer [++ index] = (yp [j] - yp [i]) / (xp [j] - xp [i]); |
| 355 | Melder_assert (index == numberOfLines); |
| 356 | const double medianSlope = num::NUMquantile_e (buffer, factor); |
| 357 | return medianSlope; |
| 358 | } |
| 359 | |
| 360 | static void SlopeSelector_init (SlopeSelector me, integer numberOfPoints) { |
| 361 | my numberOfPoints = numberOfPoints; |
| 362 | my sampleSize = my numberOfPoints; |
| 363 | my maximumContractionSize = 5 * my numberOfPoints; |
| 364 | my maximumNumberOfTries = 20; |
| 365 | |
| 366 | my sortedRandomCrossingCodes = raw_INTVEC (my maximumContractionSize); |
| 367 | my inversionsSize = 2 * my maximumContractionSize; |
| 368 | my currentInversions = raw_INTVEC (my inversionsSize); |
| 369 | my xslopes = newvectorraw <structExtendedCrossing> (my maximumContractionSize); |
| 370 | my buffer = raw_VEC (my maximumContractionSize); |
| 371 | my xcrossings = newvectorraw <structExtendedCrossing> (my numberOfPoints); |
| 372 | my lineRankingAtLowX = Permutation_create (my numberOfPoints, true); // 1..n |
| 373 | my lineRankingAtHighX = Permutation_reverse (my lineRankingAtLowX.get(), 0, 0); // n..1 |
| 374 | my lineRankingAtLowXPrevious = Permutation_create (my numberOfPoints, true); // 1..n |
| 375 | my lineRankingAtHighXPrevious = Permutation_reverse (my lineRankingAtLowX.get(), 0, 0); // n..1 |
| 376 | my inverseOfLineRankingAtLowX = Permutation_create (my numberOfPoints, true); // 1..n |
| 377 | my inversionCounter = PermutationInversionCounter_create (my numberOfPoints); |
| 378 | } |
| 379 | |
| 380 | autoSlopeSelector SlopeSelector_create (integer numberOfPoints) { |
| 381 | try { |
| 382 | autoSlopeSelector me = Thing_new (SlopeSelector); |
| 383 | SlopeSelector_init (me.get(), numberOfPoints); |
| 384 | return me; |
| 385 | } catch (MelderError) { |
| 386 | Melder_throw (U"Cannot create SlopeSelector."); |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | autoSlopeSelector SlopeSelector_create (constVEC const& x, constVEC const& y) { |
| 391 | try { |
| 392 | Melder_assert (x.size == y.size); |
| 393 | Melder_assert (x.size > 1); |
| 394 | autoSlopeSelector me = Thing_new (SlopeSelector); |
| 395 | SlopeSelector_init (me.get(), x.size); |
| 396 | my newDataPoints (x, y); |
| 397 | return me; |
| 398 | } catch (MelderError) { |
| 399 | Melder_throw (U"Cannot create SlopeSelector from data points."); |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | static void SlopeSelectorTheilSen_getMedianSlope (SlopeSelector me, double& slope, double& intercept) { |
| 404 | slope = my slopeQuantile (0.5); |
| 405 | intercept = my getIntercept (slope); |
| 406 | } |
| 407 | |
| 408 | void SlopeSelector_getSlopeAndIntercept (SlopeSelector me, double &slope, double &intercept, kSlopeSelector_method method) { |
| 409 | if (method == kSlopeSelector_method :: THEILSEN) { |
| 410 | slope = my getSlope_TheilSen (); |
| 411 | intercept = my getIntercept (slope); |
| 412 | } else if (method == kSlopeSelector_method :: SIEGEL) { |
| 413 | slope = my getSlope_Siegel (); |
| 414 | intercept = my getIntercept (slope); |
| 415 | } else if (method == kSlopeSelector_method :: LEAST_SQUARES) { |
| 416 | my getSlopeAndIntercept_leastSquares (slope, intercept); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | static void oneSpecial () { // gave a wrong slope (e-316) |
| 421 | const integer n = 50; |
| 422 | autoVEC y {0, 0.30673083561016756, 0.61346167122033513, 0.92019250683050269, 1.2269233424406703, 1.5336541780508377, 1.8403850136610054, 2.1471158492711728, 2.4538466848813405, 2.7605775204915082, 3.0673083561016754, 3.3740391917118435, 3.6807700273220108, 3.987500862932178, 4.2942316985423457, 4.6009625341525133, 4.907693369762681, 5.2144242053728478, 5.5211550409830163, -1.4631136353303322, 12.947760971671986, 6.4413475478135185, 6.748078383423687, 7.0548092190338538, 7.3615400546440215, 7.6682708902541883, 7.975001725864356, 8.2817325614745236, 8.5884633970846913, 8.895194232694859, 9.2019250683050267, 18.280348785400811, 9.815386739525362, 10.12211757513553, 10.428848410745696, 10.735579246355865, 11.042310081966033, 11.349040917576199, 11.655771753186368, 11.962502588796536, 12.269233424406702, 12.575964260016869, 12.882695095627037, 13.189425931237205, 13.496156766847374, 13.802887602457542, 14.109618438067708, 14.416349273677875, 33.000553040186531, 15.029810944898209}; |
| 423 | autoVEC x = from_to_count_VEC (0.0, 10.0, n); |
| 424 | autoSlopeSelector sls = SlopeSelector_create (x.get(), y.get()); |
| 425 | const double slope = 1.502981094489821, factor = 0.5; |
| 426 | const double slope4 = sls -> slopeQuantile_TheilSen (factor); |
| 427 | } |
| 428 | |
| 429 | static void special50 () { // gets stucck because needs > maximumNumberOfTries |
| 430 | //const integer n = 50; |
| 431 | autoVEC x {0, 0.20408163265306123, 0.40816326530612246, 0.61224489795918369, 0.81632653061224492, 1.0204081632653061, 1.2244897959183674, 1.4285714285714286, 1.6326530612244898, 1.8367346938775511, 2.0408163265306123, 2.2448979591836737, 2.4489795918367347, 2.6530612244897958, 2.8571428571428572, 3.0612244897959187, 3.2653061224489797, 3.4693877551020407, 3.6734693877551021, 3.8775510204081636, 4.0816326530612246, 4.2857142857142856, 4.4897959183673475, 4.6938775510204085, 4.8979591836734695, 5.1020408163265305, 5.3061224489795915, 5.5102040816326534, 5.7142857142857144, 5.9183673469387754, 6.1224489795918373, 6.3265306122448983, 6.5306122448979593, 6.7346938775510203, 6.9387755102040813, 7.1428571428571432, 7.3469387755102042, 7.5510204081632653, 7.7551020408163271, 7.9591836734693882, 8.1632653061224492, 8.3673469387755102, 8.5714285714285712, 8.7755102040816322, 8.979591836734695, 9.183673469387756, 9.387755102040817, 9.591836734693878, 9.795918367346939, 10}; |
| 432 | autoVEC y {0, 0.92803998653746245, 1.8560799730749249, 2.7841199596123873, 3.7121599461498498, 4.6401999326873122, 5.5682399192247747, 6.4962799057622371, 7.4243198922996996, 8.3523598788371629, 9.2803998653746245, 10.208439851912088, 11.136479838449549, 12.064519824987011, 12.992559811524474, 13.920599798061938, 14.848639784599399, 15.776679771136861, 16.704719757674326, 17.632759744211789, 18.560799730749249, 11.892870479075036, 20.416879703824176, 21.344919690361639, 22.272959676899099, 23.200999663436559, 24.129039649974022, 25.057079636511489, 25.985119623048949, 26.913159609586408, 27.841199596123875, 28.769239582661339, 29.697279569198798, 30.625319555736258, 31.553359542273721, 32.481399528811188, 33.409439515348652, 34.337479501886108, 35.265519488423578, 36.193559474961035, 52.020555528667835, 38.049639448035961, 38.977679434573417, 39.905719421110881, 40.833759407648351, 48.501531333854921, 42.689839380723278, 43.617879367260734, 44.545919353798197, 35.700411620170151}; |
| 433 | autoSlopeSelector sls = SlopeSelector_create (x.get(), y.get()); |
| 434 | //double slope = sls -> getSlope_TheilSen (); |
| 435 | } |
| 436 | /* |
| 437 | 22/2/2025 |
| 438 | Old: n² slopes, sort, NUMquantile(0.5) |
| 439 | New: Matoušek (1991) O(n log(n)) ? |
| 440 | n ntries tTS tSiegel tOld tOld/tTS tOld/tSiegel SlopeOld/Siegel |
| 441 | 10 0 8.3446e-06 1.3589e-05 9.2983e-06 *0.6140* 0.8974 1.0057 |
| 442 | 50 2 6.9379e-05 0.0002 0.0001 *0.3115* 0.3493 1.0007 |
| 443 | 100 4 0.0002 0.0009 0.0008 *0.2950* 0.3647 1.0021 |
| 444 | 500 3 0.0056 0.0021 0.0091 *2.6722* 0.6178 1.0015 |
| 445 | 1000 4 0.0075 0.0065 0.0205 *1.1525* 0.3706 1.0007 |
| 446 | 5000 3 0.2045 0.0465 0.4115 *4.3929* 0.4970 1.0003 |
| 447 | 10000 4 0.7233 0.2095 1.7015 *3.4526* 0.4251 0.9996 |
| 448 | */ |
| 449 | void timeSlopeSelection () { |
| 450 | try { |
| 451 | Melder_clearInfo (); |
| 452 | autoINTVEC sizes { 10_integer, 50_integer, 100_integer, 500_integer, 1000_integer, 5000_integer, 10000_integer }; |
| 453 | MelderInfo_write (U"Old: n² slopes, sort, NUMquantile(0.5)\n" |
| 454 | "New: Matoušek (1991) O(n log(n))\n" |
| 455 | ); |
| 456 | special50(); |
| 457 | oneSpecial(); |
| 458 | |
| 459 | MelderInfo_writeLine (U"n ntries tTS tSiegel tOld tOld/tTS tOld/tSiegel SlopeOld/Siegel"); |
| 460 | for (integer isize = 1; isize <= sizes.size; isize ++) { |
| 461 | double slope = 1.0, b = 4.0, stddev = 0.1, factor = 0.5; |
| 462 | const integer n = sizes [isize]; |
| 463 | const integer maxNumberOfLines = n * (n - 1) / 2; |
| 464 | autoVEC x = from_to_count_VEC (0.0, 10.0, n); |
| 465 | autoVEC y = randomGauss_VEC (n, b, stddev); |
| 466 | for (integer i = 1; i <= n; i ++) |
| 467 | y[i] += slope * x [i]; |
| 468 | autoSlopeSelector sls = SlopeSelector_create (x.get(), y.get()); |
| 469 | autoVEC buffer = raw_VEC (maxNumberOfLines); |
| 470 | Melder_stopwatch (); |
| 471 | const double slope1 = sls -> slopeQuantile_orderNSquaredWithBuffer (factor, buffer.get()); |
| 472 | const double t1 = Melder_stopwatch (); |
| 473 | const double slope2 = sls -> slopeQuantile_TheilSen (factor); |
| 474 | const double t2 = Melder_stopwatch (); |
| 475 | const integer ntries = sls -> numberOfTries; |
| 476 | Melder_assert (slope1 == slope2); |
| 477 | Melder_stopwatch (); |
| 478 | const double slope3 = sls -> getSlope_Siegel (); |
| 479 | const double t3 = Melder_stopwatch (); |
| 480 | MelderInfo_writeLine (n, U" ", ntries, U" ", t1, U" ", t2, U" ", t3, U" *", t1 / t2, U"*", U" ", t1 / t3, U" ", slope1/slope3); |
| 481 | /* corner cases with many equal slopes */ |
| 482 | |
| 483 | MelderInfo_writeLine (U"\n\n\n"); |
| 484 | for (integer i = 1; i <= 5; i ++) { |
| 485 | const double slope = NUMrandomUniform (0.1, 10.0); |
| 486 | for (integer i = 1; i <= n; i ++) |
| 487 | y[i] = slope * x [i]; |
| 488 | for (integer j = 1; j <= n / 10; j ++) { |
| 489 | const integer index = NUMrandomInteger (1, n); |
| 490 | y [index] += NUMrandomUniform (-20.0, 20.0); |
| 491 | } |
| 492 | sls -> newDataPoints (x.get(), y.get()); |
| 493 | const double slope4 = sls -> slopeQuantile_TheilSen (factor); |
| 494 | MelderInfo_writeLine (U"slope:", slope, U" TS:", slope4, U" ", fabs ((slope4 - slope) / slope)); |
| 495 | //Melder_assert (fabs ((slope4 - slope) / slope) < 1e-12); |
| 496 | } |
| 497 | } |
| 498 | MelderInfo_close (); |
| 499 | } catch (MelderError) { |
| 500 | Melder_throw (U""); |
| 501 | } |
| 502 | } |
| 503 | /* End of file SlopeSelector.cpp */ |