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