File: depth_dbm_solver.c

package info (click to toggle)
freecell-solver 5.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,256 kB
  • sloc: ansic: 28,700; perl: 10,050; xml: 5,600; python: 1,339; sh: 533; cpp: 275; makefile: 20; javascript: 8
file content (388 lines) | stat: -rw-r--r-- 13,132 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
 * This file is part of Freecell Solver. It is subject to the license terms in
 * the COPYING.txt file found in the top-level directory of this distribution
 * and at http://fc-solve.shlomifish.org/docs/distro/COPYING.html . No part of
 * Freecell Solver, including this file, may be copied, modified, propagated,
 * or distributed except according to the terms contained in the COPYING file.
 *
 * Copyright (c) 2012 Shlomi Fish
 */
/*
 * depth_dbm_solver.c - a specialised solver that offloads the states'
 * collection to an on-disk DBM database such as Berkeley DB or Google's
 * LevelDB. Has been adapted to be completely in-memory. It makes use of
 * delta_states.c for a very compact storage.
 *
 * In addition, this solver implements the scheme in:
 * https://groups.yahoo.com/neo/groups/fc-solve-discuss/conversations/topics/1135
 */

#include "dbm_solver_head.h"

typedef struct
{
    fcs_dbm__cache_store__common cache_store;
    meta_allocator queue_meta_alloc;
    fcs_offloading_queue queue;
} fcs_dbm_collection_by_depth;

#define MAX_FCC_DEPTH (RANK_KING * 4 * DECKS_NUM * 2)
typedef size_t fcs_batch_size;
typedef struct
{
    fcs_dbm_collection_by_depth colls_by_depth[MAX_FCC_DEPTH];
    fcs_condvar monitor;
    const char *offload_dir_path;
    int curr_depth;
    dbm_instance_common_elems common;
    fcs_batch_size max_batch_size;
} dbm_solver_instance;

#define CHECK_KEY_CALC_DEPTH()                                                 \
    (instance->curr_depth + list->num_non_reversible_moves_including_prune)

#include "dbm_procs.h"
static inline void instance_init(dbm_solver_instance *const instance,
    const fcs_dbm_common_input *const inp, const fcs_batch_size max_batch_size,
    FILE *const out_fh)
{
    instance->max_batch_size = max_batch_size;
    instance->curr_depth = 0;
    instance->offload_dir_path = inp->offload_dir_path;
    fcs_dbm__common_init(&(instance->common), inp->iters_delta_limit,
        inp->local_variant, out_fh);

    for (int depth = 0; depth < MAX_FCC_DEPTH; depth++)
    {
        const_AUTO(coll, &(instance->colls_by_depth[depth]));
#ifdef FCS_DBM_USE_OFFLOADING_QUEUE
        fcs_offloading_queue__init(
            &(coll->queue), inp->offload_dir_path, depth);
#else
        fc_solve_meta_compact_allocator_init(&(coll->queue_meta_alloc));
        fcs_offloading_queue__init(&(coll->queue), &(coll->queue_meta_alloc));
#endif

        fcs_dbm__cache_store__init(&(coll->cache_store), &(instance->common),
            &(coll->queue_meta_alloc), inp->dbm_store_path,
            inp->pre_cache_max_count, inp->caches_delta);
    }
    fcs_condvar_init(&(instance->monitor));
}

static inline void instance_destroy(dbm_solver_instance *const instance)
{
    for (int depth = 0; depth < MAX_FCC_DEPTH; depth++)
    {
        const_AUTO(coll, &(instance->colls_by_depth[depth]));
        fcs_offloading_queue__destroy(&(coll->queue));
#ifndef FCS_DBM_USE_OFFLOADING_QUEUE
        fc_solve_meta_compact_allocator_finish(&(coll->queue_meta_alloc));
#endif
        DESTROY_CACHE(coll);
    }
    fcs_condvar_destroy(&(instance->monitor));
    fcs_lock_destroy(&instance->common.storage_lock);
}

struct fcs_dbm_solver_thread_struct
{
    dbm_solver_instance *instance;
    fcs_delta_stater delta_stater;
    meta_allocator thread_meta_alloc;
};

