1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2008, 2010, 2011 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "language/expressions/helpers.h"
21 #include <gsl/gsl_roots.h>
22 #include <gsl/gsl_sf.h>
24 #include "language/expressions/private.h"
25 #include "libpspp/assertion.h"
26 #include "libpspp/pool.h"
28 const struct substring empty_string = {NULL, 0};
31 expr_ymd_to_ofs (double year, double month, double day)
39 if (y != year || m != month || d != day)
41 msg (SE, _("One of the arguments to a DATE function is not an integer. "
42 "The result will be system-missing."));
46 ofs = calendar_gregorian_to_offset (y, m, d, &error);
49 msg (SE, "%s", error);
56 expr_ymd_to_date (double year, double month, double day)
58 double ofs = expr_ymd_to_ofs (year, month, day);
59 return ofs != SYSMIS ? ofs * DAY_S : SYSMIS;
63 expr_wkyr_to_date (double week, double year)
69 msg (SE, _("The week argument to DATE.WKYR is not an integer. "
70 "The result will be system-missing."));
73 else if (w < 1 || w > 53)
75 msg (SE, _("The week argument to DATE.WKYR is outside the acceptable "
77 "The result will be system-missing."));
82 double yr_1_1 = expr_ymd_to_ofs (year, 1, 1);
84 return DAY_S * (yr_1_1 + WEEK_DAY * (w - 1));
91 expr_yrday_to_date (double year, double yday)
97 msg (SE, _("The day argument to DATE.YRDAY is not an integer. "
98 "The result will be system-missing."));
101 else if (yd < 1 || yd > 366)
103 msg (SE, _("The day argument to DATE.YRDAY is outside the acceptable "
104 "range of 1 to 366. "
105 "The result will be system-missing."));
110 double yr_1_1 = expr_ymd_to_ofs (year, 1, 1);
111 if (yr_1_1 != SYSMIS)
112 return DAY_S * (yr_1_1 + yd - 1.);
119 expr_yrmoda (double year, double month, double day)
121 if (year >= 0 && year <= 99)
123 else if (year != (int) year && year > 47516)
125 msg (SE, _("The year argument to YRMODA is greater than 47516. "
126 "The result will be system-missing."));
130 return expr_ymd_to_ofs (year, month, day);
146 /* Stores in *UNIT the unit whose name is NAME.
148 static enum date_unit
149 recognize_unit (struct substring name, enum date_unit *unit)
154 const struct substring name;
156 static const struct unit_name unit_names[] =
158 { DATE_YEARS, SS_LITERAL_INITIALIZER ("years") },
159 { DATE_QUARTERS, SS_LITERAL_INITIALIZER ("quarters") },
160 { DATE_MONTHS, SS_LITERAL_INITIALIZER ("months") },
161 { DATE_WEEKS, SS_LITERAL_INITIALIZER ("weeks") },
162 { DATE_DAYS, SS_LITERAL_INITIALIZER ("days") },
163 { DATE_HOURS, SS_LITERAL_INITIALIZER ("hours") },
164 { DATE_MINUTES, SS_LITERAL_INITIALIZER ("minutes") },
165 { DATE_SECONDS, SS_LITERAL_INITIALIZER ("seconds") },
167 const int unit_name_cnt = sizeof unit_names / sizeof *unit_names;
169 const struct unit_name *un;
171 for (un = unit_names; un < &unit_names[unit_name_cnt]; un++)
172 if (ss_equals_case (un->name, name))
178 /* TRANSLATORS: Don't translate the the actual unit names `weeks', `days' etc
179 They must remain in their original English. */
180 msg (SE, _("Unrecognized date unit `%.*s'. "
181 "Valid date units are `years', `quarters', `months', "
182 "`weeks', `days', `hours', `minutes', and `seconds'."),
183 (int) ss_length (name), ss_data (name));
187 /* Returns the number of whole years from DATE1 to DATE2,
188 where a year is defined as the same or later month, day, and
191 year_diff (double date1, double date2)
197 assert (date2 >= date1);
198 calendar_offset_to_gregorian (date1 / DAY_S, &y1, &m1, &d1, &yd1);
199 calendar_offset_to_gregorian (date2 / DAY_S, &y2, &m2, &d2, &yd2);
204 int yd1 = 32 * m1 + d1;
205 int yd2 = 32 * m2 + d2;
207 || (yd2 == yd1 && fmod (date2, DAY_S) < fmod (date1, DAY_S)))
213 /* Returns the number of whole months from DATE1 to DATE2,
214 where a month is defined as the same or later day and time of
217 month_diff (double date1, double date2)
223 assert (date2 >= date1);
224 calendar_offset_to_gregorian (date1 / DAY_S, &y1, &m1, &d1, &yd1);
225 calendar_offset_to_gregorian (date2 / DAY_S, &y2, &m2, &d2, &yd2);
227 diff = ((y2 * 12) + m2) - ((y1 * 12) + m1);
230 || (d2 == d1 && fmod (date2, DAY_S) < fmod (date1, DAY_S))))
235 /* Returns the number of whole quarter from DATE1 to DATE2,
236 where a quarter is defined as three months. */
238 quarter_diff (double date1, double date2)
240 return month_diff (date1, date2) / 3;
243 /* Returns the number of seconds in the given UNIT. */
245 date_unit_duration (enum date_unit unit)
269 /* Returns the span from DATE1 to DATE2 in terms of UNIT_NAME. */
271 expr_date_difference (double date1, double date2, struct substring unit_name)
275 if (!recognize_unit (unit_name, &unit))
281 return (date2 >= date1
282 ? year_diff (date1, date2)
283 : -year_diff (date2, date1));
286 return (date2 >= date1
287 ? quarter_diff (date1, date2)
288 : -quarter_diff (date2, date1));
291 return (date2 >= date1
292 ? month_diff (date1, date2)
293 : -month_diff (date2, date1));
300 return trunc ((date2 - date1) / date_unit_duration (unit));
306 /* How to deal with days out of range for a given month. */
309 SUM_ROLLOVER, /* Roll them over to the next month. */
310 SUM_CLOSEST /* Use the last day of the month. */
313 /* Stores in *METHOD the method whose name is NAME.
316 recognize_method (struct substring method_name, enum date_sum_method *method)
318 if (ss_equals_case (method_name, ss_cstr ("closest")))
320 *method = SUM_CLOSEST;
323 else if (ss_equals_case (method_name, ss_cstr ("rollover")))
325 *method = SUM_ROLLOVER;
330 msg (SE, _("Invalid DATESUM method. "
331 "Valid choices are `closest' and `rollover'."));
336 /* Returns DATE advanced by the given number of MONTHS, with
337 day-of-month overflow resolved using METHOD. */
339 add_months (double date, int months, enum date_sum_method method)
345 calendar_offset_to_gregorian (date / DAY_S, &y, &m, &d, &yd);
358 assert (m >= 1 && m <= 12);
360 if (method == SUM_CLOSEST && d > calendar_days_in_month (y, m))
361 d = calendar_days_in_month (y, m);
363 output = calendar_gregorian_to_offset (y, m, d, &error);
364 if (output != SYSMIS)
365 output = (output * DAY_S) + fmod (date, DAY_S);
368 msg (SE, "%s", error);
374 /* Returns DATE advanced by the given QUANTITY of units given in
375 UNIT_NAME, with day-of-month overflow resolved using
378 expr_date_sum (double date, double quantity, struct substring unit_name,
379 struct substring method_name)
382 enum date_sum_method method;
384 if (!recognize_unit (unit_name, &unit)
385 || !recognize_method (method_name, &method))
391 return add_months (date, trunc (quantity) * 12, method);
394 return add_months (date, trunc (quantity) * 3, method);
397 return add_months (date, trunc (quantity), method);
404 return date + quantity * date_unit_duration (unit);
411 compare_string_3way (const struct substring *a, const struct substring *b)
415 for (i = 0; i < a->length && i < b->length; i++)
416 if (a->string[i] != b->string[i])
417 return a->string[i] < b->string[i] ? -1 : 1;
418 for (; i < a->length; i++)
419 if (a->string[i] != ' ')
421 for (; i < b->length; i++)
422 if (b->string[i] != ' ')
428 count_valid (double *d, size_t d_cnt)
434 for (i = 0; i < d_cnt; i++)
435 valid_cnt += is_valid (d[i]);
440 alloc_string (struct expression *e, size_t length)
444 s.string = pool_alloc (e->eval_pool, length);
449 copy_string (struct expression *e, const char *old, size_t length)
451 struct substring s = alloc_string (e, length);
452 memcpy (s.string, old, length);
456 /* Returns the noncentral beta cumulative distribution function
457 value for the given arguments.
459 FIXME: The accuracy of this function is not entirely
460 satisfactory. We only match the example values given in AS
461 310 to the first 5 significant digits. */
463 ncdf_beta (double x, double a, double b, double lambda)
467 if (x <= 0. || x >= 1. || a <= 0. || b <= 0. || lambda <= 0.)
473 /* Algorithm AS 226. */
474 double x0, a0, beta, temp, gx, q, ax, sumq, sum;
475 double err_max = 2 * DBL_EPSILON;
480 x0 = floor (c - 5.0 * sqrt (c));
484 beta = (gsl_sf_lngamma (a0)
486 - gsl_sf_lngamma (a0 + b));
487 temp = gsl_sf_beta_inc (a0, b, x);
488 gx = exp (a0 * log (x) + b * log (1. - x) - beta - log (a0));
490 q = exp (-c + x0 * log (c)) - gsl_sf_lngamma (x0 + 1.);
502 gx = x * (a + b + iter - 1.) * gx / (a + iter);
508 err_bound = (temp - gx) * sumq;
510 while (iter < iter_max && err_bound > err_max);
516 /* Algorithm AS 310. */
518 int iter, iter_lower, iter_upper, iter1, iter2, j;
519 double t, q, r, psum, beta, s1, gx, fx, temp, ftemp, t0, s0, sum, s;
521 double err_max = 2 * DBL_EPSILON;
527 iter_lower = m - 5. * m_sqrt;
528 iter_upper = m + 5. * m_sqrt;
530 t = -c + m * log (c) - gsl_sf_lngamma (m + 1.);
534 beta = (gsl_sf_lngamma (a + m)
536 - gsl_sf_lngamma (a + m + b));
537 s1 = (a + m) * log (x) + b * log (1. - x) - log (a + m) - beta;
539 ftemp = temp = gsl_sf_beta_inc (a + m, b, x);
544 while (iter1 >= iter_lower && q >= err_max)
548 gx = (a + iter1) / (x * (a + b + iter1 - 1.)) * gx;
555 t0 = (gsl_sf_lngamma (a + b)
556 - gsl_sf_lngamma (a + 1.)
557 - gsl_sf_lngamma (b));
558 s0 = a * log (x) + b * log (1. - x);
561 for (j = 0; j < iter1; j++)
564 s += exp (t0 + s0 + j * log (x));
565 t1 = log (a + b + j) - log (a + 1. + j) + t0;
569 err_bound = (1. - gsl_sf_gamma_inc_P (iter1, c)) * (temp + s);
576 double ebd = err_bound + (1. - psum) * temp;
577 if (ebd < err_max || iter >= iter_upper)
585 gx = x * (a + b + iter2 - 1.) / (a + iter2) * gx;
594 cdf_bvnor (double x0, double x1, double r)
596 double z = pow2 (x0) - 2. * r * x0 * x1 + pow2 (x1);
597 return exp (-z / (2. * (1 - r * r))) * (2. * M_PI * sqrt (1 - r * r));
601 idf_fdist (double P, double df1, double df2)
603 double temp = gsl_cdf_beta_Pinv (P, df1 / 2, df2 / 2);
604 return temp * df2 / ((1. - temp) * df1);
608 * Mathlib : A C Library of Special Functions
609 * Copyright (C) 1998 Ross Ihaka
610 * Copyright (C) 2000 The R Development Core Team
612 * This program is free software; you can redistribute it and/or
614 * it under the terms of the GNU General Public License as
616 * the Free Software Foundation; either version 2 of the
618 * (at your option) any later version.
620 * This program is distributed in the hope that it will be
622 * but WITHOUT ANY WARRANTY; without even the implied warranty
624 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
625 * GNU General Public License for more details.
627 * You should have received a copy of the GNU General Public
629 * along with this program; if not, write to the Free Software
630 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
634 /* Returns the density of the noncentral beta distribution with
635 noncentrality parameter LAMBDA. */
637 npdf_beta (double x, double a, double b, double lambda)
639 if (lambda < 0. || a <= 0. || b <= 0.)
641 else if (lambda == 0.)
642 return gsl_ran_beta_pdf (x, a, b);
645 double max_error = 2 * DBL_EPSILON;
647 double term = gsl_ran_beta_pdf (x, a, b);
648 double lambda2 = 0.5 * lambda;
649 double weight = exp (-lambda2);
650 double sum = weight * term;
651 double psum = weight;
653 for (k = 1; k <= max_iter && 1 - psum < max_error; k++) {
654 weight *= lambda2 / k;
655 term *= x * (a + b) / a;
656 sum += weight * term;