Change license from GPLv2+ to GPLv3+.
[pspp-builds.git] / src / math / sort.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include "sort.h"
20
21 #include <stdio.h>
22
23 #include <data/case-ordering.h>
24 #include <data/case.h>
25 #include <data/casereader.h>
26 #include <data/casewriter.h>
27 #include <data/casewriter-provider.h>
28 #include <data/settings.h>
29 #include <libpspp/alloc.h>
30 #include <libpspp/array.h>
31 #include <libpspp/assertion.h>
32 #include <math/merge.h>
33
34 #include "gettext.h"
35 #define _(msgid) gettext (msgid)
36
37 /* These should only be changed for testing purposes. */
38 int min_buffers = 64;
39 int max_buffers = INT_MAX;
40
41 struct sort_writer
42   {
43     struct case_ordering *ordering;
44     struct merge *merge;
45     struct pqueue *pqueue;
46
47     struct casewriter *run;
48     casenumber run_id;
49     struct ccase run_end;
50   };
51
52 static struct casewriter_class sort_casewriter_class;
53
54 static struct pqueue *pqueue_create (const struct case_ordering *);
55 static void pqueue_destroy (struct pqueue *);
56 static bool pqueue_is_full (const struct pqueue *);
57 static bool pqueue_is_empty (const struct pqueue *);
58 static void pqueue_push (struct pqueue *, struct ccase *, casenumber);
59 static void pqueue_pop (struct pqueue *, struct ccase *, casenumber *);
60
61 static void output_record (struct sort_writer *);
62
63 struct casewriter *
64 sort_create_writer (struct case_ordering *ordering)
65 {
66   struct sort_writer *sort;
67
68   sort = xmalloc (sizeof *sort);
69   sort->ordering = case_ordering_clone (ordering);
70   sort->merge = merge_create (ordering);
71   sort->pqueue = pqueue_create (ordering);
72   sort->run = NULL;
73   sort->run_id = 0;
74   case_nullify (&sort->run_end);
75
76   case_ordering_destroy (ordering);
77
78   return casewriter_create (&sort_casewriter_class, sort);
79 }
80
81 static void
82 sort_casewriter_write (struct casewriter *writer UNUSED, void *sort_,
83                        struct ccase *c)
84 {
85   struct sort_writer *sort = sort_;
86   bool next_run;
87
88   if (pqueue_is_full (sort->pqueue))
89     output_record (sort);
90
91   next_run = (case_is_null (&sort->run_end)
92               || case_ordering_compare_cases (c, &sort->run_end,
93                                               sort->ordering) < 0);
94   pqueue_push (sort->pqueue, c, sort->run_id + (next_run ? 1 : 0));
95 }
96
97 static void
98 sort_casewriter_destroy (struct casewriter *writer UNUSED, void *sort_)
99 {
100   struct sort_writer *sort = sort_;
101
102   case_ordering_destroy (sort->ordering);
103   merge_destroy (sort->merge);
104   pqueue_destroy (sort->pqueue);
105   casewriter_destroy (sort->run);
106   case_destroy (&sort->run_end);
107   free (sort);
108 }
109
110 static struct casereader *
111 sort_casewriter_convert_to_reader (struct casewriter *writer, void *sort_)
112 {
113   struct sort_writer *sort = sort_;
114   struct casereader *output;
115
116   if (sort->run == NULL && sort->run_id == 0)
117     {
118       /* In-core sort. */
119       sort->run = mem_writer_create (case_ordering_get_value_cnt (
120                                        sort->ordering));
121       sort->run_id = 1;
122     }
123   while (!pqueue_is_empty (sort->pqueue))
124     output_record (sort);
125
126   merge_append (sort->merge, casewriter_make_reader (sort->run));
127   sort->run = NULL;
128
129   output = merge_make_reader (sort->merge);
130   sort_casewriter_destroy (writer, sort);
131   return output;
132 }
133
134 static void
135 output_record (struct sort_writer *sort)
136 {
137   struct ccase min_case;
138   casenumber min_run_id;
139
140   pqueue_pop (sort->pqueue, &min_case, &min_run_id);
141 #if 0
142   printf ("\toutput: %f to run %d\n", case_num_idx (&min_case, 0), min_run_id);
143 #endif
144
145   if (sort->run_id != min_run_id && sort->run != NULL)
146     {
147       merge_append (sort->merge, casewriter_make_reader (sort->run));
148       sort->run = NULL;
149     }
150   if (sort->run == NULL)
151     {
152       sort->run = tmpfile_writer_create (case_ordering_get_value_cnt (
153                                            sort->ordering));
154       sort->run_id = min_run_id;
155     }
156
157   case_destroy (&sort->run_end);
158   case_clone (&sort->run_end, &min_case);
159
160   casewriter_write (sort->run, &min_case);
161 }
162
163 static struct casewriter_class sort_casewriter_class =
164   {
165     sort_casewriter_write,
166     sort_casewriter_destroy,
167     sort_casewriter_convert_to_reader,
168   };
169 \f
170 /* Reads all the cases from INPUT.  Sorts the cases according to
171    ORDERING.  Returns the sorted cases in a new casereader, or a
172    null pointer if an I/O error occurs.  Both INPUT and ORDERING
173    are destroyed upon return, regardless of success. */
174 struct casereader *
175 sort_execute (struct casereader *input, struct case_ordering *ordering)
176 {
177   struct casewriter *output = sort_create_writer (ordering);
178   casereader_transfer (input, output);
179   return casewriter_make_reader (output);
180 }
181 \f
182 struct pqueue
183   {
184     struct case_ordering *ordering;
185     struct pqueue_record *records;
186     size_t record_cnt;
187     size_t record_cap;
188     casenumber idx;
189   };
190
191 struct pqueue_record
192   {
193     casenumber id;
194     struct ccase c;
195     casenumber idx;
196   };
197
198 static int compare_pqueue_records_minheap (const void *a, const void *b,
199                                            const void *pq_);
200
201 static struct pqueue *
202 pqueue_create (const struct case_ordering *ordering)
203 {
204   struct pqueue *pq;
205
206   pq = xmalloc (sizeof *pq);
207   pq->ordering = case_ordering_clone (ordering);
208   pq->record_cap
209     = get_workspace_cases (case_ordering_get_value_cnt (ordering));
210   if (pq->record_cap > max_buffers)
211     pq->record_cap = max_buffers;
212   else if (pq->record_cap < min_buffers)
213     pq->record_cap = min_buffers;
214   pq->record_cnt = 0;
215   pq->records = xnmalloc (pq->record_cap, sizeof *pq->records);
216   pq->idx = 0;
217
218   return pq;
219 }
220
221 static void
222 pqueue_destroy (struct pqueue *pq)
223 {
224   if (pq != NULL)
225     {
226       while (!pqueue_is_empty (pq))
227         {
228           struct ccase c;
229           casenumber id;
230           pqueue_pop (pq, &c, &id);
231           case_destroy (&c);
232         }
233       case_ordering_destroy (pq->ordering);
234       free (pq->records);
235       free (pq);
236     }
237 }
238
239 static bool
240 pqueue_is_full (const struct pqueue *pq)
241 {
242   return pq->record_cnt >= pq->record_cap;
243 }
244
245 static bool
246 pqueue_is_empty (const struct pqueue *pq)
247 {
248   return pq->record_cnt == 0;
249 }
250
251 static void
252 pqueue_push (struct pqueue *pq, struct ccase *c, casenumber id)
253 {
254   struct pqueue_record *r;
255
256   assert (!pqueue_is_full (pq));
257
258   r = &pq->records[pq->record_cnt++];
259   r->id = id;
260   case_move (&r->c, c);
261   r->idx = pq->idx++;
262
263   push_heap (pq->records, pq->record_cnt, sizeof *pq->records,
264              compare_pqueue_records_minheap, pq);
265 }
266
267 static void
268 pqueue_pop (struct pqueue *pq, struct ccase *c, casenumber *id)
269 {
270   struct pqueue_record *r;
271
272   assert (!pqueue_is_empty (pq));
273
274   pop_heap (pq->records, pq->record_cnt--, sizeof *pq->records,
275             compare_pqueue_records_minheap, pq);
276
277   r = &pq->records[pq->record_cnt];
278   *id = r->id;
279   case_move (c, &r->c);
280 }
281
282 /* Compares record-run tuples A and B on id, then on case data,
283    then on insertion order, in descending order. */
284 static int
285 compare_pqueue_records_minheap (const void *a_, const void *b_,
286                                 const void *pq_)
287 {
288   const struct pqueue_record *a = a_;
289   const struct pqueue_record *b = b_;
290   const struct pqueue *pq = pq_;
291   int result = a->id < b->id ? -1 : a->id > b->id;
292   if (result == 0)
293     result = case_ordering_compare_cases (&a->c, &b->c, pq->ordering);
294   if (result == 0)
295     result = a->idx < b->idx ? -1 : a->idx > b->idx;
296   return -result;
297 }