static void *instance_run_solver_thread(void *const void_arg)
{
    fcs_derived_state *derived_list_recycle_bin = NULL;
    fcs_state_keyval_pair state;
#ifdef DEBUG_OUT
    fcs_state_locs_struct locs;
    fc_solve_init_locs(&locs);
#endif
    DECLARE_IND_BUF_T(indirect_stacks_buffer)

    const_AUTO(thread, ((thread_arg *)void_arg)->thread);
    const_SLOT(instance, thread);
    const_AUTO(delta_stater, &(thread->delta_stater));
    const_AUTO(local_variant, instance->common.variant);
    const_SLOT(max_batch_size, instance);

    fcs_batch_size prev_size = 0;
    compact_allocator derived_list_allocator;
    fc_solve_compact_allocator_init(
        &(derived_list_allocator), &(thread->thread_meta_alloc));
    const_AUTO(out_fh, instance->common.out_fh);

    TRACE("%s\n", "instance_run_solver_thread start");

    const_AUTO(coll, &(instance->colls_by_depth[instance->curr_depth]));
    fcs_dbm_record *tokens[max_batch_size];
    fcs_derived_state *derived_lists[max_batch_size];
    while (TRUE)
    {
        /* First of all extract a batch of items. */
        fcs_lock_lock(&instance->common.storage_lock);
        bool should_break = FALSE;
        fcs_batch_size batch_size = 0;
        if (prev_size > 0)
        {
            if (!(instance->common.queue_num_extracted_and_processed -=
                    prev_size))
            {
                fcs_condvar_broadcast(&(instance->monitor));
            }
            prev_size = 0;
        }
        else
        {
            should_break =
                (instance->common.should_terminate != DONT_TERMINATE);
            if (instance->common.should_terminate == DONT_TERMINATE)
            {
                for (; batch_size < max_batch_size; ++batch_size)
                {
                    if (fcs_offloading_queue__extract(&(coll->queue),
                            (offloading_queue_item *)(&tokens[batch_size])))
                    {
                        derived_lists[batch_size] = NULL;
                        instance_increment(instance);
                    }
                    else
                    {
                        break;
                    }
                }

                should_break =
                    !instance->common.queue_num_extracted_and_processed;

                prev_size = batch_size;
                if ((!should_break) && (batch_size == 0))
                {
                    /* Sleep until more items become available in the
                     * queue. */
                    fcs_condvar__wait_on(
                        &(instance->monitor), &(instance->common.storage_lock));
                }
            }
        }
        fcs_lock_unlock(&instance->common.storage_lock);

        if (should_break && (prev_size == 0))
        {
            break;
        }
        if (batch_size == 0)
        {
            continue;
        }

        for (fcs_batch_size batch_i = 0; batch_i < batch_size; ++batch_i)
        {
            const_AUTO(token, tokens[batch_i]);
            /* Handle item. */
            fc_solve_delta_stater_decode_into_state(
                delta_stater, token->key.s, &state, indirect_stacks_buffer);
            /* A section for debugging. */
            FCS__OUTPUT_STATE(out_fh, "", &(state.s), &locs);

            if (instance_solver_thread_calc_derived_states(local_variant,
                    &state, token, &derived_lists[batch_i],
                    &derived_list_recycle_bin, &derived_list_allocator, TRUE))
            {
                fcs_dbm_queue_item physical_item;
                physical_item.key = token->key;
                fcs_lock_lock(&instance->common.storage_lock);
                fcs_dbm__found_solution(
                    &(instance->common), token, &physical_item);
                fcs_condvar_broadcast(&(instance->monitor));
                fcs_lock_unlock(&instance->common.storage_lock);
                goto thread_end;
            }
        }

        /* Encode all the states. */
        for (fcs_batch_size batch_i = 0; batch_i < batch_size; ++batch_i)
        {
            for (var_AUTO(derived_iter, derived_lists[batch_i]); derived_iter;
                 derived_iter = derived_iter->next)
            {
                fcs_init_and_encode_state(delta_stater, local_variant,
                    &(derived_iter->state), &(derived_iter->key));
            }
        }

        instance_check_multiple_keys(thread, instance, &(coll->cache_store),
            &(thread->thread_meta_alloc), derived_lists, batch_size
#ifdef FCS_DBM_CACHE_ONLY
            ,
            item->moves_to_key
#endif
        );

        for (fcs_batch_size batch_i = 0; batch_i < batch_size; ++batch_i)
        {
            fcs_derived_state_list__recycle(
                &derived_list_recycle_bin, &derived_lists[batch_i]);
        }
        /* End handle item. */
        /* End of main thread loop */
    }
thread_end:

    fc_solve_compact_allocator_finish(&(derived_list_allocator));
    TRACE("%s\n", "instance_run_solver_thread end");
    return NULL;
}

#include "depth_dbm_procs.h"

