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