67aa32d29048fffbb5e7b3c03b371b8db9c88a62
[pspp-builds.git] / src / math / sort.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009 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.h>
24 #include <data/casereader.h>
25 #include <data/casewriter.h>
26 #include <data/casewriter-provider.h>
27 #include <data/settings.h>
28 #include <data/subcase.h>
29 #include <libpspp/array.h>
30 #include <libpspp/assertion.h>
31 #include <math/merge.h>
32
33 #include "xalloc.h"
34
35 #include "gettext.h"
36 #define _(msgid) gettext (msgid)
37
38 /* These should only be changed for testing purposes. */
39 int min_buffers = 64;
40 int max_buffers = INT_MAX;
41
42 struct sort_writer
43   {
44     size_t value_cnt;
45     struct subcase ordering;
46     struct merge *merge;
47     struct pqueue *pqueue;
48
49     struct casewriter *run;
50     casenumber run_id;
51     struct ccase *run_end;
52   };
53
54 static struct casewriter_class sort_casewriter_class;
55
56 static struct pqueue *pqueue_create (const struct subcase *, size_t);
57 static void pqueue_destroy (struct pqueue *);
58 static bool pqueue_is_full (const struct pqueue *);
59 static bool pqueue_is_empty (const struct pqueue *);
60 static void pqueue_push (struct pqueue *, struct ccase *, casenumber);
61 static struct ccase *pqueue_pop (struct pqueue *, casenumber *);
62
63 static void output_record (struct sort_writer *);
64
65 struct casewriter *
66 sort_create_writer (const struct subcase *ordering, size_t value_cnt)
67 {
68   struct sort_writer *sort;
69
70   sort = xmalloc (sizeof *sort);
71   sort->value_cnt = value_cnt;
72   subcase_clone (&sort->ordering, ordering);
73   sort->merge = merge_create (ordering, value_cnt);
74   sort->pqueue = pqueue_create (ordering, value_cnt);
75   sort->run = NULL;
76   sort->run_id = 0;
77   sort->run_end = NULL;
78
79   return casewriter_create (value_cnt, &sort_casewriter_class, sort);
80 }
81
82 static void
83 sort_casewriter_write (struct casewriter *writer UNUSED, void *sort_,
84                        struct ccase *c)
85 {
86   struct sort_writer *sort = sort_;
87   bool next_run;
88
89   if (pqueue_is_full (sort->pqueue))
90     output_record (sort);
91
92   next_run = (sort->run_end == NULL
93               || subcase_compare_3way (&sort->ordering, c,
94                                        &sort->ordering, sort->run_end) < 0);
95   pqueue_push (sort->pqueue, c, sort->run_id + (next_run ? 1 : 0));
96 }
97
98 static void
99 sort_casewriter_destroy (struct casewriter *writer UNUSED, void *sort_)
100 {
101   struct sort_writer *sort = sort_;
102
103   subcase_destroy (&sort->ordering);
104   merge_destroy (sort->merge);
105   pqueue_destroy (sort->pqueue);
106   casewriter_destroy (sort->run);
107   case_unref (sort->run_end);
108   free (sort);
109 }
110
111 static struct casereader *
112 sort_casewriter_convert_to_reader (struct casewriter *writer, void *sort_)
113 {
114   struct sort_writer *sort = sort_;
115   struct casereader *output;
116
117   if (sort->run == NULL && sort->run_id == 0)
118     {
119       /* In-core sort. */
120       sort->run = mem_writer_create (casewriter_get_value_cnt (writer));
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   min_case = pqueue_pop (sort->pqueue, &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 (sort->value_cnt);
153       sort->run_id = min_run_id;
154     }
155
156   case_unref (sort->run_end);
157   sort->run_end = case_ref (min_case);
158   casewriter_write (sort->run, min_case);
159 }
160
161 static struct casewriter_class sort_casewriter_class =
162   {
163     sort_casewriter_write,
164     sort_casewriter_destroy,
165     sort_casewriter_convert_to_reader,
166   };
167 \f
168 /* Reads all the cases from INPUT.  Sorts the cases according to
169    ORDERING.  Returns the sorted cases in a new casereader. */
170 struct casereader *
171 sort_execute (struct casereader *input, const struct subcase *ordering)
172 {
173   struct casewriter *output =
174     sort_create_writer (ordering, casereader_get_value_cnt (input));
175   casereader_transfer (input, output);
176   return casewriter_make_reader (output);
177 }
178
179 /* Reads all the cases from INPUT.  Sorts the cases in ascending
180    order according to VARIABLE.  Returns the sorted cases in a
181    new casereader. */
182 struct casereader *
183 sort_execute_1var (struct casereader *input, const struct variable *var)
184 {
185   struct subcase sc;
186   struct casereader *reader;
187
188   subcase_init_var (&sc, var, SC_ASCEND);
189   reader = sort_execute (input, &sc);
190   subcase_destroy (&sc);
191   return reader;
192 }
193 \f
194 struct pqueue
195   {
196     struct subcase ordering;
197     struct pqueue_record *records;
198     size_t record_cnt;
199     size_t record_cap;
200     casenumber idx;
201   };
202
203 struct pqueue_record
204   {
205     casenumber id;
206     struct ccase *c;
207     casenumber idx;
208   };
209
210 static int compare_pqueue_records_minheap (const void *a, const void *b,
211                                            const void *pq_);
212
213 static struct pqueue *
214 pqueue_create (const struct subcase *ordering, size_t value_cnt)
215 {
216   struct pqueue *pq;
217
218   pq = xmalloc (sizeof *pq);
219   subcase_clone (&pq->ordering, ordering);
220   pq->record_cap
221     = settings_get_workspace_cases (value_cnt);
222   if (pq->record_cap > max_buffers)
223     pq->record_cap = max_buffers;
224   else if (pq->record_cap < min_buffers)
225     pq->record_cap = min_buffers;
226   pq->record_cnt = 0;
227   pq->records = xnmalloc (pq->record_cap, sizeof *pq->records);
228   pq->idx = 0;
229
230   return pq;
231 }
232
233 static void
234 pqueue_destroy (struct pqueue *pq)
235 {
236   if (pq != NULL)
237     {
238       while (!pqueue_is_empty (pq))
239         {
240           casenumber id;
241           struct ccase *c = pqueue_pop (pq, &id);
242           case_unref (c);
243         }
244       subcase_destroy (&pq->ordering);
245       free (pq->records);
246       free (pq);
247     }
248 }
249
250 static bool
251 pqueue_is_full (const struct pqueue *pq)
252 {
253   return pq->record_cnt >= pq->record_cap;
254 }
255
256 static bool
257 pqueue_is_empty (const struct pqueue *pq)
258 {
259   return pq->record_cnt == 0;
260 }
261
262 static void
263 pqueue_push (struct pqueue *pq, struct ccase *c, casenumber id)
264 {
265   struct pqueue_record *r;
266
267   assert (!pqueue_is_full (pq));
268
269   r = &pq->records[pq->record_cnt++];
270   r->id = id;
271   r->c = c;
272   r->idx = pq->idx++;
273
274   push_heap (pq->records, pq->record_cnt, sizeof *pq->records,
275              compare_pqueue_records_minheap, pq);
276 }
277
278 static struct ccase *
279 pqueue_pop (struct pqueue *pq, casenumber *id)
280 {
281   struct pqueue_record *r;
282
283   assert (!pqueue_is_empty (pq));
284
285   pop_heap (pq->records, pq->record_cnt--, sizeof *pq->records,
286             compare_pqueue_records_minheap, pq);
287
288   r = &pq->records[pq->record_cnt];
289   *id = r->id;
290   return r->c;
291 }
292
293 /* Compares record-run tuples A and B on id, then on case data,
294    then on insertion order, in descending order. */
295 static int
296 compare_pqueue_records_minheap (const void *a_, const void *b_,
297                                 const void *pq_)
298 {
299   const struct pqueue_record *a = a_;
300   const struct pqueue_record *b = b_;
301   const struct pqueue *pq = pq_;
302   int result = a->id < b->id ? -1 : a->id > b->id;
303   if (result == 0)
304     result = subcase_compare_3way (&pq->ordering, a->c, &pq->ordering, b->c);
305   if (result == 0)
306     result = a->idx < b->idx ? -1 : a->idx > b->idx;
307   return -result;
308 }