diff --git a/TODO-archiving b/TODO-archiving index 27a0f29de..754fca0c7 100644 --- a/TODO-archiving +++ b/TODO-archiving @@ -12,3 +12,8 @@ - [ ] Hypervolume archiver - [ ] MGA + +# NDS Forest + + - [ ] Enable timing of query vs update + - [ ] Add stats to Treap diff --git a/c/Makefile b/c/Makefile index 20b439809..4249a391b 100644 --- a/c/Makefile +++ b/c/Makefile @@ -196,7 +196,7 @@ $(ALL_NAMES): %: $(BINDIR)/%$(EXE) include libhv.mk -$(BINDIR)/archiver$(EXE): main-archiver.o io.o treap_archive.o nondominated.o treap2d_fixed_size.o +$(BINDIR)/archiver$(EXE): main-archiver.o io.o treap_archive.o nondominated.o treap2d_fixed_size.o timer.o $(BINDIR)/dominatedsets$(EXE): dominatedsets.o nondominated.o treap2d_fixed_size.o $(BINDIR)/eaf$(EXE): eaf.o eaf_main.o eaf3d.o avl.o $(BINDIR)/epsilon$(EXE): epsilon.o nondominated.o treap2d_fixed_size.o @@ -226,7 +226,7 @@ hvapprox.o: hvapprox.h pow_int.h rng.h mt19937/mt19937.h hvc3d.o: hv_priv.h sort.h hv3d_priv.h treap2d.h igd.o: cmdline.h io.h nondominated.h igd.h pow_int.h io.o: io.h io_priv.h -main-archiver.o: cmdline.h io.h treap_archive.h treap2d.h nd_tree.h libmoocore-config.h +main-archiver.o: cmdline.h io.h treap_archive.h treap2d.h nd_tree.h nds_forest.h libmoocore-config.h main-hv.o: cmdline.h io.h hv.h timer.h libmoocore-config.h nondominated.h hvapprox.h main-hvapprox.o: cmdline.h io.h hvapprox.h main-nondominated.o : cmdline.h io.h nondominated.h nondominated_kung.h diff --git a/c/README.md b/c/README.md index ff31252e8..1b7f24bd9 100644 --- a/c/README.md +++ b/c/README.md @@ -26,7 +26,7 @@ The [**moocore** project](https://github.com/multi-objective/moocore/) collects * Computation of the Empirical Attainment Function. The empirical attainment function (EAF) describes the probabilistic distribution of the outcomes obtained by a stochastic algorithm in the objective space. - * Archivers that allow efficiently storing a nondominated set from points given one-by-one as a sequence. + * Archivers that allow efficiently storing a nondominated set, or sorted nondominated set, from points given one-by-one as a sequence. The goal of **moocore** is to provide an implementation of these functions that is efficient, thoroughly tested, well-documented, multi-platform (Windows, Linux, MacOS), multi-language (C, R, and Python, so far), with minimal dependencies and reusable from other libraries and packages, thus providing an easy-to-use and high-performance building block. diff --git a/c/main-archiver.c b/c/main-archiver.c index df7718f31..7b78ca38c 100644 --- a/c/main-archiver.c +++ b/c/main-archiver.c @@ -22,17 +22,21 @@ #include #include #include +#include #include // for getopt() #include // for getopt_long() #include "io.h" #include "archive.h" +#include "nds_forest.h" + #define CMDLINE_COPYRIGHT_YEARS "2026" #define CMDLINE_AUTHORS "Manuel Lopez-Ibanez \n" #include "cmdline.h" static bool union_flag = false; static bool always_nd_tree_flag = false; +static bool nds_flag = false; static int verbose_flag = 1; static char *suffix = NULL; @@ -50,6 +54,9 @@ OPTION_HELP_STR OPTION_VERSION_STR " -v, --verbose print some information (time, maximum, etc). \n" " --nd-tree Always use ND-Tree for any dimension.\n" +" --nds NDS-archive (currently NDS-Forest).\n" +" --strategy= NDS-Forest insertion strategy: linear, front-binary, \n" +" previous-rank, zero-then-binary, dominance-guided-binary.\n" OPTION_UNION_STR " -s, --suffix=STRING Create an output file for each input file by appending\n" " this suffix. This is ignored when reading from stdin. \n" @@ -57,6 +64,16 @@ OPTION_UNION_STR "\n"); } +static bool +check_no_missing_points(NDSForest *archiver, size_t expected_n) +{ + size_t nfronts = nds_forest_len(archiver); + size_t total_points = 0; + for (size_t i = 0; i < nfronts; i++) + total_points += nds_forest_front_total_size(archiver, i); + return total_points == expected_n; +} + // FIXME: Add options to print quality metrics after archiving each input point. static bool read_and_archive(FILE * input) @@ -115,11 +132,97 @@ read_and_archive(FILE * input) return (status == 0); } +static bool +read_and_nds_archive(FILE * input, int strategy) +{ + dimension_t dim = 0; + double point[MOOCORE_DIMENSION_MAX+1]; + // Read the first line as the dimension/template point. + int status = fread_next_double_point(input, point, &dim); + if (status != 1) + fatal_error("reading the first point"); + if (dim < 2) + fatal_error("At least 2 dimensions are required"); + + const bool use_treap = (dim == 2 && !always_nd_tree_flag); + const bool x_is_null = true; + const bool do_timing = (verbose_flag >= 2); + NDSForest * archive = use_treap + ? nds_forest_treap_new(strategy, x_is_null, do_timing) + : nds_forest_ndtree_new(dim, strategy, /*max_children=*/0, /*max_bucket_size=*/0, x_is_null, do_timing); + + size_t points_read = 0; + // Read point until EOF or empty line. + do { + if (!nds_forest_add(archive, point, /*x=*/NULL)) + fatal_error("Memory error!"); + + points_read++; + if (!check_no_missing_points(archive, points_read)) + fatal_error("missing points when adding point %zu =[%g, %g, ...]\n", points_read, point[0], point[1]); + + status = fread_next_double_point(input, point, &dim); + } while (status == 1 || (union_flag && status == 0)); + + if (status != READ_INPUT_FILE_EMPTY && status != 0) + fatal_error("reading point from input"); + + // We completed one data set + size_t nfronts = nds_forest_len(archive); + // Print result + if (verbose_flag >= 2) { + fprintf(stdout, + "# Query time: %-20.12g\n" + "# Update time: %-20.12g\n" + "# Total points: %zu\n" + "# Unique points: %zu\n" + "# Number of fronts: %zu\n", + archive->query_time, archive->update_time, + nds_forest_total_size(archive), + nds_forest_unique_size(archive), + nfronts); + fprintf(stdout, "# Front total sizes: "); + if (nfronts > 0) { + fprintf(stdout, "%zu", nds_forest_front_total_size(archive, 0)); + for (size_t i = 1; i < nfronts; i++) + fprintf(stdout, ", %zu", nds_forest_front_total_size(archive, i)); + fprintf(stdout, "\n"); + } + fprintf(stdout, "# Front unique sizes: "); + if (nfronts > 0) { + fprintf(stdout, "%zu", nds_forest_front_unique_size(archive, 0)); + for (size_t i = 1; i < nfronts; i++) + fprintf(stdout, ", %zu", nds_forest_front_unique_size(archive, i)); + fprintf(stdout, "\n"); + } + } + + _attr_maybe_unused size_t total_points = 0; + for (size_t i = 0; i < nfronts; i++) { + size_t npoint = nds_forest_front_total_size(archive, i); + ASSUME(npoint > 0); + ASSUME(npoint < INT_MAX); + total_points += npoint; + double * z_list = MOOCORE_MALLOC(dim * npoint, *z_list); + nds_forest_front_get_contents(archive, i, z_list, NULL); + // FIXME: Add an option to sort the output. + char prefix[256]; + snprintf(prefix, 255, "%zu ", i); + // FIXME: write_sets should take size_t * or unsigned *; + int n_points = (int) npoint; + write_sets(stdout, z_list, dim, &n_points, 1, prefix); + free(z_list); + } + nds_forest_free(archive); + assert(total_points == points_read); + return (status == 0); +} + int main(int argc, char *argv[]) { // See the man page for getopt_long for an explanation of these fields. - static const char short_options[] = "hVvqUs:N"; + static const char short_options[] = "hVvqUs:NnS:"; static const struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'}, @@ -128,16 +231,30 @@ int main(int argc, char *argv[]) {"union", no_argument, NULL, 'U'}, {"suffix", required_argument, NULL, 's'}, {"nd-tree", no_argument, NULL, 'N'}, + {"nds", no_argument, NULL, 'n'}, + {"strategy", required_argument, NULL, 'S'}, {NULL, 0, NULL, 0} /* marks end of list */ }; set_program_invocation_short_name(argv[0]); + int nds_forest_insertion_strategy = LINEAR; + int opt; /* it's actually going to hold a char. */ int longopt_index; while (0 < (opt = getopt_long (argc, argv, short_options, long_options, &longopt_index))) { switch (opt) { + case 'S': // --strategy + nds_forest_insertion_strategy = parse_nds_forest_strategy(optarg); + if (nds_forest_insertion_strategy == UNKNOWN_STRATEGY) + fatal_error("unknown value (%s) of --strategy=", optarg); + break; + + case 'n': // --nds + nds_flag = true; + break; + case 'N': // --nd-tree always_nd_tree_flag = true; break; @@ -165,8 +282,14 @@ int main(int argc, char *argv[]) int numfiles = argc - optind; if (numfiles < 1) { // Read stdin. - while (read_and_archive(stdin)) { - fprintf(stdout, "\n"); + if (nds_flag) { + while (read_and_nds_archive(stdin, nds_forest_insertion_strategy)) { + fprintf(stdout, "\n"); + } + } else { + while (read_and_archive(stdin)) { + fprintf(stdout, "\n"); + } } } return EXIT_SUCCESS; diff --git a/c/nds_forest.h b/c/nds_forest.h new file mode 100644 index 000000000..6ed2af36f --- /dev/null +++ b/c/nds_forest.h @@ -0,0 +1,802 @@ +/************************************************************************* + + nds_forest.h: Non-dominated Sorting Forest + + --------------------------------------------------------------------- + Copyright (C) 2026 + Jonathan Fieldsend + Manuel Lopez-Ibanez + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + + --------------------------------------------------------------------- + +*************************************************************************/ +#ifndef NDS_FOREST_H +#define NDS_FOREST_H + +#include +#include +#include +#include +#include +#include + +#include "nd_tree.h" +#include "treap_archive.h" +#include "timer.h" + +enum nds_forest_insertion_strategy_t { + LINEAR = 0, + FRONT_BINARY, + PREVIOUS_RANK, + ZERO_THEN_BINARY, + DOMINANCE_GUIDED_BINARY, + UNKNOWN_STRATEGY, +}; + +static inline int +parse_nds_forest_strategy(const char * optarg) +{ +#define STREQUAL(S1, S2) (strncmp((S1), (S2), strlen(S2)) == 0) +#define STRATEGY_MATCH(STRING, ENUM_VALUE) \ + if (STREQUAL(optarg, STRING)) return ENUM_VALUE + + STRATEGY_MATCH("linear", LINEAR); + STRATEGY_MATCH("front-binary", FRONT_BINARY); + STRATEGY_MATCH("previous-rank", PREVIOUS_RANK); + STRATEGY_MATCH("zero-then-binary", ZERO_THEN_BINARY); + STRATEGY_MATCH("dominance-guided-binary", DOMINANCE_GUIDED_BINARY); + return UNKNOWN_STRATEGY; +#undef STRATEGY_MATCH +#undef STREQUAL +} + +enum nds_forest_tree_type_t { + NDS_FOREST_TREE_TREAP, + NDS_FOREST_TREE_NDTREE, +}; + +typedef struct NDSForest { + enum nds_forest_tree_type_t tree_type; + // FIXME: Use a deque + void *fronts; // Array of concrete tree objects, not pointers. + size_t n; + size_t cap; + size_t last_rank; + dimension_t dim; + enum nds_forest_insertion_strategy_t insertion_strategy; + double query_time, update_time; + BaseArchive base; + NDTreeConfig config; // Used only by NDTreeArchive. + double last_objectives[]; // Flexible array. +} NDSForest; + +typedef struct NDSForestIterator { + const NDSForest *forest; + union { + NDTreeIterator * ndtree_it; + TreapIterator * treap_it; + }; + size_t front_index; + uint64_t revision; // To detect modifications of the tree while iterating. +} NDSForestIterator; + + +#define NDS_FOREST_DISPATCH(SELF, TREAP_CODE, NDTREE_CODE) \ + switch ((SELF)->tree_type) { \ + case NDS_FOREST_TREE_TREAP: do { TREAP_CODE; } while(0); break; \ + case NDS_FOREST_TREE_NDTREE: do { NDTREE_CODE; } while(0); break; \ + default: unreachable(); \ + } + +static inline size_t +nds_forest_sizeof_tree_type(const NDSForest * restrict self) +{ + NDS_FOREST_DISPATCH(self, + return sizeof(TreapArchive), + return sizeof(NDTreeArchive)); +} + +_attr_warn_unused_result +static inline NDSForest * +nds_forest_new(dimension_t dim, + enum nds_forest_insertion_strategy_t strategy, + enum nds_forest_tree_type_t tree_type, + const NDTreeConfig *config, bool x_is_null, bool do_timing) +{ + if (strategy >= UNKNOWN_STRATEGY) { + errprintf("Unknown insertion strategy for NDS Forest"); + return NULL; + } + + if (dim < 2) { + errprintf("Minimum number of dimensions is 2"); + return NULL; + } + + if (tree_type == NDS_FOREST_TREE_TREAP && dim != 2) { + errprintf("Treap trees only support dimension 2"); + return NULL; + } + + if (tree_type != NDS_FOREST_TREE_TREAP + && tree_type != NDS_FOREST_TREE_NDTREE) { + errprintf("Unknown tree type"); + return NULL; + } + + /* FIXME: last_objectives could be just a pointer to the actual last point, + because the last inserted point has to be in one tree and cannot be + erased without resetting last_objectives. */ + NDSForest *self = malloc(sizeof(*self) + dim * sizeof(*self->last_objectives)); + if (!self) + return NULL; + + self->tree_type = tree_type; + self->cap = 64; + self->fronts = malloc(self->cap * nds_forest_sizeof_tree_type(self)); + if (self->fronts == NULL) { + free(self); + return NULL; + } + + for (dimension_t i = 0; i < dim; i++) + self->last_objectives[i] = INFINITY; + + self->n = 0; + self->last_rank = SIZE_MAX; + self->dim = dim; + self->insertion_strategy = strategy; + if (tree_type == NDS_FOREST_TREE_NDTREE) + self->config = *config; + self->base.revision = 0; + self->base.keep_duplicates = true; + self->base.x_is_null = x_is_null; + self->query_time = (do_timing) ? 0 : -1; + self->update_time = self->query_time; + return self; +} + +static inline Timer_t +nds_forest_timer_start(const NDSForest * self) +{ + if (likely(self->query_time < 0)) + return (Timer_t) { 0 }; // unused. + return timer_start(VIRTUAL_TIME); +} + +static inline void +nds_forest_timer_finish_query(NDSForest * self, Timer_t * timer) +{ + if (likely(self->query_time < 0)) + return; + self->query_time += timer_reset(timer); +} + +static inline void +nds_forest_timer_finish_update(NDSForest * self, Timer_t * timer) +{ + ASSUME((self->query_time < 0) == (self->update_time < 0)); + if (likely(self->update_time < 0)) + return; + self->update_time += timer_elapsed(timer); +} + +static inline void +nds_forest_get_timings(const NDSForest * self, double * query_time, double * update_time) +{ + *query_time = self->query_time; + *update_time = self->update_time; +} + +static inline NDSForest * +nds_forest_ndtree_new(dimension_t dim, + enum nds_forest_insertion_strategy_t strategy, + uint8_t max_children, uint8_t max_bucket_size, + bool x_is_null, bool do_timing) +{ + NDTreeConfig config = { .max_children = max_children, .max_bucket_size = max_bucket_size }; + return nds_forest_new(dim, strategy, NDS_FOREST_TREE_NDTREE, &config, x_is_null, do_timing); +} + +static inline NDSForest * +nds_forest_treap_new(enum nds_forest_insertion_strategy_t strategy, bool x_is_null, bool do_timing) +{ + return nds_forest_new(2, strategy, NDS_FOREST_TREE_TREAP, NULL, x_is_null, do_timing); +} + +static inline void * +nds_forest_front_at(NDSForest * restrict self, size_t rank) +{ + return (unsigned char *)self->fronts + rank * nds_forest_sizeof_tree_type(self); +} + +static inline const void * +nds_forest_front_at_const(const NDSForest * restrict self, size_t rank) +{ + return (const unsigned char *)self->fronts + rank * nds_forest_sizeof_tree_type(self); +} + +static inline void +nds_forest_front_free_nodes(NDSForest * restrict self, size_t rank) +{ + NDS_FOREST_DISPATCH(self, + treap_archive_free_nodes(nds_forest_front_at(self, rank)), + ndtree_free_nodes(nds_forest_front_at(self, rank))); +} + +static inline void +nds_forest_free(NDSForest * restrict self) +{ + if (!self) + return; + + for (size_t i = 0; i < self->n; i++) + nds_forest_front_free_nodes(self, i); + + free(self->fronts); + free(self); +} + +static inline size_t +nds_forest_len(const NDSForest *self) +{ + return self->n; +} + +static inline size_t +nds_forest_last_rank(const NDSForest *self) +{ + return self->last_rank; +} + +static inline size_t +nds_forest_front_total_size(const NDSForest *self, size_t rank) +{ + assert(rank < self->n); + if (rank >= self->n) + return SIZE_MAX; + + NDS_FOREST_DISPATCH( + self, + return treap_archive_total_size(nds_forest_front_at_const(self, rank)), + return ndtree_total_size(nds_forest_front_at_const(self, rank))); +} + +static inline size_t +nds_forest_total_size(const NDSForest *self) +{ + size_t n_fronts = nds_forest_len(self); + size_t total = 0; + for (size_t i = 0; i < n_fronts; i++) + total += nds_forest_front_total_size(self, i); + return total; +} + +static inline size_t +nds_forest_front_unique_size(const NDSForest *self, size_t rank) +{ + assert(rank < self->n); + if (rank >= self->n) + return SIZE_MAX; + + NDS_FOREST_DISPATCH( + self, + return treap_archive_unique_size(nds_forest_front_at_const(self, rank)), + return ndtree_unique_size(nds_forest_front_at_const(self, rank))); +} + +static inline size_t +nds_forest_unique_size(const NDSForest *self) +{ + size_t n_fronts = nds_forest_len(self); + size_t total = 0; + for (size_t i = 0; i < n_fronts; i++) + total += nds_forest_front_unique_size(self, i); + return total; +} + +static inline bool +nds_forest_dominates(const NDSForest * restrict self, size_t rank, const double *z) +{ + if (rank >= self->n) + return false; + + NDS_FOREST_DISPATCH( + self, + return treap_archive_dominates(nds_forest_front_at_const(self, rank), z), + return ndtree_dominates(nds_forest_front_at_const(self, rank), z)); +} + +static inline bool +nds_forest_dominated_by(const NDSForest *self, size_t rank, const double *z) +{ + if (rank >= self->n) + return false; + + NDS_FOREST_DISPATCH( + self, + return treap_archive_dominated_by(nds_forest_front_at_const(self, rank), z), + return ndtree_dominated_by(nds_forest_front_at_const(self, rank), z)); +} + + +static inline int +nds_forest_add_to_front(NDSForest * restrict self, size_t rank, + const double * restrict z, const void * restrict x, + bool check, void **displaced) +{ + NDS_FOREST_DISPATCH( + self, + return treap_archive_add(nds_forest_front_at(self, rank), z, x, check, (TreapArchive **)displaced), + return ndtree_add(nds_forest_front_at(self, rank), z, x, check, (FlexBucket **)displaced)); +} + +static inline size_t +nds_forest_displaced_unique_size(const NDSForest * restrict self, + const void * restrict displaced) +{ + NDS_FOREST_DISPATCH( + self, + return treap_archive_unique_size((const TreapArchive *)displaced), + return flex_bucket_unique_len((const FlexBucket *)displaced)); +} + +static inline void +nds_forest_displaced_free(const NDSForest * restrict self, void * restrict displaced) +{ + NDS_FOREST_DISPATCH( + self, + treap_archive_free((TreapArchive *)displaced), + flex_bucket_free((FlexBucket *)displaced)); +} + +static inline bool +nds_forest_front_init_with_single_solution(NDSForest * restrict self, size_t rank, + const double * restrict z, + const void * restrict x) +{ + assert((x == NULL) == self->base.x_is_null); + NDS_FOREST_DISPATCH( + self, + return treap_archive_init_with_single_solution(nds_forest_front_at(self, rank), + z, x, + /*keep_duplicates=*/true), + return ndtree_init_with_single_solution(nds_forest_front_at(self, rank), + z, x, self->dim, (const NDTreeConfig *)&self->config, + /*keep_duplicates=*/true)); +} + +static inline bool +nds_forest_front_init_with_displaced(NDSForest * restrict self, size_t rank, void * restrict displaced) +{ + NDS_FOREST_DISPATCH( + self, + return treap_archive_move(nds_forest_front_at(self, rank), (TreapArchive *)displaced), + return ndtree_init_with_displaced(nds_forest_front_at(self, rank), (FlexBucket *)displaced, + self->dim, (const NDTreeConfig *)&self->config, + /*keep_duplicates=*/true, + /*x_is_null=*/self->base.x_is_null)); +} + +/** + Insert a new empty front at rank. + + This function may reallocate the memory of self->fronts and return a new pointer. +*/ +_attr_warn_unused_result +static inline bool +nds_forest_insert_front(NDSForest * restrict self, size_t rank) +{ + const size_t sizeof_tree_type = nds_forest_sizeof_tree_type(self); + + if (self->n == self->cap) { + size_t new_cap = self->cap * 2; + void * fronts = realloc(self->fronts, new_cap * sizeof_tree_type); + if (fronts == NULL) + return false; + self->fronts = fronts; + self->cap = new_cap; + } + + if (rank < self->n) { + size_t size = sizeof_tree_type * (self->n - rank); + unsigned char *src = (unsigned char *) nds_forest_front_at(self, rank); + unsigned char *dst = src + sizeof_tree_type; + memmove(dst, src, size); + // If we insert a new front in the middle, last_rank becomes invalid. + if (self->last_rank >= rank) + self->last_rank = SIZE_MAX; + } + + self->n++; + assert(rank < self->n); + return true; +} + +/** + Insert a new front containing a single entry at rank. + + Updates last_rank. +*/ +_attr_warn_unused_result +static inline int +nds_forest_insert_singleton_front(NDSForest * restrict self, size_t rank, + const double * restrict z, + const void * restrict x) +{ + if (!nds_forest_insert_front(self, rank)) + return ARCHIVE_INSERT_MEMORY_ERROR; + + self->last_rank = rank; + memcpy(self->last_objectives, z, self->dim * sizeof(*z)); + + bool ok = nds_forest_front_init_with_single_solution(self, rank, z, x); + assert(nds_forest_front_unique_size(self, rank) > 0); + return ok ? ARCHIVE_INSERT_ACCEPTED : ARCHIVE_INSERT_MEMORY_ERROR; +} + +/** + Insert a new front containing a displaced tree. + + Updates last_rank. +*/ +_attr_warn_unused_result +static inline int +nds_forest_insert_displaced_front(NDSForest *self, size_t rank, void ** restrict displaced) +{ + if (!nds_forest_insert_front(self, rank)) + return ARCHIVE_INSERT_MEMORY_ERROR; + + bool ok = nds_forest_front_init_with_displaced(self, rank, *displaced); + assert(nds_forest_front_unique_size(self, rank) > 0); + *displaced = NULL; + return ok ? ARCHIVE_INSERT_ACCEPTED : ARCHIVE_INSERT_MEMORY_ERROR; +} + +static inline void +nds_forest_front_insert_displaced(NDSForest * restrict self, size_t rank, + void ** restrict displaced, + bool * restrict all_displaced) +{ + NDS_FOREST_DISPATCH( + self, + treap_archive_insert_displaced_p(nds_forest_front_at(self, rank), (TreapArchive **) displaced, all_displaced), + ndtree_insert_displaced(nds_forest_front_at(self, rank), (FlexBucket **)displaced, all_displaced)); +} + +/** + check: If true, check if FOREST_FUNC(_dominates)(self, rank, z) then z is rejected. + + Updates last_rank. +*/ +_attr_warn_unused_result +static inline bool +nds_forest_cascade(NDSForest * restrict self, size_t rank, + const double * restrict z, const void * restrict x) +{ + assert(rank <= self->n); + // Insert a new front at the end, no need to cascade. + if (rank == self->n) + return nds_forest_insert_singleton_front(self, rank, z, x); + + self->last_rank = rank; + memcpy(self->last_objectives, z, self->dim * sizeof(*z)); + assert(!nds_forest_dominates(self, rank, z)); + + void *displaced = NULL; + _attr_maybe_unused size_t prev_size = nds_forest_front_unique_size(self, rank); + assert(prev_size > 0); + int res = nds_forest_add_to_front(self, rank, z, x, /*check=*/false, &displaced); + assert(res == ARCHIVE_INSERT_ACCEPTED || res == ARCHIVE_INSERT_DUPLICATED); + if (res == ARCHIVE_INSERT_DUPLICATED) + return res; + + assert(nds_forest_front_unique_size(self, rank) > 0); + if (nds_forest_front_unique_size(self, rank) == 1) { + /* If we inserted a new vector, but there is only one vector, it means + everything was displaced. */ + assert(displaced != NULL + && nds_forest_displaced_unique_size(self, displaced) > 0 + && prev_size == nds_forest_displaced_unique_size(self, displaced)); + rank++; + res = nds_forest_insert_displaced_front(self, rank, &displaced); + assert(displaced == NULL); + return res; + } + + bool all_displaced = false; + while (displaced && nds_forest_displaced_unique_size(self, displaced)) { + rank++; + if (all_displaced || rank == self->n) { + // The whole front was displaced or we reached the last one. + res = nds_forest_insert_displaced_front(self, rank, &displaced); + assert(displaced == NULL); + return res; + } + nds_forest_front_insert_displaced(self, rank, &displaced, &all_displaced); + assert(nds_forest_front_unique_size(self, rank) > 0); + } + + assert(displaced == NULL + || nds_forest_displaced_unique_size(self, displaced) == 0); + if (displaced) + nds_forest_displaced_free(self, displaced); + return ARCHIVE_INSERT_ACCEPTED; +} + +/** + z_list must be an array of double allocated with sufficient space. Vectors + are copied to this array. + + x_list must be of array of void *. Only the pointers are copied. +*/ +static inline void +nds_forest_front_get_contents(const NDSForest * restrict self, size_t rank, double * z_list, const void ** x_list) +{ + NDS_FOREST_DISPATCH( + self, + treap_archive_get_contents(nds_forest_front_at_const(self, rank), z_list, x_list), + ndtree_get_contents(nds_forest_front_at_const(self, rank), z_list, x_list)); +} + +static inline size_t +nds_forest_find_exact_vector(const NDSForest * restrict self, const double * restrict z) +{ + // FIXME: We could use the dominance properties to do a binary search. + for (size_t rank = 0; rank < self->n; rank++) { + NDS_FOREST_DISPATCH(self, + if (treap_archive_find_exact_vector(nds_forest_front_at_const(self, rank), z)) return rank, + if (ndtree_find_exact_vector(nds_forest_front_at_const(self, rank), z)) return rank); + } + return (size_t)-1; // NOT FOUND +} + + +/* ------------------------------------------------------------------------- + * Insertion strategies + * ------------------------------------------------------------------------- */ + +/** + Returns rank == self->n || (rank < self->n && !nds_forest_dominates(self, rank, z)) +*/ +static inline size_t +nds_forest_find_insertion_linear(const NDSForest * restrict self, const double * restrict z) +{ + size_t rank = 0; + while (nds_forest_dominates(self, rank, z)) + rank++; + return rank; +} + +static inline size_t +nds_forest_find_insertion_bsearch(const NDSForest * restrict self, const double * restrict z, + size_t lowest, size_t highest) +{ + size_t low = lowest, high = highest; + while (low < high) { + size_t mid = low + (high - low) / 2; + if (nds_forest_dominates(self, mid, z)) + low = mid + 1; + else + high = mid; + } + assert((low == 0 && self->n == 0) + // z is dominated by highest - 1 + || (low == highest && nds_forest_dominates(self, low - 1, z)) + // z is dominated by low - 1, but not dominated by low + || (lowest < low && low < highest && nds_forest_dominates(self, low - 1, z) + && !nds_forest_dominates(self, low, z)) + // z is not dominated by anything in the range + || (lowest == low && !nds_forest_dominates(self, low, z))); + return low; +} + +static inline size_t +nds_forest_find_insertion_front_binary(const NDSForest * restrict self, const double * restrict z) +{ + return nds_forest_find_insertion_bsearch(self, z, 0, self->n); +} + +static inline size_t +nds_forest_find_insertion_previous_rank(const NDSForest * restrict self, const double * restrict z) +{ + if (self->n == 0) + return 0; + + assert(self->last_rank < self->n); + size_t rank = self->last_rank; + if (nds_forest_dominates(self, rank, z)) { + do { + rank++; + } while (rank < self->n && nds_forest_dominates(self, rank, z)); + } else { + while (rank > 0 && !nds_forest_dominates(self, rank - 1, z)) + rank--; + + assert((rank == 0 && !nds_forest_dominates(self, 0, z)) + || (rank > 0 && nds_forest_dominates(self, rank - 1, z))); + } + return rank; +} + +static inline size_t +nds_forest_find_insertion_zero_then_binary(const NDSForest * restrict self, const double * restrict z) +{ + return nds_forest_dominates(self, 0, z) + ? nds_forest_find_insertion_bsearch(self, z, 1, self->n) + : 0; +} + +/** + Bound binary search using dominance against the previously inserted point. +*/ +_attr_warn_unused_result +static inline int +nds_forest_insert_strategy_dominance_guided_binary(NDSForest * restrict self, const double * restrict z, const void * restrict x) +{ + Timer_t timer = nds_forest_timer_start(self); + + size_t rank; + if (unlikely(self->n == 0)) { + rank = 0; + } else if (weakly_dominates(z, self->last_objectives, self->dim)) { + if (unlikely(all_equal_double(z, self->last_objectives, self->dim))) { + assert(self->last_rank < self->n); + // There is no cascade here, so insert directly. + size_t last_rank = self->last_rank; + void *displaced = NULL; + nds_forest_timer_finish_query(self, &timer); + _attr_maybe_unused int res = + nds_forest_add_to_front(self, last_rank, z, x, /*check=*/false, &displaced); + nds_forest_timer_finish_update(self, &timer); + assert(nds_forest_front_unique_size(self, last_rank) > 0); + assert(res == ARCHIVE_INSERT_DUPLICATED && displaced == NULL); + return ARCHIVE_INSERT_DUPLICATED; + } + // new dominates previous. + assert(self->last_rank < self->n); + rank = nds_forest_dominates(self, 0, z) + ? nds_forest_find_insertion_bsearch(self, z, 1, self->last_rank + 1) + : 0; + assert(rank < self->n && !nds_forest_dominates(self, rank, z)); + ASSUME(rank < self->n); + } else if (weakly_dominates(self->last_objectives, z, self->dim)) { + assert(self->last_rank < self->n); + // previous weakly dominates new + rank = self->last_rank + 1; + if (nds_forest_dominates(self, rank, z)) + rank = nds_forest_find_insertion_bsearch(self, z, rank + 1, self->n); + } else { // previous and new are mutually nondominated + rank = nds_forest_find_insertion_zero_then_binary(self, z); + } + nds_forest_timer_finish_query(self, &timer); + int res = nds_forest_cascade(self, rank, z, x); + nds_forest_timer_finish_update(self, &timer); + return res; +} + +/* ------------------------------------------------------------------------- + * Top-level insertion entry point + * ------------------------------------------------------------------------- */ + +static inline int +nds_forest_add(NDSForest * restrict self, const double * restrict z, const void * restrict x) +{ + ASSUME(self->insertion_strategy < UNKNOWN_STRATEGY); + self->base.revision++; + + size_t rank; + int res; +#if DEBUG >= 1 + // All strategies should return the same rank. + rank = nds_forest_find_insertion_linear(self, z); + assert(rank == nds_forest_find_insertion_front_binary(self, z)); + assert(rank == nds_forest_find_insertion_previous_rank(self, z)); + assert(rank == nds_forest_find_insertion_zero_then_binary(self, z)); + res = nds_forest_insert_strategy_dominance_guided_binary(self, z, x); + assert(rank == self->last_rank); + return res; +#endif + + Timer_t timer; + if (self->insertion_strategy != DOMINANCE_GUIDED_BINARY) + timer = nds_forest_timer_start(self); + + switch (self->insertion_strategy) { + case LINEAR: + rank = nds_forest_find_insertion_linear(self, z); + break; + case FRONT_BINARY: + rank = nds_forest_find_insertion_front_binary(self, z); + break; + case PREVIOUS_RANK: + rank = nds_forest_find_insertion_previous_rank(self, z); + break; + case ZERO_THEN_BINARY: + rank = nds_forest_find_insertion_zero_then_binary(self, z); + break; + case DOMINANCE_GUIDED_BINARY: + return nds_forest_insert_strategy_dominance_guided_binary(self, z, x); + default: + return ARCHIVE_INSERT_UKNOWN_ERROR; + } + nds_forest_timer_finish_query(self, &timer); + res = nds_forest_cascade(self, rank, z, x); + nds_forest_timer_finish_update(self, &timer); + return res; +} + +NDSForestIterator * +nds_forest_iter_new(const NDSForest *forest) +{ + if (forest == NULL) + return NULL; + + NDSForestIterator * it = malloc(sizeof(*it)); + if (it == NULL) + return NULL; + + // Init the iterator + it->forest = forest; + it->front_index = 0; + it->revision = forest->base.revision; + NDS_FOREST_DISPATCH(forest, + it->treap_it = treap_archive_iter_new(nds_forest_front_at_const(forest, 0)), + it->ndtree_it = ndtree_iter_new(nds_forest_front_at_const(forest, 0))); + return it; +} + +void +nds_forest_iter_free(NDSForestIterator * it) +{ + if (it == NULL) + return; + NDS_FOREST_DISPATCH(it->forest, + treap_archive_iter_free(it->treap_it), + ndtree_iter_free(it->ndtree_it)); + free(it); +} + +/** + 1 next element returned + 0 end of iteration + -1 error +*/ +int +nds_forest_iter_next(NDSForestIterator * restrict it, size_t * restrict rank, + double * restrict z, const void ** restrict x) +{ + if (it == NULL || rank == NULL || z == NULL || it->revision != it->forest->base.revision) + return -1; + + int res; + NDS_FOREST_DISPATCH(it->forest, + res = treap_archive_iter_next(it->treap_it, z, x), + res = ndtree_iter_next(it->ndtree_it, z, x)); + if (res > 0) { + *rank = it->front_index; + return 1; + } + if (res == 0) { + it->front_index++; + if (it->front_index == it->forest->n) + return 0; + const void * front = nds_forest_front_at_const(it->forest, it->front_index); + NDS_FOREST_DISPATCH(it->forest, + treap_archive_iter_init(it->treap_it, front), + ndtree_iter_init(it->ndtree_it, front)); + NDS_FOREST_DISPATCH(it->forest, + res = treap_archive_iter_next(it->treap_it, z, x), + res = ndtree_iter_next(it->ndtree_it, z, x)); + *rank = it->front_index; + assert(res == 1); + return res; + } + return -1; +} + +#endif /* NDS_FOREST_H */ diff --git a/c/timer.c b/c/timer.c index 61bb4ab2c..da320b37c 100644 --- a/c/timer.c +++ b/c/timer.c @@ -12,10 +12,11 @@ #if DEBUG >= 1 #include #endif -#include /* for struct timeval */ -#ifndef WIN32 -#include /* for getrusage */ +#ifndef _WIN32 +#include // for struct timeval +#include // for getrusage #else +#include // for struct timeval /* getrusage Implementation according to: diff --git a/c/treap_archive.h b/c/treap_archive.h index 26581b7cb..e1ccac287 100644 --- a/c/treap_archive.h +++ b/c/treap_archive.h @@ -70,8 +70,19 @@ bool treap_archive_find_exact_vector(const TreapArchive * arch, const double * z VoidList * treap_archive_find_solutions_of_vector(const TreapArchive * arch, const double * z); typedef struct TreapIterator TreapIterator; +void treap_archive_iter_init(TreapIterator *it, const TreapArchive *arch); void treap_archive_iter_free(TreapIterator *it); TreapIterator * treap_archive_iter_new(const TreapArchive *arch); int treap_archive_iter_next(TreapIterator * restrict it, double * restrict z, const void ** restrict x); +/** + This is a wrapper for the API expected by nds_forest.h + +*/ +static inline int +treap_archive_insert_displaced_p(TreapArchive *arch, TreapArchive **incoming, bool *all_displaced) +{ + return treap_archive_insert_displaced(arch, *incoming, all_displaced); +} + #endif // TREAP_ARCHIVE_H diff --git a/python/benchmarks/bench_nds_forest.py b/python/benchmarks/bench_nds_forest.py new file mode 100644 index 000000000..70977aa6a --- /dev/null +++ b/python/benchmarks/bench_nds_forest.py @@ -0,0 +1,117 @@ +import itertools + +import matplotlib.pyplot as plt +import numpy as np +from bench import Bench + +import moocore + +datasets = { + "hypercube-uniform": lambda max_size, n_obj, rng: moocore.generate_sequence( + max_size, n_obj, method="cube", seed=rng + ), + "hypercube-uniform-rep4": lambda max_size, n_obj, rng: ( + moocore.generate_sequence( + int(max_size / 4), n_obj, method="cube", seed=rng, n_rep=max_size + ) + ), + "each-dominates-next": lambda max_size, n_obj, rng: ( + moocore.generate_sequence( + max_size, n_obj, method="each-dominates-next", seed=rng + ) + ), + "each-dominates-previous": lambda max_size, n_obj, rng: ( + moocore.generate_sequence( + max_size, n_obj, method="each-dominates-previous", seed=rng + ) + ), + "hypercube-ndsort=1": lambda max_size, n_obj, rng: ( + moocore.generate_sequence( + max_size, n_obj, method="cube", ndsort=1, seed=rng + ) + ), + "hypercube-ndsort=-1": lambda max_size, n_obj, rng: ( + moocore.generate_sequence( + max_size, n_obj, method="cube", ndsort=-1, seed=rng + ) + ), + "within-concave-sphere": lambda max_size, n_obj, rng: ( + moocore.generate_sequence( + max_size, n_obj, method="sphere", r_min=0.5, seed=rng + ) + ), + "glas2017,c=1": lambda max_size, n_obj, rng: moocore.generate_sequence( + max_size, n_obj, method="glas2017", c_value=1, seed=rng + ), + "glas2017,c=0.5": lambda max_size, n_obj, rng: moocore.generate_sequence( + max_size, n_obj, method="glas2017", c_value=0.5, seed=rng + ), + "glas2017,c=2.0": lambda max_size, n_obj, rng: moocore.generate_sequence( + max_size, n_obj, method="glas2017", c_value=2.0, seed=rng + ), +} + +n_repeats = 15 + +title = "Adding a point to the archive" +file_prefix = "nds_forest_add" +max_exp = {2: 18, 3: 17, 4: 12, 5: 17, 10: 17} +print(f"Running benchmark: {title}") +names = datasets.keys() +n_objs = [2, 3, 5, 10] +strategies = moocore.BaseNDSForest.RANK_QUERY_STRATEGIES +for n_obj, name in itertools.product(n_objs, names): + if n_obj == 2 and name.endswith("cliff"): + continue + test_archive_sizes = 2 ** np.arange(1, max_exp[n_obj]) + max_size = test_archive_sizes[-1] + + # This is a bit wasteful because we rebuild the archive from scratch for + # each size. On the other hand, it is probably less sensitive to noise. + setup = { + f"moocore ({strategy})": lambda z: { + "moa": moocore.NDSortedArchive(n_obj, query_strategy=strategy), + "z": z, + } + for strategy in strategies + } + + benchmarks = { + f"moocore ({strategy})": lambda moa, z: [moa.add(p) for p in z] + for strategy in strategies + } + # benchmarks["moocore (pareto_rank)"] = lambda z: moocore.pareto_rank(z) + + bench = Bench( + name=f"{name}-{n_obj}d", + n=test_archive_sizes, + bench=benchmarks, + setup=setup, + reps=1, + max_time=10, + baseline=next(iter(benchmarks)), + ) + + for r in range(n_repeats): + # We generate the dataset outside setup because we want to do it once + # per repetition, not once per benchmark. + rng = np.random.default_rng(42 + r) + z = datasets[name](max_size, n_obj, rng) + bench(lambda n: z[:n]) + + # Divide time by number of points, so that we report the average time per + # point for different input sizes. + normalise = set(benchmarks) + bench.normalise_times(normalise) + + bench.plots( + file_prefix=file_prefix, + title=title, + log="xy", + xlabel="Archive size", + logx_base=2, + show_ci=True, + ) + +if "__file__" not in globals(): # Running interactively. + plt.show() diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-10d-time.png new file mode 100644 index 000000000..cd5fe1d7c Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-2d-time.png new file mode 100644 index 000000000..d3d60589b Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-3d-time.png new file mode 100644 index 000000000..46f109d36 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-5d-time.png new file mode 100644 index 000000000..b4bcc8cca Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-next-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-10d-time.png new file mode 100644 index 000000000..8393a42b6 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-2d-time.png new file mode 100644 index 000000000..7f7437a41 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-3d-time.png new file mode 100644 index 000000000..5cc1a27da Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-5d-time.png new file mode 100644 index 000000000..3b71e537a Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-each-dominates-previous-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-10d-time.png new file mode 100644 index 000000000..a3be242f7 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-2d-time.png new file mode 100644 index 000000000..3f57b6da6 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-3d-time.png new file mode 100644 index 000000000..dbd041728 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-5d-time.png new file mode 100644 index 000000000..bfa4f5629 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=0.5-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-10d-time.png new file mode 100644 index 000000000..722d9a4c6 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-2d-time.png new file mode 100644 index 000000000..614ca338e Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-3d-time.png new file mode 100644 index 000000000..f6828e740 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-5d-time.png new file mode 100644 index 000000000..775ad541c Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=1-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-10d-time.png new file mode 100644 index 000000000..972d44dd0 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-2d-time.png new file mode 100644 index 000000000..c10dae130 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-3d-time.png new file mode 100644 index 000000000..7b4291400 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-5d-time.png new file mode 100644 index 000000000..4bf73eaf2 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-glas2017,c=2.0-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-10d-time.png new file mode 100644 index 000000000..3bead5081 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-2d-time.png new file mode 100644 index 000000000..97acf10b3 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-3d-time.png new file mode 100644 index 000000000..dc6595acc Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-5d-time.png new file mode 100644 index 000000000..ae2aefd86 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=-1-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-10d-time.png new file mode 100644 index 000000000..56a7a0d3c Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-2d-time.png new file mode 100644 index 000000000..6581f1f4e Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-3d-time.png new file mode 100644 index 000000000..39cd61115 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-5d-time.png new file mode 100644 index 000000000..54c506d55 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-ndsort=1-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-10d-time.png new file mode 100644 index 000000000..bfa1a5701 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-2d-time.png new file mode 100644 index 000000000..199b3bb49 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-3d-time.png new file mode 100644 index 000000000..4e800bb81 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-5d-time.png new file mode 100644 index 000000000..dfc95da14 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-10d-time.png new file mode 100644 index 000000000..383a6f191 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-2d-time.png new file mode 100644 index 000000000..bc005f261 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-3d-time.png new file mode 100644 index 000000000..c22db0f36 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-5d-time.png new file mode 100644 index 000000000..3b4562c93 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-hypercube-uniform-rep4-5d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-10d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-10d-time.png new file mode 100644 index 000000000..de11af919 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-10d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-2d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-2d-time.png new file mode 100644 index 000000000..3e418c700 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-2d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-3d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-3d-time.png new file mode 100644 index 000000000..4fde88dc9 Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-3d-time.png differ diff --git a/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-5d-time.png b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-5d-time.png new file mode 100644 index 000000000..443e81a1c Binary files /dev/null and b/python/doc/source/_static/bench/nds_forest_add_bench-within-concave-sphere-5d-time.png differ diff --git a/python/doc/source/benchmarks.inc.rst b/python/doc/source/benchmarks.inc.rst index 00460257b..f8cc1c5c6 100644 --- a/python/doc/source/benchmarks.inc.rst +++ b/python/doc/source/benchmarks.inc.rst @@ -289,6 +289,12 @@ Archiving Benchmarks See :ref:`Archiving Benchmarks `. +Non-Dominated Sorted Archiving Benchmarks +----------------------------------------- + +See :ref:`NDSortedArchive Benchmarks `. + + .. _BoFire: https://experimental-design.github.io/bofire/ .. _BoTorch: https://botorch.org/ .. _DEAP: https://deap.readthedocs.io/en/master/ diff --git a/python/doc/source/benchmarks_nds_archive.rst b/python/doc/source/benchmarks_nds_archive.rst new file mode 100644 index 000000000..69ff71fa5 --- /dev/null +++ b/python/doc/source/benchmarks_nds_archive.rst @@ -0,0 +1,196 @@ +:orphan: + +.. _benchmarks_nds_archive: + +########################## +NDSortedArchive Benchmarks +########################## + +The following plots benchmark the performance of +:func:`~moocore.NDSortedArchive` for various query strategies. + +The sequences are generated using :func:`~moocore.generate_ndset` and +:func:`~moocore.generate_sequence`. + +The source code for the benchmarks below can be found at +https://github.com/multi-objective/moocore/tree/main/python/benchmarks . + +Each archive is given the number of points in the x-axis, one at a time. We +measure the CPU time required to archive the whole sequence of points and +divide it by the number of points, which gives an estimation of the time to +process each point for different input sizes. + +2D +~~ + +|nds_forest_add_bench-each-dominates-next-2d-time| |nds_forest_add_bench-each-dominates-previous-2d-time| + +|nds_forest_add_bench-glas2017,c=0.5-2d-time| |nds_forest_add_bench-glas2017,c=1-2d-time| + +|nds_forest_add_bench-glas2017,c=2.0-2d-time| |nds_forest_add_bench-hypercube-ndsort=-1-2d-time| + +|nds_forest_add_bench-hypercube-ndsort=1-2d-time| |nds_forest_add_bench-hypercube-uniform-2d-time| + +|nds_forest_add_bench-hypercube-uniform-rep4-2d-time| |nds_forest_add_bench-within-concave-sphere-2d-time| + +.. |nds_forest_add_bench-each-dominates-next-2d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-next-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-each-dominates-previous-2d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-previous-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=0.5-2d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=0.5-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=1-2d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=1-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=2.0-2d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=2.0-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=-1-2d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=-1-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=1-2d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=1-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-2d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-rep4-2d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-rep4-2d-time.png + :width: 49% + +.. |nds_forest_add_bench-within-concave-sphere-2d-time| image:: _static/bench/nds_forest_add_bench-within-concave-sphere-2d-time.png + :width: 49% + + + +3D +~~ + +|nds_forest_add_bench-each-dominates-next-3d-time| |nds_forest_add_bench-each-dominates-previous-3d-time| + +|nds_forest_add_bench-glas2017,c=0.5-3d-time| |nds_forest_add_bench-glas2017,c=1-3d-time| + +|nds_forest_add_bench-glas2017,c=2.0-3d-time| |nds_forest_add_bench-hypercube-ndsort=-1-3d-time| + +|nds_forest_add_bench-hypercube-ndsort=1-3d-time| |nds_forest_add_bench-hypercube-uniform-3d-time| + +|nds_forest_add_bench-hypercube-uniform-rep4-3d-time| |nds_forest_add_bench-within-concave-sphere-3d-time| + +.. |nds_forest_add_bench-each-dominates-next-3d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-next-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-each-dominates-previous-3d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-previous-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=0.5-3d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=0.5-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=1-3d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=1-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=2.0-3d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=2.0-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=-1-3d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=-1-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=1-3d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=1-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-3d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-rep4-3d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-rep4-3d-time.png + :width: 49% + +.. |nds_forest_add_bench-within-concave-sphere-3d-time| image:: _static/bench/nds_forest_add_bench-within-concave-sphere-3d-time.png + :width: 49% + +5D +~~ + +|nds_forest_add_bench-each-dominates-next-5d-time| |nds_forest_add_bench-each-dominates-previous-5d-time| + +|nds_forest_add_bench-glas2017,c=0.5-5d-time| |nds_forest_add_bench-glas2017,c=1-5d-time| + +|nds_forest_add_bench-glas2017,c=2.0-5d-time| |nds_forest_add_bench-hypercube-ndsort=-1-5d-time| + +|nds_forest_add_bench-hypercube-ndsort=1-5d-time| |nds_forest_add_bench-hypercube-uniform-5d-time| + +|nds_forest_add_bench-hypercube-uniform-rep4-5d-time| |nds_forest_add_bench-within-concave-sphere-5d-time| + +.. |nds_forest_add_bench-each-dominates-next-5d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-next-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-each-dominates-previous-5d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-previous-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=0.5-5d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=0.5-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=1-5d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=1-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=2.0-5d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=2.0-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=-1-5d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=-1-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=1-5d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=1-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-5d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-rep4-5d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-rep4-5d-time.png + :width: 49% + +.. |nds_forest_add_bench-within-concave-sphere-5d-time| image:: _static/bench/nds_forest_add_bench-within-concave-sphere-5d-time.png + :width: 49% + + +10D +~~~ + +|nds_forest_add_bench-each-dominates-next-10d-time| |nds_forest_add_bench-each-dominates-previous-10d-time| + +|nds_forest_add_bench-glas2017,c=0.5-10d-time| |nds_forest_add_bench-glas2017,c=1-10d-time| + +|nds_forest_add_bench-glas2017,c=2.0-10d-time| |nds_forest_add_bench-hypercube-ndsort=-1-10d-time| + +|nds_forest_add_bench-hypercube-ndsort=1-10d-time| |nds_forest_add_bench-hypercube-uniform-10d-time| + +|nds_forest_add_bench-hypercube-uniform-rep4-10d-time| |nds_forest_add_bench-within-concave-sphere-10d-time| + +.. |nds_forest_add_bench-each-dominates-next-10d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-next-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-each-dominates-previous-10d-time| image:: _static/bench/nds_forest_add_bench-each-dominates-previous-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=0.5-10d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=0.5-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=1-10d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=1-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-glas2017,c=2.0-10d-time| image:: _static/bench/nds_forest_add_bench-glas2017,c=2.0-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=-1-10d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=-1-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-ndsort=1-10d-time| image:: _static/bench/nds_forest_add_bench-hypercube-ndsort=1-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-10d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-hypercube-uniform-rep4-10d-time| image:: _static/bench/nds_forest_add_bench-hypercube-uniform-rep4-10d-time.png + :width: 49% + +.. |nds_forest_add_bench-within-concave-sphere-10d-time| image:: _static/bench/nds_forest_add_bench-within-concave-sphere-10d-time.png + :width: 49% diff --git a/python/doc/source/conf.py b/python/doc/source/conf.py index f8ba49490..2bb920ea1 100644 --- a/python/doc/source/conf.py +++ b/python/doc/source/conf.py @@ -311,6 +311,10 @@ def setup(app): "MOOCORE_HVAPPROX_DIMENSION_MAX", ] } +CONSTANTS["RANK_QUERY_STRATEGIES"] = ", ".join( + f"``'{s}'``" + for s in moocore._nds_archive.BaseNDSForest.RANK_QUERY_STRATEGIES +) rst_epilog = "\n".join(f".. |{k}| replace:: {v}" for k, v in CONSTANTS.items()) diff --git a/python/doc/source/index.rst b/python/doc/source/index.rst index 9e5c57014..c4179cf34 100644 --- a/python/doc/source/index.rst +++ b/python/doc/source/index.rst @@ -24,12 +24,14 @@ moocore: Core Algorithms for Multi-Objective Optimization This webpage documents the ``moocore`` Python package. There is also a `moocore R package `_. -The goal of the **moocore** project (https://github.com/multi-objective/moocore/) is to collect and document fast implementations of core mathematical functions and algorithms for multi-objective optimization and make them available to different programming languages via similar interfaces. These functions include: +The goal of the **moocore** project (https://github.com/multi-objective/moocore/) is to collect and document fast implementations of core mathematical functions and algorithms for multi-objective optimization and make them available to different programming languages via similar interfaces. These functions and algorithms include: * :ref:`Generate and transform nondominated sets `. * :ref:`Identify and filter dominated vectors `. * :ref:`Quality metrics ` such as (weighted) hypervolume, epsilon, IGD+, (exact) R2, etc. * :ref:`Computation of the Empirical Attainment Function `. The empirical attainment function (EAF) describes the probabilistic distribution of the outcomes obtained by a stochastic algorithm in the objective space. +* :ref:`Archivers ` that allow efficiently storing a nondominated set, or sorted nondominated sets, from points given one-by-one as a sequence. + Most critical functionality is implemented in C, with the R and Python packages providing convenient interfaces to the C code. diff --git a/python/doc/source/reference/functions.archiving.rst b/python/doc/source/reference/functions.archiving.rst index 5dd46c607..01afe8458 100644 --- a/python/doc/source/reference/functions.archiving.rst +++ b/python/doc/source/reference/functions.archiving.rst @@ -16,3 +16,13 @@ Unbounded Archiving of a Nondominated Set UnboundedArchive BaseUnboundedArchive + + +Unbounded Archiving of Nondominated Sorted Sets +=============================================== + +.. autosummary:: + :toctree: generated/ + + NDSortedArchive + BaseNDSForest diff --git a/python/doc/source/whatsnew/index.rst b/python/doc/source/whatsnew/index.rst index 9913d3fe2..f02b0912c 100644 --- a/python/doc/source/whatsnew/index.rst +++ b/python/doc/source/whatsnew/index.rst @@ -15,6 +15,7 @@ Version 0.4.0 - `pygmo `_ is now included in the :ref:`bench-ndsort` and :ref:`bench-hv` benchmarks. - New unbounded nondominated archive :func:`~moocore.UnboundedArchive`. - New archiving benchmarks :ref:`benchmarks_archiving`. +- New unbounded nondominated sorted archive, :func:`~moocore.NDSortedArchive`. Version 0.3.2 (11/07/2026) diff --git a/python/src/moocore/__init__.py b/python/src/moocore/__init__.py index a870bda4b..ec344a459 100644 --- a/python/src/moocore/__init__.py +++ b/python/src/moocore/__init__.py @@ -40,6 +40,10 @@ whv_hype, whv_rect, ) +from ._nds_archive import BaseNDSForest as BaseNDSForest + +# The redundant alias silences a ruff warning. +from ._nds_archive import NDSortedArchive __version__ = _metadata_version("moocore") # Remove symbols imported for internal use @@ -48,6 +52,7 @@ __all__ = [ "Hypervolume", + "NDSortedArchive", "ReadDatasetsError", "RelativeHypervolume", "UnboundedArchive", diff --git a/python/src/moocore/_archive.py b/python/src/moocore/_archive.py index 11b951413..9c3c335a4 100644 --- a/python/src/moocore/_archive.py +++ b/python/src/moocore/_archive.py @@ -21,6 +21,9 @@ def _remember_handle(handles, what): class BaseArchive(ABC): _lib_archive_free: ClassVar[Callable[..., Any]] _lib_archive_has_x_values: ClassVar[Callable[..., Any]] + _lib_archive_iter_free: ClassVar[Callable[..., Any]] + _lib_archive_iter_new: ClassVar[Callable[..., Any]] + _lib_archive_iter_next: ClassVar[Callable[..., Any]] def __init__( self, diff --git a/python/src/moocore/_ffi_build.py b/python/src/moocore/_ffi_build.py index 4eece466b..2a2755809 100644 --- a/python/src/moocore/_ffi_build.py +++ b/python/src/moocore/_ffi_build.py @@ -32,6 +32,7 @@ #include "hvapprox.h" #include "treap_archive.h" #include "nd_tree.h" +#include "nds_forest.h" """ sources = [ "avl.c", @@ -51,6 +52,7 @@ "nondominated.c", "pareto.c", "rng.c", + "timer.c", "treap_archive.c", "treap2d_fixed_size.c", "whv.c", @@ -148,6 +150,7 @@ def _get_target_platforms() -> list[str]: # This is not done automatically by ffibuilder.compile(debug=True) ! DEBUG = int(os.environ.get("MOOCORE_DEBUG", DEBUG)) if DEBUG >= 1: + # Use these for debugging, but they are too slow for running the testsuite. debug_flags = ["-Og", "-g3", "-fno-lto", "-Werror"] cflags += debug_flags ldflags += debug_flags diff --git a/python/src/moocore/_nds_archive.py b/python/src/moocore/_nds_archive.py new file mode 100644 index 000000000..e5744fb8a --- /dev/null +++ b/python/src/moocore/_nds_archive.py @@ -0,0 +1,541 @@ +from collections.abc import Iterator, Sequence # For type hints +from typing import Any, ClassVar, Final + +import numpy as np +from numpy.typing import ArrayLike # For type hints + +from ._archive import ( + BaseArchive, + BaseUnboundedArchive, + NDTreeArchive, + TreapArchive, + _remember_handle, +) +from ._docsubstitute import DocSubstitute + +## The CFFI library is used to create C bindings. +from ._libmoocore import ffi, lib # ty: ignore[import-not-found] +from ._utils import _as_2d_float_array + + +class BaseNDSForest(BaseArchive): + """Interface implemented by objects returned by :func:`NDSortedArchive`. + + This class defines the common interface for ``BaseNDSForest`` objects. It is + not intended to be instantiated directly; use :func:`NDSortedArchive` to + create an NDS archive. + + """ + + # Derived classes must define these. + _ArchiveClass: ClassVar[BaseUnboundedArchive] + + _lib_archive_free = lib.nds_forest_free + + # This must be keep synchronized with enum nds_forest_insertion_strategy_t. + # When the minimum version is Python 3.15, use a frozendict. + _strategy_to_c_enum: Final[dict[str, int]] = { + "linear": lib.LINEAR, + "front-binary": lib.FRONT_BINARY, + "previous-rank": lib.PREVIOUS_RANK, + "zero-then-binary": lib.ZERO_THEN_BINARY, + "dominance-guided-binary": lib.DOMINANCE_GUIDED_BINARY, + } + RANK_QUERY_STRATEGIES: Final[tuple[str, ...]] = tuple( + _strategy_to_c_enum.keys() + ) + """Names of the supported query strategies.""" + + def __init__( + self, + dim: int, + *, + maximise: bool | Sequence[bool], + query_strategy: str, + has_x_values: bool, + do_timings: bool, + ): + self.do_timings = do_timings + self.query_strategy = query_strategy + if query_strategy not in self.RANK_QUERY_STRATEGIES: + raise ValueError( + "'query_strategy' must be one of: " + + ", ".join(sorted(self.RANK_QUERY_STRATEGIES)) + ) + + # self._c_archive is setup by super().__init__(). + super().__init__( + dim=dim, + maximise=maximise, + keep_duplicates=True, + has_x_values=has_x_values, + ) + + def __len__(self) -> int: + """Return the total number of stored points across all fronts.""" + return sum(self.fronts_total_sizes()) + + @property + def len_fronts(self) -> int: + """Return the number of fronts.""" + return lib.nds_forest_len(self._c_archive) + + def _last_rank(self) -> int: + return lib.nds_forest_last_rank(self._c_archive) + + def _check_rank(self, rank): + if rank < 0 or rank >= self.len_fronts: + raise ValueError(f"invalid rank: {rank}") + + def front_total_size(self, rank: int) -> int: + """Return the total size of a front (including duplicated points).""" + self._check_rank(rank) + return lib.nds_forest_front_total_size(self._c_archive, rank) + + def front_unique_size(self, rank: int) -> int: + """Return the number of unique points in a front.""" + self._check_rank(rank) + return lib.nds_forest_front_unique_size(self._c_archive, rank) + + def fronts_total_sizes(self) -> list[int]: + """Return the number of total points stored in each front.""" + return [self.front_total_size(rank) for rank in range(self.len_fronts)] + + def fronts_unique_sizes(self) -> list[int]: + """Return the number of unique points stored in each front.""" + return [self.front_unique_size(rank) for rank in range(self.len_fronts)] + + def get_timings(self) -> tuple[float, float]: + """ + Return query/update times (if timing is enabled). + + Returns + ------- + A tuple ``(query_time, update_time)`` if the archive was created with ``do_timings=True``. Otherwise, raise ``ValueError``. + + """ + if not self.do_timings: + raise ValueError("This archive was created with `do_timings=False`") + query_time_p = ffi.new("double *") + update_time_p = ffi.new("double *") + lib.nds_forest_get_timings(self._c_archive, query_time_p, update_time_p) + return query_time_p[0], update_time_p[0] + + # FIXME: We should also have: + # def dominates(self, objectives): + # def dominated_by(self, objectives): + + # FIXME: add options return_x_values, return_n to return x values and/or number of duplicates. + def index(self, objectives) -> int: + """Return the index of the front (rank) that contains ``objectives``. Raises ``ValueError`` if not found, similar to ``list.index()``.""" + z_c = self._objectives_to_c(objectives) + rank = lib.nds_forest_find_exact_vector(self._c_archive, z_c) + if rank < self.len_fronts: + return rank + raise ValueError("Objective vector not found") + + def __contains__(self, z): + """Return true if the given objective vector is archived.""" + # FIXME: This is similar to self.index(z) but we do not need to catch the exception. + z_c = self._objectives_to_c(z) + rank = lib.nds_forest_find_exact_vector(self._c_archive, z_c) + return rank < self.len_fronts + + def front_dominated_by(self, rank, objectives): + """Return ``True`` if all points in the ``rank``-th front are dominated by ``z``.""" + self._check_rank(rank) + z_c = self._objectives_to_c(objectives) + return lib.nds_forest_dominated_by(self._c_archive, rank, z_c) + + def front_dominates(self, rank, z) -> bool: + """Return ``True`` if the ``rank``-th front dominates ``z``.""" + self._check_rank(rank) + z_c = self._objectives_to_c(z) + return lib.nds_forest_dominates(self._c_archive, rank, z_c) + + def add(self, objectives: ArrayLike, x: Any = None) -> int: + """Insert a point in the archive and return its Pareto rank. + + This operation always succeeds if there is enough memory. Adding the + new point may increase the number of fronts. + + This operation stores a copy of ``objectives``, so modifying it after + adding it does not change the copy stored in the archive. This + operation does not copy ``x`` only a reference to it, so modifying it + after the call does change the copy stored in the archive. + + """ + z_c, x_c = self._prepare_to_insert(objectives, x) + if lib.nds_forest_add(self._c_archive, z_c, x_c) < 0: + raise MemoryError + return self._last_rank() + + def add_many( + self, z: ArrayLike, x: Sequence[Any] | None = None + ) -> list[int]: + """Add several points sequentially and return the rank of each point when it was inserted. + + Since the points are added sequentially, later points may change the + insertion rank of earlier ones. + """ + # FIXME: We could call pareto_rank on the input sequence to insert the + # points in an order that ensures no changes of rank, then resort the + # ranks returned to match the original order of the points. + z = _as_2d_float_array(z, dim=self.dim) + x = [None] * len(z) if x is None else list(x) + if len(x) != len(z): + raise ValueError( + "'x' must be either None or a list with one value per input vector" + ) + return [self.add(point, x[index]) for index, point in enumerate(z)] + + def __repr__(self) -> str: + z, x = self.get_contents() + if x is None: + return str(z) + return f"{z}\nx = {x}" + + def get_contents(self) -> tuple[list, list | None]: + """Return the full contents of the archive. + + Returns + ------- + Tuple with two elements. The first element is a list of Numpy arrays, each element are the objective vectors of each front. These are copies, so they can be modified without affecting the archive. The second element is a list (or ``None`` if ``not self.has_x_values()``), one per front, where each element is a list of x values. These are references, so modifying them does modify the objects stored in the archive. + + """ + z_list = [None] * self.len_fronts + if self.has_x_values(): + x_list = [None] * self.len_fronts + for rank in range(self.len_fronts): + z_list[rank], x_list[rank] = self._c_get_contents( + lib.nds_forest_front_at(self._c_archive, rank) + ) + return z_list, x_list + + for rank in range(self.len_fronts): + z_list[rank], _ = self._c_get_contents( + lib.nds_forest_front_at(self._c_archive, rank) + ) + return z_list, None + + def get_unique_vectors(self) -> list[np.ndarray]: + """Return the unique objective vectors stored in the archive. + + This function returns copies that can be safely modified without affecting the archive. + """ + return [ + self._c_get_unique_vectors( + lib.nds_forest_front_at(self._c_archive, rank) + ) + for rank in range(self.len_fronts) + ] + + def get_x_values(self) -> list[list[Any]]: + """Return the x-values stored in the archive.""" + return [ + self._ArchiveClass._c_get_x_values( + lib.nds_forest_front_at(self._c_archive, rank) + ) + for rank in range(self.len_fronts) + ] + + def _c_get_contents(self, c_front): + return self._ArchiveClass._c_get_contents( + c_front, dim=self.dim, minmax=self._minmax + ) + + def _c_get_unique_vectors(self, c_front): + return self._ArchiveClass._c_get_unique_vectors( + c_front, dim=self.dim, minmax=self._minmax + ) + + def _prepare_to_insert(self, z: ArrayLike, x: Any): + """Prepare objectives and x for insertion in the C structure.""" + # The C code will copy the z vectors but not the x objects. + z_c = self._objectives_to_c(z) + + if x is None: + x_c = ffi.NULL + else: + x_c = ffi.new_handle(x) + _remember_handle(self._x_handles, x_c) + + return z_c, x_c + + def __iter__(self) -> Iterator[tuple[int, np.ndarray, Any]]: + """Return front indexes, z vectors and, if available, their associated x object one at a time. + + The z vectors are copies so modifying them does not modify the archive. + However, for efficiency, iterating does not make copies of the objects. + + Modifying the archive while iterating raises a :exc:`RuntimeError`. + """ + if self.len_fronts == 0: + return + + it = lib.nds_forest_iter_new(self._c_archive) + if it == ffi.NULL: + raise MemoryError("failed to create iterator") + it = ffi.gc(it, lib.nds_forest_iter_free) + try: + rank = ffi.new("size_t *") + z = np.empty(self._dim) + z_c = ffi.from_buffer("double []", z) + x = ffi.new("const void **") if self.has_x_values() else ffi.NULL + while True: + rc = lib.nds_forest_iter_next(it, rank, z_c, x) + if rc == 1: + x_handle = None if x == ffi.NULL else ffi.from_handle(x[0]) + # Return a copy of z, so that list(self) works as expected. + yield rank[0], z.copy(), x_handle + elif rc == 0: + break + else: + raise RuntimeError( + "invalid 'BaseNDSForest' iterator, did you modify the archive?" + ) + finally: + # lib.nds_forest_iter_free() needs the archive to be alive, but it + # is possible that Python frees 'self' before 'it', so we + # explicitly free the iterator while this frame still retains self. + ffi.release(it) + + def has_x_values(self) -> bool: + """Return true if the archive stores 'x' values.""" + if self.len_fronts == 0: + return False + return self._ArchiveClass._lib_archive_has_x_values( + lib.nds_forest_front_at(self._c_archive, 0) + ) + + +class NDSForestNDTree(BaseNDSForest): + """Ranked Pareto fronts backed by the C specialised 2D treap front.""" + + _ArchiveClass: Final = NDTreeArchive + + def __init__( + self, + dim: int, + *, + maximise: bool | Sequence[bool], + query_strategy: str, + max_children: int = 0, + max_bucket_size: int = 0, + has_x_values: bool, + do_timings: bool, + ): + """Create a NDS-Forest archive using ND-Trees.""" + self.max_children, self.max_bucket_size = ( + NDTreeArchive._get_default_config( + dim, max_children, max_bucket_size + ) + ) + super().__init__( + dim=dim, + maximise=maximise, + query_strategy=query_strategy, + has_x_values=has_x_values, + do_timings=do_timings, + ) + + def _setup_c_archive(self, keep_duplicates: bool, has_x_values: bool): + strategy = self._strategy_to_c_enum[self.query_strategy] + x_is_null = not has_x_values + return lib.nds_forest_ndtree_new( + self.dim, + strategy, + self.max_children, + self.max_bucket_size, + x_is_null, + self.do_timings, + ) + + +class NDSForestTreap(BaseNDSForest): + """Ranked Pareto fronts backed by the C specialised 2D treap front.""" + + _ArchiveClass: Final = TreapArchive + + def __init__( + self, + maximise: bool | Sequence[bool], + query_strategy: str, + has_x_values: bool, + do_timings: bool, + ): + """Create an empty C-accelerated 2D ranked-front archive.""" + super().__init__( + dim=2, + maximise=maximise, + query_strategy=query_strategy, + has_x_values=has_x_values, + do_timings=do_timings, + ) + + def _setup_c_archive(self, keep_duplicates: bool, has_x_values: bool): + strategy = self._strategy_to_c_enum[self.query_strategy] + x_is_null = not has_x_values + return lib.nds_forest_treap_new(strategy, x_is_null, self.do_timings) + + +@DocSubstitute() +def NDSortedArchive( # noqa: N802 + dim: int, + *, + maximise: bool | Sequence[bool] = False, + query_strategy: str = "zero-then-binary", + max_children: int = 0, + max_bucket_size: int = 0, + has_x_values: bool = False, + do_timings: bool = False, +) -> BaseNDSForest: + """Build an unbounded-size nondominated sorted archive. The type of archive built depends on dim. + + A nondominated sorted archive is a data structure that stores multiple nondominated sets (i.e., `fronts`) and allows efficient updates with new points. The sets are sorted according to Pareto rank (see :func:`~moocore.pareto_rank`), that is, each point in the archive is associated to the set whose 0-based index is given by nondominating sorting the whole archive. When a new point is added, the point is assigned to the set with the smallest index that does not contain any point dominating the new point. If such set does not exist, the point is added to a new set with index equal to the number of sets in the archive, thus increasing the number of sets in the archive. Points are never rejected by this archive. Duplicated points are always accepted. + + These archives are unbounded, that is, there is no limit in the number of nondominated points that can be stored in the archive. + + The archive can optionally store an arbitrary Python object associated to each point. Duplicated points may be associated to different Python objects. + + When :code:`dim = 2`, the archive is based on a treap data structure :footcite:p:`AraSei1989rst`. + When :code:`dim > 2`, the archive is based on a ND-Tree :footcite:p:`JasLus2018ndtree`. + + Parameters + ---------- + dim : + ${dim} + maximise : + ${maximise} + query_strategy : + Strategy when searching for the insertion front. Valid values are given by :py:const:`BaseNDSForest.RANK_QUERY_STRATEGIES`: |RANK_QUERY_STRATEGIES|. + max_children : + Maximum number of children used in the ND-Tree (only when :code:`dim > 2`). + max_bucket_size : + Maximum number of solutions stored in each leaf of the ND-Tree (only when :code:`dim > 2`). + has_x_values : + Whether the archive will store a Python object (`x`-value) for each input point (i.e., objective vector). + do_timings : + Measure query and update time for NDS-Forest. The values can be retrieved using :func:`~moocore.BaseNDSForest.get_timings`. + Timing adds some overhead, so it must be explicitly enabled. + + + Returns + ------- + Abstract base class that documents the methods available. + + + See Also + -------- + BaseNDSForest: documents the methods available. + + + References + ---------- + .. footbibliography:: + + Examples + -------- + >>> arch = NDSortedArchive(dim=2, has_x_values=True) + >>> arch.add_many( + ... [ + ... [0, 0], + ... [2, 0], + ... [ + ... 3, + ... 3, + ... ], + ... [2, 0], + ... ], + ... x=["a", "b", "c", "d"], + ... ) + [0, 1, 2, 1] + >>> len(arch) + 4 + >>> arch.len_fronts + 3 + >>> arch.fronts_total_sizes() + [1, 2, 1] + >>> arch.fronts_unique_sizes() + [1, 1, 1] + >>> arch.add([5, 5], x="e") + 3 + >>> arch + [array([[0., 0.]]), array([[2., 0.], + [2., 0.]]), array([[3., 3.]]), array([[5., 5.]])] + x = [['a'], ['b', 'd'], ['c'], ['e']] + + We can test whether an objective vector has been archived using the ``in`` operator or use ``index()`` to find its rank. + + >>> [3, 3] in arch + True + >>> arch.index([3, 3]) + 2 + >>> [1, 1] in arch + False + >>> arch.index([1, 1]) # doctest: +IGNORE_EXCEPTION_DETAIL +ELLIPSIS + Traceback (most recent call last): + ValueError: ... + + We can also dump the contents of the archive: + + >>> arch.get_contents() + ([array([[0., 0.]]), array([[2., 0.], + [2., 0.]]), array([[3., 3.]]), array([[5., 5.]])], [['a'], ['b', 'd'], ['c'], ['e']]) + >>> arch.get_unique_vectors() + [array([[0., 0.]]), array([[2., 0.]]), array([[3., 3.]]), array([[5., 5.]])] + >>> arch.get_x_values() + [['a'], ['b', 'd'], ['c'], ['e']] + >>> for rank, z, x in arch: + ... print(f"front {rank}: {x} -> {z}") + front 0: a -> [0. 0.] + front 1: b -> [2. 0.] + front 1: d -> [2. 0.] + front 2: c -> [3. 3.] + front 3: e -> [5. 5.] + + The archive can handle maximisation and minimisation objectives: + + >>> arch = NDSortedArchive(dim=3, maximise=[False, True, False]) + >>> arch.add_many([[10, 10, 10], [9, 9, 10], [0, 0, 0]]) + [0, 0, 0] + >>> arch.add([10, 9, 10]) + 1 + >>> arch + [array([[10., 10., 10.], + [ 9., 9., 10.], + [ 0., 0., 0.]]), array([[10., 9., 10.]])] + + + Enable timing of the archive operations: + + >>> arch = NDSortedArchive(dim=2, do_timings=True) + >>> x = np.random.uniform(size=(5000, 2)) + >>> res = arch.add_many(x) + >>> query_time, update_time = arch.get_timings() + >>> print( + ... f"query_time = {query_time}, update_time = {update_time}" + ... ) # doctest: +ELLIPSIS + query_time = 0.0..., update_time = 0.0... + """ + if dim > 2: + return NDSForestNDTree( + dim, + maximise=maximise, + query_strategy=query_strategy, + max_children=max_children, + max_bucket_size=max_bucket_size, + has_x_values=has_x_values, + do_timings=do_timings, + ) + if dim == 2: + return NDSForestTreap( + maximise=maximise, + query_strategy=query_strategy, + has_x_values=has_x_values, + do_timings=do_timings, + ) + if dim < 2: + raise ValueError("'dim' cannot be smaller than 2") + + raise NotImplementedError("This type of archive is not implemented yet") diff --git a/python/src/moocore/libmoocore.h b/python/src/moocore/libmoocore.h index e7e7c526f..7c5367b48 100644 --- a/python/src/moocore/libmoocore.h +++ b/python/src/moocore/libmoocore.h @@ -148,6 +148,36 @@ NDTreeIterator *ndtree_iter_new(const NDTreeArchive *); int ndtree_iter_next(NDTreeIterator *it, double *z, const void **x); void ndtree_iter_free(NDTreeIterator *it); +// nds_forest.h +typedef enum nds_forest_insertion_strategy_t { + LINEAR = ..., + FRONT_BINARY, + PREVIOUS_RANK, + ZERO_THEN_BINARY, + DOMINANCE_GUIDED_BINARY, + UNKNOWN_STRATEGY +}; + +typedef struct NDSForest NDSForest; +NDSForest * nds_forest_ndtree_new(dimension_t dim, enum nds_forest_insertion_strategy_t strategy, + uint8_t max_children, uint8_t max_bucket_size, + bool x_is_null, bool do_timing); +NDSForest * nds_forest_treap_new(enum nds_forest_insertion_strategy_t strategy, bool x_is_null, bool do_timing); +void nds_forest_free(NDSForest *self); +void nds_forest_get_timings(const NDSForest * self, double * query_time, double * update_time); +size_t nds_forest_len(const NDSForest *self); +size_t nds_forest_last_rank(const NDSForest *self); +void * nds_forest_front_at(NDSForest *self, size_t rank); +size_t nds_forest_front_total_size(const NDSForest *self, size_t rank); +size_t nds_forest_front_unique_size(const NDSForest *self, size_t rank); +bool nds_forest_dominates(const NDSForest *self, size_t rank, const double *z); +bool nds_forest_dominated_by(const NDSForest *self, size_t rank, const double *z); +int nds_forest_add(NDSForest *self, const double *z, const void *x); +size_t nds_forest_find_exact_vector(const NDSForest * restrict self, const double * restrict z); +typedef struct NDSForestIterator NDSForestIterator; +NDSForestIterator * nds_forest_iter_new(const NDSForest *forest); +void nds_forest_iter_free(NDSForestIterator * it); +int nds_forest_iter_next(NDSForestIterator * it, size_t * rank, double *z, const void **x); /* typedef ... hype_sample_dist; diff --git a/python/tests/test_nds_archiving.py b/python/tests/test_nds_archiving.py new file mode 100644 index 000000000..402981ce4 --- /dev/null +++ b/python/tests/test_nds_archiving.py @@ -0,0 +1,128 @@ +# ruff: noqa: D100, D103, N802 +import os + +import numpy as np +import pytest +from numpy.testing import ( + assert_array_equal, +) + +import moocore + + +def no_print(x): + return + + +RANK_QUERY_STRATEGIES = moocore._nds_archive.BaseNDSForest.RANK_QUERY_STRATEGIES + + +def rank_query_strategies(): + if os.environ.get("MOOCORE_SKIP_SLOW_TESTS") == "1": + return RANK_QUERY_STRATEGIES[:1] + return RANK_QUERY_STRATEGIES + + +@pytest.fixture(scope="module", params=[(1000, 2), (1000, 3), (1000, 10)]) +def generate_points(request): + n, d = request.param + seed = np.random.default_rng().integers(2**32 - 2) + print(f"seed={seed}") + rng = np.random.default_rng(seed) + array = rng.integers(0, 100, (n, d)) + array.flags.writeable = False + return array + + +@pytest.fixture(scope="module") +def pareto_rank_front_sizes(generate_points): + points = generate_points + ranks = moocore.pareto_rank(points) + # FIXME: Use fronts to test exact equality of results. + # FIXME: Is there a faster way to generate the front sizes? + ## fronts = [points.compress((g == ranks), axis=0) for g in np.unique(ranks)] + _, counts = np.unique_counts(ranks) + return counts + + +@pytest.mark.parametrize("strategy", rank_query_strategies()) +def test_NDSortedArchive_random( + strategy, generate_points, pareto_rank_front_sizes +): + points = generate_points + expected = pareto_rank_front_sizes + nds_archive = moocore.NDSortedArchive( + dim=points.shape[1], query_strategy=strategy, has_x_values=True + ) + for i, p in enumerate(points): + no_print(f"p = {p}") + nds_archive.add(p, x=i) + + nds_sizes = nds_archive.fronts_total_sizes() + assert_array_equal(expected, nds_sizes) + + +@pytest.mark.parametrize("strategy", rank_query_strategies()) +def test_NDSortedArchive(strategy): + arch = moocore.NDSortedArchive(dim=2, query_strategy=strategy) + + def assert_add(arch, z, rank, total_sizes): + assert arch.add(z) == rank + assert_array_equal(arch.fronts_total_sizes(), total_sizes) + + assert_add(arch, [1, 1], 0, [1]) + assert_add(arch, [2, 2], 1, [1, 1]) + assert_add(arch, [0, 3], 0, [2, 1]) + assert_add(arch, [3, 0], 0, [3, 1]) + assert_add(arch, [9, 1], 1, [3, 2]) + assert_add(arch, [1, 9], 1, [3, 3]) + assert_add(arch, [2, 0], 0, [3, 3, 1]) + assert_add(arch, [0, 2], 0, [3, 3, 2]) + assert_add(arch, [0, 0], 0, [1, 3, 3, 2]) + assert_add(arch, [0, 0], 0, [2, 3, 3, 2]) + assert_array_equal(arch.fronts_unique_sizes(), [1, 3, 3, 2]) + + +@pytest.mark.parametrize("dim", [2, 3]) +def test_invalid_iterator(dim): + archive = moocore.NDSortedArchive(dim) + rng = np.random.default_rng() + n = 5 + z = rng.uniform(size=(n, dim)) + archive.add_many(z) + with pytest.raises(RuntimeError, match=r"invalid 'BaseNDSForest' iterator"): + for r, z, x in archive: + archive.add(np.full(dim, 1)) + + # The archive was modified. + assert len(archive) == n + 1 + + # Test that the iterator keeps the archive alive. + iterator = iter(archive) + del archive + r, z, x = next(iterator) + assert r < n + 1 + assert len(z) == dim + assert x is None + + +@pytest.mark.parametrize("dim", [2, 3]) +def test_conversion_to_list(dim): + archive = moocore.NDSortedArchive(dim) + n = 5 + z = np.arange(n) + z = np.full(dim, 1) * z[:, np.newaxis] + archive.add_many(z) + res = [] + for r, z, x in archive: + res.append((r, z.copy(), x)) + + res2 = list(archive) + + def archive_lists_equal(list1, list2): + return len(list1) == len(list2) and all( + r1 == r2 and np.array_equal(z1, z2) and x1 == x2 + for (r1, z1, x1), (r2, z2, x2) in zip(list1, list2) + ) + + assert archive_lists_equal(res, res2) diff --git a/python/tox.ini b/python/tox.ini index b31ac98fb..c27726650 100644 --- a/python/tox.ini +++ b/python/tox.ini @@ -16,7 +16,7 @@ extras = test cov: coverage commands = - pytest --doctest-modules --doctest-continue-on-failure --import-mode=importlib {envsitepackagesdir}/moocore tests + pytest --doctest-modules --doctest-continue-on-failure --import-mode=importlib {envsitepackagesdir}/moocore tests {posargs} [testenv:report] skip_install = true