static inline void instance_check_key(
    dbm_solver_thread *const thread GCC_UNUSED,
    dbm_solver_instance *const instance, const int key_depth,
    fcs_encoded_state_buffer *const key, fcs_dbm_record *const parent,
    const unsigned char move GCC_UNUSED,
    const fcs_which_moves_bitmask *const which_irreversible_moves_bitmask
        GCC_UNUSED
#ifdef FCS_DBM_CACHE_ONLY
    ,
    const fcs_fcc_move *moves_to_parent
#endif
)
{
    const_AUTO(coll, &(instance->colls_by_depth[key_depth]));
    fcs_dbm_record *token;

    if ((token = cache_store__has_key(&coll->cache_store, key, parent)))
    {
#ifndef FCS_DBM_WITHOUT_CACHES
        fcs_cache_key_info *cache_key = cache_store__insert_key(
            &(instance->cache_store), key, parent, moves_to_parent, move);
#endif

        /* Now insert it into the queue. */

        fcs_offloading_queue__insert(
            &(coll->queue), (const offloading_queue_item *)(&token));

        ++instance->common.count_of_items_in_queue;
        ++instance->common.num_states_in_collection;
        instance_debug_out_state(instance, &(token->key));
    }
}

static void instance_run_all_threads(dbm_solver_instance *const instance,
    fcs_state_keyval_pair *const init_state, const size_t num_threads)
{
    const_AUTO(threads,
        dbm__calc_threads(instance, init_state, num_threads, init_thread));
    while (instance->curr_depth < MAX_FCC_DEPTH)
    {
        dbm__spawn_threads(instance, num_threads, threads);
        if (instance->common.queue_solution_was_found)
        {
            break;
        }
        mark_and_sweep_old_states(instance,
            fc_solve_dbm_store_get_dict(
                instance->colls_by_depth[instance->curr_depth]
                    .cache_store.store),
            instance->curr_depth);
        ++instance->curr_depth;
    }

    dbm__free_threads(instance, num_threads, threads, free_thread);
}

int main(int argc, char *argv[])
{
    const char *out_filename = NULL;
    DECLARE_IND_BUF_T(init_indirect_stacks_buffer)
    fcs_dbm_common_input inp = fcs_dbm_common_input_init;
    fcs_batch_size max_batch_size = 1;
    const char *param;

    int real_arg;
    int *arg = &real_arg;
    for (real_arg = 1; real_arg < argc; real_arg++)
    {
        if (fcs_dbm__extract_common_from_argv(argc, argv, arg, &inp))
        {
        }
        else if ((param = TRY_PARAM("--batch-size")))
        {
            max_batch_size = (fcs_batch_size)atol(param);
            if (max_batch_size < 1)
            {
                fc_solve_err("--batch-size must be at least 1.\n");
            }
        }
        else if ((param = TRY_PARAM("-o")))
        {
            out_filename = param;
        }
        else
        {
            break;
        }
    }

    if (real_arg < argc - 1)
    {
        fc_solve_err("%s\n", "Junk arguments!");
    }
    if (real_arg == argc)
    {
        fc_solve_err("%s\n", "No board specified.");
    }
    const_AUTO(num_threads, inp.num_threads);

    FILE *const out_fh = calc_out_fh(out_filename);
    fcs_state_keyval_pair init_state;
    read_state_from_file(inp.local_variant, argv[real_arg],
        &init_state PASS_IND_BUF_T(init_indirect_stacks_buffer));
    horne_prune__simple(inp.local_variant, &init_state);

    const_AUTO(local_variant, inp.local_variant);
    fcs_delta_stater delta;
    fc_solve_delta_stater_init(&delta, local_variant, &init_state.s, STACKS_NUM,
        FREECELLS_NUM PASS_ON_NOT_FC_ONLY(CALC_SEQUENCES_ARE_BUILT_BY()));

#define KEY_PTR() (key_ptr)
    dbm_solver_instance instance;
    instance_init(&instance, &inp, max_batch_size, out_fh);

    fcs_encoded_state_buffer *const key_ptr = &(instance.common.first_key);
    fcs_init_and_encode_state(&delta, local_variant, &init_state, KEY_PTR());

    /* The NULL parent_state_enc and move for indicating this is the
     * initial state. */
    fcs_encoded_state_buffer parent_state_enc;
    fcs_init_encoded_state(&(parent_state_enc));

    fcs_dbm_record *token;
#ifndef FCS_DBM_WITHOUT_CACHES
    cache_store__insert_key(
        &(instance.cache_store), KEY_PTR(), &parent_state_enc, NULL, '\0');
#else
    token = fc_solve_dbm_store_insert_key_value(
        instance.colls_by_depth[0].cache_store.store, KEY_PTR(), NULL, TRUE);
#endif

    fcs_offloading_queue__insert(&(instance.colls_by_depth[0].queue),
        (const offloading_queue_item *)(&token));
    ++instance.common.num_states_in_collection;
    ++instance.common.count_of_items_in_queue;

    instance_run_all_threads(&instance, &init_state, NUM_THREADS());
    handle_and_destroy_instance_solution(&instance, &delta);

    fc_solve_delta_stater_release(&delta);
    if (out_filename)
    {
        fclose(out_fh);
    }

    return 0;
}