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