sort: New function sort_distinct_execute().
[pspp] / src / math / sort.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010 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.h"
26 #include "data/casewriter-provider.h"
27 #include "data/settings.h"
28 #include "data/subcase.h"
29 #include "libpspp/assertion.h"
30 #include "libpspp/bt.h"
31 #include "math/merge.h"
32
33 #include "gl/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     struct caseproto *proto;
45     struct subcase ordering;
46     struct merge *merge;
47     struct pqueue *pqueue;
48
49     sort_distinct_combine_func *combine;
50     sort_distinct_destroy_func *destroy;
51     void *aux;
52
53     struct casewriter *run;
54     casenumber run_id;
55     struct ccase *run_end;
56   };
57
58 static struct casewriter_class sort_casewriter_class;
59
60 static struct pqueue *pqueue_create (const struct subcase *,
61                                      const struct caseproto *,
62                                      sort_distinct_combine_func *, void *aux);
63 static void pqueue_destroy (struct pqueue *);
64 static bool pqueue_is_full (const struct pqueue *);
65 static bool pqueue_is_empty (const struct pqueue *);
66 static void pqueue_push (struct pqueue *, struct ccase *, casenumber);
67 static struct ccase *pqueue_pop (struct pqueue *, casenumber *);
68
69 static void output_record (struct sort_writer *);
70
71 struct casewriter *
72 sort_create_writer (const struct subcase *ordering,
73                     const struct caseproto *proto)
74 {
75   return sort_distinct_create_writer (ordering, proto, NULL, NULL, NULL);
76 }
77
78 struct casewriter *
79 sort_distinct_create_writer (const struct subcase *ordering,
80                              const struct caseproto *proto,
81                              sort_distinct_combine_func *combine,
82                              sort_distinct_destroy_func *destroy,
83                              void *aux)
84 {
85   struct sort_writer *sort;
86
87   sort = xmalloc (sizeof *sort);
88   sort->proto = caseproto_ref (proto);
89   subcase_clone (&sort->ordering, ordering);
90   sort->merge = merge_create (ordering, proto, combine, aux);
91   sort->pqueue = pqueue_create (ordering, proto, combine, aux);
92
93   sort->combine = combine;
94   sort->destroy = destroy;
95   sort->aux = aux;
96
97   sort->run = NULL;
98   sort->run_id = 0;
99   sort->run_end = NULL;
100
101   return casewriter_create (proto, &sort_casewriter_class, sort);
102 }
103
104 static void
105 sort_casewriter_write (struct casewriter *writer UNUSED, void *sort_,
106                        struct ccase *c)
107 {
108   struct sort_writer *sort = sort_;
109   bool next_run;
110
111   if (pqueue_is_full (sort->pqueue))
112     output_record (sort);
113
114   next_run = (sort->run_end == NULL
115               || subcase_compare_3way (&sort->ordering, c,
116                                        &sort->ordering, sort->run_end) < 0);
117   pqueue_push (sort->pqueue, c, sort->run_id + (next_run ? 1 : 0));
118 }
119
120 static void
121 sort_casewriter_destroy (struct casewriter *writer UNUSED, void *sort_)
122 {
123   struct sort_writer *sort = sort_;
124
125   if (sort->destroy != NULL)
126     sort->destroy (sort->aux);
127
128   subcase_destroy (&sort->ordering);
129   merge_destroy (sort->merge);
130   pqueue_destroy (sort->pqueue);
131   casewriter_destroy (sort->run);
132   case_unref (sort->run_end);
133   caseproto_unref (sort->proto);
134   free (sort);
135 }
136
137 static struct casereader *
138 sort_casewriter_convert_to_reader (struct casewriter *writer, void *sort_)
139 {
140   struct sort_writer *sort = sort_;
141   struct casereader *output;
142
143   if (sort->run == NULL && sort->run_id == 0)
144     {
145       /* In-core sort. */
146       sort->run = mem_writer_create (sort->proto);
147       sort->run_id = 1;
148     }
149   while (!pqueue_is_empty (sort->pqueue))
150     output_record (sort);
151
152   merge_append (sort->merge, casewriter_make_reader (sort->run));
153   sort->run = NULL;
154
155   output = merge_make_reader (sort->merge);
156   sort_casewriter_destroy (writer, sort);
157   return output;
158 }
159
160 static void
161 output_record (struct sort_writer *sort)
162 {
163   struct ccase *min_case;
164   casenumber min_run_id;
165
166   min_case = pqueue_pop (sort->pqueue, &min_run_id);
167 #if 0
168   printf ("\toutput: %f to run %d\n", case_num_idx (min_case, 0), min_run_id);
169 #endif
170
171   if (sort->run_id != min_run_id && sort->run != NULL)
172     {
173       merge_append (sort->merge, casewriter_make_reader (sort->run));
174       sort->run = NULL;
175     }
176   if (sort->run == NULL)
177     {
178       sort->run = tmpfile_writer_create (sort->proto);
179       sort->run_id = min_run_id;
180     }
181
182   case_unref (sort->run_end);
183   sort->run_end = case_ref (min_case);
184   casewriter_write (sort->run, min_case);
185 }
186
187 static struct casewriter_class sort_casewriter_class =
188   {
189     sort_casewriter_write,
190     sort_casewriter_destroy,
191     sort_casewriter_convert_to_reader,
192   };
193 \f
194 /* Reads all the cases from INPUT.  Sorts the cases according to
195    ORDERING.  Returns the sorted cases in a new casereader. */
196 struct casereader *
197 sort_execute (struct casereader *input, const struct subcase *ordering)
198 {
199   struct casewriter *output =
200     sort_create_writer (ordering, casereader_get_proto (input));
201   casereader_transfer (input, output);
202   return casewriter_make_reader (output);
203 }
204
205 /* Reads all the cases from INPUT.  Sorts the cases in ascending
206    order according to VARIABLE.  Returns the sorted cases in a
207    new casereader. */
208 struct casereader *
209 sort_execute_1var (struct casereader *input, const struct variable *var)
210 {
211   struct subcase sc;
212   struct casereader *reader;
213
214   subcase_init_var (&sc, var, SC_ASCEND);
215   reader = sort_execute (input, &sc);
216   subcase_destroy (&sc);
217   return reader;
218 }
219
220 /* Reads all the cases from INPUT.  Sorts the cases according to ORDERING,
221    combining cases that have the same ORDERING values using COMBINE.
222    Returns the sorted cases in a new casereader. */
223 struct casereader *
224 sort_distinct_execute (struct casereader *input,
225                        const struct subcase *ordering,
226                        sort_distinct_combine_func *combine,
227                        sort_distinct_destroy_func *destroy,
228                        void *aux)
229 {
230   struct casewriter *output =
231     sort_distinct_create_writer (ordering, casereader_get_proto (input),
232                                  combine, destroy, aux);
233   casereader_transfer (input, output);
234   return casewriter_make_reader (output);
235 }
236 \f
237 struct pqueue
238   {
239     struct subcase ordering;
240     struct bt bt;
241     size_t record_cap;
242     casenumber idx;
243
244     sort_distinct_combine_func *combine;
245     void *aux;
246   };
247
248 struct pqueue_record
249   {
250     struct bt_node bt_node;
251     casenumber id;
252     struct ccase *c;
253     casenumber idx;
254   };
255
256 static int compare_pqueue_records (const struct bt_node *a,
257                                    const struct bt_node *b,
258                                    const void *ordering);
259
260 static struct pqueue *
261 pqueue_create (const struct subcase *ordering, const struct caseproto *proto,
262                sort_distinct_combine_func *combine, void *aux)
263 {
264   struct pqueue *pq;
265
266   pq = xmalloc (sizeof *pq);
267   subcase_clone (&pq->ordering, ordering);
268   pq->record_cap = settings_get_workspace_cases (proto);
269   if (pq->record_cap > max_buffers)
270     pq->record_cap = max_buffers;
271   else if (pq->record_cap < min_buffers)
272     pq->record_cap = min_buffers;
273   bt_init (&pq->bt, compare_pqueue_records, &pq->ordering);
274   pq->idx = 0;
275
276   pq->combine = combine;
277   pq->aux = aux;
278
279   return pq;
280 }
281
282 static void
283 pqueue_destroy (struct pqueue *pq)
284 {
285   if (pq != NULL)
286     {
287       while (!pqueue_is_empty (pq))
288         {
289           casenumber id;
290           struct ccase *c = pqueue_pop (pq, &id);
291           case_unref (c);
292         }
293       subcase_destroy (&pq->ordering);
294       free (pq);
295     }
296 }
297
298 static bool
299 pqueue_is_full (const struct pqueue *pq)
300 {
301   return bt_count (&pq->bt) >= pq->record_cap;
302 }
303
304 static bool
305 pqueue_is_empty (const struct pqueue *pq)
306 {
307   return bt_is_empty (&pq->bt);
308 }
309
310 static void
311 pqueue_push (struct pqueue *pq, struct ccase *c, casenumber id)
312 {
313   struct pqueue_record *r;
314
315   assert (!pqueue_is_full (pq));
316
317   r = xmalloc (sizeof *r);
318   r->id = id;
319   r->c = c;
320   r->idx = pq->idx++;
321   bt_insert (&pq->bt, &r->bt_node);
322
323   if (pq->combine != NULL)
324     {
325       struct bt_node *q_ = bt_prev (&pq->bt, &r->bt_node);
326       if (q_ != NULL)
327         {
328           struct pqueue_record *q = bt_data (q_, struct pqueue_record,
329                                              bt_node);
330           if (q->id == r->id && subcase_equal (&pq->ordering, q->c,
331                                                &pq->ordering, r->c))
332             {
333               bt_delete (&pq->bt, &r->bt_node);
334               free (r);
335               q->c = pq->combine (q->c, r->c, pq->aux);
336             }
337         }
338     }
339 }
340
341 static struct ccase *
342 pqueue_pop (struct pqueue *pq, casenumber *id)
343 {
344   struct pqueue_record *r;
345   struct ccase *c;
346
347   assert (!pqueue_is_empty (pq));
348
349   r = bt_data (bt_first (&pq->bt), struct pqueue_record, bt_node);
350   bt_delete (&pq->bt, &r->bt_node);
351   *id = r->id;
352   c = r->c;
353   free (r);
354   return c;
355 }
356
357 /* Compares record-run tuples A and B on id, then on case data,
358    then on insertion order. */
359 static int
360 compare_pqueue_records (const struct bt_node *a_, const struct bt_node *b_,
361                         const void *ordering_)
362 {
363   const struct pqueue_record *a = bt_data (a_, struct pqueue_record, bt_node);
364   const struct pqueue_record *b = bt_data (b_, struct pqueue_record, bt_node);
365   const struct subcase *ordering = ordering_;
366   int result = a->id < b->id ? -1 : a->id > b->id;
367   if (result == 0)
368     result = subcase_compare_3way (ordering, a->c, ordering, b->c);
369   if (result == 0)
370     result = a->idx < b->idx ? -1 : a->idx > b->idx;
371   return result;
372 }