-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.c
1969 lines (1771 loc) · 48.5 KB
/
utilities.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
/* MigSelect 2013-2019 Arun Sethuraman, Vitor Sousa, Jody Hey */
/* This code was developed based on IMa2 2009-2010 Jody Hey, Rasmus Nielsen and Sang Chul Choi*/
#undef GLOBVARS
#include "imamp.h"
#include "utilities.h"
/*********** LOCAL STUFF **********/
double loghalffact[50 * ABSMIGMAX];
int BITNUMBERTRUE[256];
unsigned long *iseed;
/* function prototype */
static int *ivector (long nl, long nh);
static void free_ivector (int *v, long nl/* , long nh*/);
static double bessi0 (double x);
static double bessi1 (double x);
/* try a new random number generator in rand.c */
void init_genrand(unsigned long s);
unsigned long genrand_int32(void);
/* generates a random number on (0,1)-real-interval */
double genrand_real3(void);
#ifdef SANITY_TEST
/* used in testing only */
unsigned long getKnownRandom(void);
#endif /* SANITY_TEST */
// stuff called by indexx() - sorting an index, from NR
#define NRANSI
#define NR_END 1l
#define FREE_ARG char*
int *
ivector (long nl, long nh)
/* allocate an int vector with subscript range v[nl..nh] */
{
int *v;
v = (int *) malloc ((size_t) ((nh - nl + 1 + NR_END) * sizeof (int)));
if (!v)
{
nrerror ("allocation failure in ivector()");
}
return v - nl + NR_END;
}
void
free_ivector (int *v, long nl/*, long nh*/)
/* free an int vector allocated with ivector() */
{
free ((FREE_ARG) (v + nl - NR_END));
}
double
bessi0 (double x)
{
double ax, ans;
double y;
if ((ax = fabs (x)) < 3.75)
{
y = x / 3.75;
y *= y;
ans = 1.0 + y * (3.5156229 + y * (3.0899424 + y * (1.2067492
+ y * (0.2659732 +
y *
(0.360768e-1 +
y *
0.45813e-2)))));
}
else
{
y = 3.75 / ax;
ans = (exp (ax) / sqrt (ax)) * (0.39894228 + y * (0.1328592e-1
+ y * (0.225319e-2 +
y *
(-0.157565e-2 +
y *
(0.916281e-2
+ y *
(-0.2057706e-1
+
y *
(0.2635537e-1
+
y *
(-0.1647633e-1
+ y *
0.392377e-2))))))));
}
return ans;
}
double
bessi1 (double x)
{
double ax, ans;
double y;
if ((ax = fabs (x)) < 3.75)
{
y = x / 3.75;
y *= y;
ans = ax * (0.5 + y * (0.87890594 + y * (0.51498869 + y * (0.15084934
+ y *
(0.2658733e-1
+
y *
(0.301532e-2
+
y *
0.32411e-3))))));
}
else
{
y = 3.75 / ax;
ans = 0.2282967e-1 + y * (-0.2895312e-1 + y * (0.1787654e-1
- y * 0.420059e-2));
ans = 0.39894228 + y * (-0.3988024e-1 + y * (-0.362018e-2
+ y * (0.163801e-2 +
y * (-0.1031555e-1 +
y * ans))));
ans *= (exp (ax) / sqrt (ax));
}
return x < 0.0 ? -ans : ans;
}
/********** GLOBAL FUNCTIONS ***********/
/* Here is how to add an error message.
* 1. Add an element to enum in utilities.h with prefix of "IMERR_XXX"
* 2. Add the corresponding error message string to simerrmsg.
* 3. Call function IM_err (IMERR_XXX, ...) where ... is like the way that
* printf function arguments are used.
*/
static const char *simerrmsg[] = {
/* 0 */ "",
/* 1 */ "cannot open a file for reading",
/* 2 */ " memory error ",
/* 3 */ "problem finding .ti file(s)",
/* 4 */ "cannot create file",
/* 5 */ "cannot open file for appending",
/* 6 */ " problem with opening or closing output file",
/* 7 */ "",
/* 8 */ "incompatibility on command line",
/* 9 */ "not enough information provided on command line",
/* 10 */ "problem with command line formatting ",
/* 11 */ "problem with heating terms in command line",
/* 12 */ "missing population string in input file",
/* 13 */ "some problem in the population tree string ",
/* 14 */ "",
/* 15 */ "problem w/ number of loci indicated in data file",
/* 16 */ "problem in specifying nested models for LLR tests",
/* 17 */ "",
/* 18 */ "mutation range priors to constraining - not able to set starting values",
/* 19 */ "product of mutation scalars not equal to 1",
/* 20 */ "",
/* 21 */ "Too many migration events found when storing edges",
/* 22 */ "to much migration called for in checkmig - reduce maximum value of migration parameter",
/* 23 */ "problem in calculating HPD interval",
/* 24 */ "",
/* 25 */ "error reading data, too many lines or line too long",
/* 26 */ "error in data",
/* 27 */ "",
/* 28 */ "problem reading mcf file",
/* 29 */ "cannot load mcf file, split times in file not compatiable with t prior",
/* 30 */ "",
/* 31 */ "",
/* 32 */ "",
/* 33 */ "problem with root ",
/* 34 */ "",
/* 35 */ "input file invalid ",
/* 36 */ "data not compatible with infinite sites model",
/* 37 */ "",
/* 38 */ "likelihoods do not add up for stepwise model",
/* 39 */ "",
/* 40 */ "",
/* 41 */ "error in lowergamma function",
/* 42 */ "error in uppergamma function",
/* 43 */ "error using LogDiff macro, difference is non-positive",
/* 44 */ "",
/* 45 */ "error calculating prior of t in multi_t_prior_func",
/* 46 */ "problem in the values specified in a file with parameter priors",
/* 47 */ "",
/* 48 */ "",
/* 49 */ "",
/* 50 */ "",
/* 51 */ "error in NR functions",
/* 52 */ "GSL error",
/* 53 */ "",
/* 54 */ "",
/* 55 */ "Potential bug",
/* 56 */ "Invalid input file: gene name",
/* 57 */ "Assignment Error",
/* 58 */ "",
/* 59 */ "",
/* 60 */ "problem calculating migration path probability when updating genealogy",
/* 61 */ "",
/* 62 */ ""
};
void
IM_err (int i, const char *fmt, ...)
{
va_list args;
va_start (args, fmt);
fprintf (stderr, "IMa2: %s - ", simerrmsg[i]);
vfprintf (stderr, fmt, args);
fprintf (stderr, "\n");
va_end (args);
exit (i);
}
void
IM_errloc (const char *loc, const char *fmt, ...)
{
va_list args;
va_start (args, fmt);
/* fprintf (stderr, "IMamp at %s: %s - ", loc, simerrmsg[i]); */
fprintf (stderr, "IMamp at %s - ", loc);
vfprintf (stderr, fmt, args);
fprintf (stderr, "\n");
va_end (args);
exit (1);
}
void
nrerror (const char error_text[])
/* Numerical Recipes standard error handler */
{
IM_err (IMERR_NUMERICALRECIPES, " error text: %s", error_text);
}
/* for a large value x, cosh[x] = sinh[x]
also (cosh[x] + sinh[x] = exp[x] so for a large value of x cosh[x] = sinh[x] = Exp[x]/2
so rather than return floating error, for the log of a cosh of a large number just return x - log[2] */
double
mylogcosh (double x)
{
if (x < 100)
return log (cosh (x));
else
return x - LOG2;
}
double
mylogsinh (double x)
{
if (x < 100)
return log (sinh (x));
else
return x - LOG2;
}
/***********************************/
/* RANDOM NUMBER RELATED FUNCTIONS */
/***********************************/
/* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
#ifdef SANITY_TEST
/* for testing only. read a random number from a file
* containing a known list of random numbers (in ascii)
* then convert the ascii to undsigned long and return.
*/
#define ranNumFile "randNums"
#define MAXLINE 120
unsigned long getKnownRandom(void)
{
static FILE *ranNum = NULL;
static int firstTime = 1;
unsigned long y;
char line[MAXLINE];
char comment = '#';
while ( 1 )
{
if ( firstTime )
{
firstTime = 0;
if (( ranNum = fopen(ranNumFile, "r")) == NULL )
assert (0);
if (( fgets(line, MAXLINE, ranNum)) == NULL)
assert (0);
/* skip the beginning comment lines started with # */
while( line[0] == comment )
{
fgets(line, MAXLINE, ranNum);
}
break;
}
else
if ( fgets(line, MAXLINE, ranNum) == NULL )
{
firstTime = 1;
fclose(ranNum);
}
else
break;
} /* end while */
y = strtoul(line, NULL, 0);
return y;
}
#endif /* SANITY_TEST */
/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
}
/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489UL); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
// hook for sanity testing with a known list of random numbers - janeen
#ifdef SANITY_TEST
y = getKnownRandom();
#endif /* SANITY_TEST */
return y;
}
/* generates a random number on (0,1)-real-interval */
double genrand_real3(void)
{
/* CR 110715.2
* converted 1/2^32 to a const instead of performing a calculation
* each time function is called.
* n * 1/2^32 = n * 2.32830643653869628906e-10
*/
return (((double)genrand_int32()) + 0.5) * 2.32830643653869628906e-10;
/* divided by 2^32 */
}
#undef N
#undef M
#undef MATRIX_A
#undef UPPER_MASK
#undef LOWER_MASK
void
setseeds (int seed)
{
init_genrand((unsigned long) seed);
/* try a new random number generator 9_19_10 don;t use z_rndu */
// z_rndu = 170 * (seed % 178) + 137;
iseed = malloc (sizeof (unsigned long));
*iseed = ULONG_MAX / 2 + (unsigned long) seed; // just set it so that iseed points to a large number - probably not necessary
}
void
unsetseeds ()
{
XFREE (iseed);
iseed = NULL;
return;
}
double
uniform ()
{
double r;
/* started using a new random number generator 9_19_10 */
/* see rand.c */
r = genrand_real3();
return r;
}
double
expo (double c)
{
return -log (uniform ()) / c;
}
__forceinlineVS int
randposint (int lessthanval) // actually should be rand_nonneg_int
{
return (int) floor (uniform () * lessthanval);
}
/* for binary random numbers - quick - based on Press et al irbit2() */
#define IB1 1
#define IB18 131072
#define MASK 19
__forceinlineVS int
bitran (void)
{
if (*iseed & IB18)
{
*iseed = ((*iseed ^ MASK) << 1) | IB1;
return 1;
}
else
{
*iseed <<= 1;
return 0;
}
}
#undef MASK
#undef IB18
#undef IB1
#define ONEOVERSQRT2PI 0.3989422803
double
normprob (double mean, double stdev, double val)
{
return ONEOVERSQRT2PI * exp (-SQR ((val - mean) / stdev) / 2) / stdev;
}
#undef ONEOVERSQRT2PI
double
normdev (double mean, double stdev)
{
static int iset = 0;
static double gset;
double fac, rsq, v1, v2;
double rescale;
if (iset == 0)
{
do
{
v1 = 2.0 * uniform () - 1.0;
v2 = 2.0 * uniform () - 1.0;
rsq = v1 * v1 + v2 * v2;
}
while (rsq >= 1.0 || rsq == 0.0);
fac = sqrt (-2.0 * log (rsq) / rsq);
gset = v1 * fac;
iset = 1;
rescale = ((v2 * fac * stdev) + mean);
return rescale;
}
else
{
iset = 0;
rescale = ((gset * stdev) + mean);
return rescale;
}
} /* normdev */
/* gets a poisson random variable. checked it out with simulations
if condition is 0, pick an even number
if condition is 1, pick an odd number
if condition is 2, pick any number other than 0 (because they must be different)
if condition is 3, pick any number other than 1
if condition is -1 pick any number
If param > minpp the normal distribution is used as an approximation
Also stuck in some stuff to deal with the case when condition is 1 and param << 1
*/
#define USENORMAL 100.0 // only for very large parameter values, because it is not a perfect approximation
#define MINPP 0.25
int
poisson (double param, int condition)
{
long double randnum, raised, rcheck;
int i;
int stop;
if (param < MINPP && condition == 1) /* i.e. need an odd number but the parameter is a small value */
{
randnum = uniform ();
rcheck = param / sinh (param);
if (randnum < rcheck) /* param / sinh(param) is prob of # being 1, given it must be odd */
i = 1;
else
{
rcheck = param * (6 + param * param) / (6 * sinh (param));
if (randnum < rcheck)
i = 3;
else
i = 5;
}
return (i);
}
/*if (param < 0.25 && condition == 2) a function for cases when need any number not zero, but the parameter is a small value */
/* seems to work - check file Poisson_low_value_parameter_simulation_check.nb */
if (param < MINPP && condition == 2)
{
raised = exp (-param);
rcheck = raised = param * raised / (1 - raised);
randnum = uniform ();
i = 1;
while (randnum > rcheck)
{
raised *= param / (i + 1);
rcheck += raised;
i++;
}
return (i);
}
do
{
if (param >= USENORMAL) // used normal approximation
{
i = IMAX (0, POSROUND (normdev (param, param)));
/* I checked this out extensively, and although the mean and variance of the normal and the poisson come to be
very close for parameter values of 10 or or, non-trivial differences persist for the tails of the distribution
even for very large parameter values*/
}
else
{
raised = exp (-param);
randnum = uniform ();
for (i = 0; randnum > raised; i++)
randnum *= uniform ();
}
switch (condition)
{
case -1:
stop = 1;
break;
case 0:
stop = !ODD (i);
break;
case 1:
stop = ODD (i);
break;
case 2:
stop = (i != 0);
break; //*
case 3:
stop = (i != 1);
break;
}
} while (!stop);
if (i > ADDMIGMAX) /* trap numbers that get too large to handle (and that don't make sense) */
{
if (condition == 1)
i = ADDMIGMAX - 1;
else
i = ADDMIGMAX;
}
return (i);
} /* pickpoisson */
#undef USENORMAL
#undef MINPP
int
geometric (double p)
/* returns a geometrically distributed random integer variable >= 0 */
/* this distribution is given by prob(k) = p*(1-p)^(k-1) where k = 1,2,... which has a mode of 1 and an expectation of 1/p */
/* it is a bit different from prob(k) = p*(1-p)^k where k = 0,1, 2... , which has a mode of 0 and an expectation of (1-p)/p */
/* the variance of these two different versions is the same, i.e. (1-p)/p^2 */
/* checked this in various ways - seems ok */
{
return (int) ceil (log (uniform ()) / log (1.0 - p));
}
/***********************************/
/* SORTING FUNCTIONS */
/***********************************/
/* heap sort is slightly faster than shell sort */
void
hpsortmig (struct migstruct *lptr, int n)
{
unsigned long i, ir, j, l;
double t;
if (n < 2)
return;
l = (n >> 1) + 1;
ir = n;
for (;;)
{
if (l > 1)
{
t = (lptr + --l)->mt;
}
else
{
t = (lptr + ir)->mt;
(lptr + ir)->mt = (lptr + 1)->mt;
if (--ir == 1)
{
(lptr + 1)->mt = t;
break;
}
}
i = l;
j = l + l;
while (j <= ir)
{
if (j < ir && (lptr + j)->mt < (lptr + (j + 1))->mt)
j++;
if (t < (lptr + j)->mt)
{
(lptr + i)->mt = (lptr + j)->mt;
i = j;
j <<= 1;
}
else
{
j = ir + 1;
}
}
(lptr + i)->mt = t;
}
} /*hpsortmig */
void
shellhist (struct hlists *hptr, int length)
{
double aln = 1.442695022, tiny = 1.0e-5;
struct hlists h;
static int nn, m, lognb2, i, j, k, l;
lognb2 = (int) floor (log ((double) length) * aln + tiny);
m = length;
for (nn = 1; nn <= lognb2; nn++)
{
m = m / 2;
k = length - m;
for (j = 0; j <= k - 1; j++)
{
i = j;
reloop:l = i + m;
if (((hptr + l)->p < (hptr + i)->p)
|| (((hptr + l)->p == (hptr + i)->p)
&& (((hptr + l)->v < (hptr + i)->v))))
{
h = *(hptr + i);
*(hptr + i) = *(hptr + l);
*(hptr + l) = h;
i = i - m;
if (i >= 0)
goto reloop;
}
}
}
} /* shellhist */
/* quicksort of an index of locations */
#define SWAP(a,b) itemp=(a);(a)=(b);(b)=itemp
#define M 7
#define NSTACK 50
void
indexx (unsigned long n, struct gtreeevent *arr, unsigned long *indx)
{
unsigned long i, indxt, ir = n, itemp, j, k, l = 1;
int jstack = 0, *istack;
double a;
istack = ivector (1, NSTACK);
for (j = 1; j <= n; j++)
indx[j] = j;
for (;;)
{
if (ir - l < M)
{
for (j = l + 1; j <= ir; j++)
{
indxt = indx[j];
a = arr[indxt].time;
for (i = j - 1; i >= l; i--)
{
if (arr[indx[i]].time <= a)
break;
indx[i + 1] = indx[i];
}
indx[i + 1] = indxt;
}
if (jstack == 0)
break;
ir = istack[jstack--];
l = istack[jstack--];
}
else
{
k = (l + ir) >> 1;
SWAP (indx[k], indx[l + 1]);
if (arr[indx[l]].time > arr[indx[ir]].time)
{
SWAP (indx[l], indx[ir]);
}
if (arr[indx[l + 1]].time > arr[indx[ir]].time)
{
SWAP (indx[l + 1], indx[ir]);
}
if (arr[indx[l]].time > arr[indx[l + 1]].time)
{
SWAP (indx[l], indx[l + 1]);
}
i = l + 1;
j = ir;
indxt = indx[l + 1];
a = arr[indxt].time;
for (;;)
{
do
i++;
while (arr[indx[i]].time < a);
do
j--;
while (arr[indx[j]].time > a);
if (j < i)
break;
SWAP (indx[i], indx[j]);
}
indx[l + 1] = indx[j];
indx[j] = indxt;
jstack += 2;
if (jstack > NSTACK)
nrerror ("NSTACK too small in indexx.");
if (ir - i + 1 >= j - l)
{
istack[jstack] = ir;
istack[jstack - 1] = i;
ir = j - 1;
}
else
{
istack[jstack] = j - 1;
istack[jstack - 1] = l;
l = i;
}
}
}
free_ivector (istack, 1/*, NSTACK*/);
}
#undef SWAP
#define SWAP(a,b) temp=(a);(a)=(b);(b)=temp
#undef SWAP
#undef M
#undef NSTACK
#undef SWAP
/* (C) Copr. 1986-92 Numerical Recipes Software '$&'3$. */
#define ITMAX 1000
#define EPS 3.0e-7
#define FPMIN 1.0e-30
void
gcf (double *gammcf, double a, double x, double *gln)
{
int i;
double an, b, c, d, del, h;
*gln = logfact[(int) a - 1];
b = x + 1.0 - a;
c = 1.0 / FPMIN;
d = 1.0 / b;
h = d;
for (i = 1; i <= ITMAX; i++)
{
an = -i * (i - a);
b += 2.0;
d = an * d + b;
if (fabs (d) < FPMIN)
d = FPMIN;
c = b + an / c;
if (fabs (c) < FPMIN)
c = FPMIN;
d = 1.0 / d;
del = d * c;
h *= del;
if (fabs (del - 1.0) < EPS)
break;
}
if (i > ITMAX)
IM_err (IMERR_LOWERGAMMA, " too many iterations within gcf()");
*gammcf = exp (-x + a * log (x) - (*gln)) * h;
}
// gcflog is the same as gcf but returns the logarithm of gammcf
// saves a little time and stops some underflows
void
gcflog (double *gammcflog, double a, double x, double *gln)
{
int i;
double an, b, c, d, del, h;
*gln = logfact[(int) a - 1];
b = x + 1.0 - a;
c = 1.0 / FPMIN;
d = 1.0 / b;
h = d;
for (i = 1; i <= ITMAX; i++)
{
an = -i * (i - a);
b += 2.0;
d = an * d + b;
if (fabs (d) < FPMIN)
d = FPMIN;
c = b + an / c;
if (fabs (c) < FPMIN)
c = FPMIN;
d = 1.0 / d;
del = d * c;
h *= del;
if (fabs (del - 1.0) < EPS)
break;
}
if (i > ITMAX)
IM_err (IMERR_UPPERGAMMA, " too many iterations within gcflog()");
//*gammcf=exp(-x+a*log(x)-(*gln))*h;
*gammcflog = (-x + a * log (x) - (*gln)) + log (h);
} //gcflog
#undef FPMIN
/* (C) Copr. 1986-92 Numerical Recipes Software '$&'3$. */
void
gser (double *gamser, int a, double x, double *gln)
{
int n;
double sum, del, ap;
*gln = logfact[a - 1];
if (x <= 0.0)
{
if (x < 0.0)
IM_err (IMERR_UPPERGAMMA,
" gser() called with negative x value, x: %lf ", x);
*gamser = 0.0;
return;
}
else
{
ap = a;
del = sum = 1.0 / a;
for (n = 1; n <= ITMAX; n++)
{
++ap;
del *= x / ap;
sum += del;
if (fabs (del) < fabs (sum) * EPS)
{
*gamser = sum * exp (-x + a * log (x) - (*gln));
return;
}
}
IM_err (IMERR_UPPERGAMMA, " too many iterations within gser() ");
return;
}
}
// gserlog is the same as gser but returns the logarith of gamser
// saves a little time and stops some underflows
void
gserlog (double *gamserlog, int a, double x, double *gln)
{
int n;
double sum, del, ap;
*gln = logfact[a - 1];
if (x <= 0.0)
{
if (x < 0.0)
IM_err (IMERR_LOWERGAMMA,
" function gserlog() called from lowergamma() with negative x value, x: %lf",
x);
*gamserlog = 0.0;
return;
}
else
{
ap = a;
del = sum = 1.0 / a;
for (n = 1; n <= ITMAX; n++)
{
++ap;
del *= x / ap;
sum += del;
if (fabs (del) < fabs (sum) * EPS)
{
//*gamser=sum*exp(-x+a*log(x)-(*gln));
*gamserlog = log (sum) + (-x + a * log (x) - (*gln));
return;
}
}
IM_err (IMERR_LOWERGAMMA, " too many iterations within gserlog() ");
return;
}
}
#undef ITMAX
/* (C) Copr. 1986-92 Numerical Recipes Software '$&'3$. */
#define MAXIT 100
#define EULER 0.5772156649
#define FPMIN 1.0e-30
double
expint (int n, double x, int *islog)
{
int i, ii, nm1;
double a, b, c, d, del, fact, h, psi, ans;
*islog = 0;
nm1 = n - 1;
if (n < 0 || x < 0.0 || (x == 0.0 && (n == 0 || n == 1)))
{
IM_err (IMERR_UPPERGAMMA,
" expint() called from uppergamma() with bad value(s). n %d x %lf",
n, x);
}
else
{
if (n == 0)
{
ans = exp (-x) / x;
}
else
{
if (x == 0.0)
{
ans = 1.0 / nm1;
}
else
{
if (x > 1.0)
{
b = x + n;
c = 1.0 / FPMIN;
d = 1.0 / b;
h = d;
for (i = 1; i <= MAXIT; i++)
{
a = -i * (nm1 + i);
b += 2.0;
d = 1.0 / (a * d + b);