Alien-libhisto

 view release on metacpan or  search on metacpan

bundled/tools/src/cmd_cmp.c  view on Meta::CPAN

/*
 * CLI subcommand histo cmp: two-sample statistical distance computations.
 */

#include "cli_common.h"
#include "cli_opt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>

int histo_cli_cmp(int argc, char **argv, FILE *out, FILE *err) {
    if (!out) out = stdout;
    if (!err) err = stderr;

    const char *fmt = "table";

    const cli_opt_spec_t specs[] = {
        {'f', "format", NULL, CLI_OPT_TYPE_STRING, &fmt, NULL, 0, "FMT",
         "Output format: table (default), json, tsv", "table"}
    };

    cli_opt_parser_t parser;
    cli_opt_init(&parser, specs, sizeof(specs) / sizeof(specs[0]),
                 "histo-cmp", "[OPTIONS] <HISTO_A> <HISTO_B>",
                 "Compares two histograms and computes statistical distance metrics and compatibility.");

    int rc = cli_opt_parse(&parser, argc, argv, 1);
    if (rc < 0) {
        cli_opt_print_help(&parser, out);
        cli_opt_free(&parser);
        return 0;
    }
    if (rc > 0) {
        fprintf(err, "%s\n", cli_opt_error(&parser));
        cli_opt_free(&parser);
        return 1;
    }

    if (parser.num_positionals < 2) {
        fprintf(err, "Error: Two histogram input paths are required.\n\n");
        cli_opt_print_help(&parser, err);
        cli_opt_free(&parser);
        return 1;
    }

    const char *path1 = parser.positionals[0];
    const char *path2 = parser.positionals[1];

    histo_t *h1 = NULL;
    histo_t *h2 = NULL;

    if (cli_read_histogram_from_file(path1, &h1) != HISTO_OK) {
        fprintf(err, "Error: Failed to read first histogram from '%s'\n", path1);
        cli_opt_free(&parser);
        return 1;
    }
    if (cli_read_histogram_from_file(path2, &h2) != HISTO_OK) {
        fprintf(err, "Error: Failed to read second histogram from '%s'\n", path2);
        histo_destroy(h1);
        cli_opt_free(&parser);
        return 1;
    }

    double chi2 = 0.0;
    uint32_t ndf = 0;
    double ks = 0.0;
    double w1 = 0.0;
    double kl = 0.0;
    double bhat = 0.0;

    histo_cmp_chi2(h1, h2, &chi2, &ndf);
    histo_cmp_ks(h1, h2, &ks);
    histo_cmp_wasserstein_1d(h1, h2, &w1);



( run in 0.961 second using v1.01-cache-2.11-cpan-5c0b1e786e0 )