/*
 *  $Id: neural.c 30047 2026-06-11 08:30:45Z yeti-dn $
 *  Copyright (C) 2012-2026 David Necas (Yeti), Petr Klapetek.
 *  E-mail: yeti@gwyddion.net, klapetek@gwyddion.net.
 *
 *  This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 *  License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any
 *  later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 *  details.
 *
 *  You should have received a copy of the GNU General Public License along with this program; if not, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <glib/gi18n-lib.h>
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gwy.h>
#include "neuraldata.h"
#include "../preview.h"

#define RUN_MODES GWY_RUN_INTERACTIVE

enum {
    RESPONSE_TRAIN = GWY_RESPONSE_USER,
    RESPONSE_REINITIALIZE,
};

enum {
    /* Module parameters. */
    PARAM_MODEL,
    PARAM_SIGNAL,
    PARAM_TRAINSTEPS,
    PARAM_MASKING,
    PARAM_SCALE_OUTPUT,
    PARAM_NAME,
    PARAM_PREVIEW,

    BUTTON_TRAIN,
    BUTTON_REINITIALIZE,
    MESSAGE_TRAINING,

    /* Neural network parameters (not all are actually meaningful at present). */
    PARAM_WIN_WIDTH,
    PARAM_WIN_HEIGHT,
    PARAM_NLAYERS,
    PARAM_NHIDDEN,
    PARAM_NOUTPUT,
    PARAM_INPOWER_XY,
    PARAM_INPOWER_Z,
    PARAM_OUTUNITS,
};

typedef enum {
    PREVIEW_MODEL,
    PREVIEW_SIGNAL,
    PREVIEW_RESULT,
    PREVIEW_DIFFERENCE,
} PreviewType;

enum {
    NETWORK_NAME = 0,
    NETWORK_SIZE,
    NETWORK_HIDDEN,
    NETWORK_LAST,
};

typedef struct {
    GwyParams *params;
    GwyNeuralNetwork *nn;
} NeuralTrainArgs;

typedef struct {
    NeuralTrainArgs *args;
    gboolean calculated;
    gboolean compatible;
    gboolean loading_network;
    GwyParamTable *table_training;
    GwyParamTable *table_network;
    GwyField *result;
    GwyField *diff;
    GtkWidget *dialog;
    GtkWidget *dataview;
    GwyGraphModel *gmodel;
    /* Network list */
    GwyInventoryStore *store;
    GtkWidget *networklist;
    GtkWidget *load;
    GtkWidget *save;
    GtkWidget *rename;
    GtkWidget *delete;
    GtkWidget *networkname;
} NeuralTrainGUI;

typedef struct {
    GwyParams *params;
    GwyField *field;
    GwyField *result;
    /* This is the actual resource. */
    GwyNeuralNetwork *nn;
} NeuralApplyArgs;

typedef struct {
    NeuralApplyArgs *args;
    GtkWidget *dialog;
    GwyInventoryStore *store;
    GtkWidget *networklist;
    GtkWidget *scale_output;
} NeuralApplyGUI;

static gboolean          module_register            (void);
static void              neural_train               (GwyFile *data,
                                                     GwyRunModeFlags mode);
static void              neural_apply               (GwyFile *data,
                                                     GwyRunModeFlags mode);
static GwyDialogOutcome  run_gui_train              (NeuralTrainArgs *args);
static GwyDialogOutcome  run_gui_apply              (NeuralApplyArgs *args);
static gboolean          execute_apply              (NeuralApplyArgs *args,
                                                     GwyFile *data,
                                                     gint id);
static gboolean          can_select_network         (GtkTreeSelection *selection,
                                                     GtkTreeModel *model,
                                                     GtkTreePath *path,
                                                     gboolean path_currently_selected,
                                                     gpointer data);
static void              param_changed              (NeuralTrainGUI *gui,
                                                     gint id);
static void              dialog_response            (NeuralTrainGUI *gui,
                                                     gint response);
static GtkWidget*        training_tab_new           (NeuralTrainGUI *gui);
static GtkWidget*        parameters_tab_new         (NeuralTrainGUI *gui);
static GtkWidget*        networks_tab_new           (NeuralTrainGUI *gui);
static void              train_network              (NeuralTrainGUI *gui);
static void              switch_preview             (NeuralTrainGUI *gui);
static void              network_load               (NeuralTrainGUI *gui);
static void              network_store              (NeuralTrainGUI *gui);
static void              network_delete             (NeuralTrainGUI *gui);
static void              network_rename             (NeuralTrainGUI *gui);
static void              network_train_selected     (NeuralTrainGUI *gui);
static void              network_apply_selected     (NeuralApplyGUI *gui);
static gboolean          network_validate_name      (NeuralTrainGUI *gui,
                                                     const gchar *name,
                                                     gboolean show_warning);
static gboolean          gwy_neural_network_save    (GwyNeuralNetwork *nn);
static void              load_network_to_param_table(NeuralTrainGUI *gui,
                                                     GwyNeuralNetwork *network);
static GwyNeuralNetwork* ensure_network             (GwyParams *params);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Neural network SPM data processing"),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "3.1",
    "David Nečas (Yeti) & Petr Klapetek",
    "2012",
};

GWY_MODULE_QUERY2(module_info, neural)

static gboolean
module_register(void)
{
    static gint types_initialized = 0;
    GwyResourceClass *klass;

    /* FIXME: Load the resources on demand? */
    if (!types_initialized) {
        types_initialized += gwy_neural_network_get_type();
        klass = g_type_class_ref(GWY_TYPE_NEURAL_NETWORK);
        gwy_resource_class_load(klass);
        gwy_resource_class_mkdir(klass);
        g_type_class_unref(klass);
    }

    gwy_image_func_register("neural_train",
                            &neural_train,
                            N_("/M_ultidata/Neural Network _Training..."),
                            GWY_ICON_NEURAL_TRAIN,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Train a neural network for image processing"));
    gwy_image_func_register("neural_apply",
                            &neural_apply,
                            N_("/M_ultidata/Apply _Neural Network..."),
                            GWY_ICON_NEURAL_APPLY,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Process data using a trained neural network"));

    return TRUE;
}

static GwyParamDef*
define_module_params_train(void)
{
    static const GwyEnum previews[] = {
        { N_("Model"),      PREVIEW_MODEL,      },
        { N_("Signal"),     PREVIEW_SIGNAL,     },
        { N_("Result"),     PREVIEW_RESULT,     },
        { N_("Difference"), PREVIEW_DIFFERENCE, },
    };
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, "neural");
    gwy_param_def_add_image_id(paramdef, PARAM_MODEL, NULL, _("_Model"));
    gwy_param_def_add_image_id(paramdef, PARAM_SIGNAL, "signal", _("_Signal"));
    gwy_param_def_add_int(paramdef, PARAM_TRAINSTEPS, "trainsteps", _("Training ste_ps"), 0, 10000, 1000);
    gwy_param_def_add_enum(paramdef, PARAM_MASKING, "masking", NULL, GWY_TYPE_MASKING_TYPE, GWY_MASK_IGNORE);
    gwy_param_def_add_resource(paramdef, PARAM_NAME, "name", NULL, gwy_neural_networks(), GWY_NEURAL_NETWORK_UNTITLED);
    gwy_param_def_add_gwyenum(paramdef, PARAM_PREVIEW, NULL, _("Preview"),
                              previews, G_N_ELEMENTS(previews), PREVIEW_SIGNAL);

    gwy_param_def_add_int(paramdef, PARAM_WIN_WIDTH, NULL, _("Window _width"), 1, 100, 11);
    gwy_param_def_add_int(paramdef, PARAM_WIN_HEIGHT, NULL, _("Window h_eight"), 1, 100, 11);
    gwy_param_def_add_int(paramdef, PARAM_NHIDDEN, NULL, _("_Hidden nodes"), 1, 100, 7);
    /* Do not translate, not public. */
    gwy_param_def_add_int(paramdef, PARAM_NLAYERS, NULL, "_Number of layers", 1, 10, 1);
    gwy_param_def_add_int(paramdef, PARAM_NOUTPUT, NULL, "_Number of outputs", 1, 3, 1);
    gwy_param_def_add_int(paramdef, PARAM_INPOWER_XY, NULL, _("Power of source _XY"), -12, 12, 0);
    gwy_param_def_add_int(paramdef, PARAM_INPOWER_Z, NULL, _("Power of source _Z"), -12, 12, 1);
    /* This is actually a unit but we handle it weird. */
    gwy_param_def_add_string(paramdef, PARAM_OUTUNITS, NULL, _("_Fixed units"),
                             GWY_PARAM_STRING_NULL_IS_EMPTY, NULL, "");

    return paramdef;
}

static GwyParamDef*
define_module_params_apply(void)
{
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, "neural");
    gwy_param_def_add_resource(paramdef, PARAM_NAME, "name", NULL, gwy_neural_networks(), GWY_NEURAL_NETWORK_UNTITLED);
    gwy_param_def_add_boolean(paramdef, PARAM_SCALE_OUTPUT, "scale_output", _("_Scale proportionally to input"), FALSE);
    return paramdef;
}

static void
neural_train(G_GNUC_UNUSED GwyFile *data, GwyRunModeFlags mode)
{
    NeuralTrainArgs args;
    GwyField *field, *signalfield;
    GwyParams *params;
    GwyAppDataId dataid;

    g_return_if_fail(mode & RUN_MODES);
    gwy_clear1(args);

    args.params = params = gwy_params_new_from_settings(define_module_params_train());
    gwy_data_browser_get_current(GWY_APP_FIELD_ID, &dataid.id,
                                 GWY_APP_FIELD, &field,
                                 GWY_APP_FILE_ID, &dataid.datano,
                                 0);
    gwy_params_set_image_id(params, PARAM_MODEL, dataid);
    signalfield = gwy_params_get_image(params, PARAM_SIGNAL);
    /* Init signal to a field compatible with model. */
    if (!signalfield || gwy_field_is_incompatible(field, signalfield,
                                                  GWY_DATA_MISMATCH_RES
                                                  | GWY_DATA_MISMATCH_REAL
                                                  | GWY_DATA_MISMATCH_LATERAL))
        gwy_params_set_image_id(params, PARAM_SIGNAL, dataid);
    args.nn = ensure_network(params);
    gwy_debug("switching args->nn to %s", gwy_resource_get_name(GWY_RESOURCE(args.nn)));

    run_gui_train(&args);
    gwy_params_save_to_settings(params);
    g_object_unref(args.params);
}

static void
neural_apply(GwyFile *data, GwyRunModeFlags mode)
{
    NeuralApplyArgs args;
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    gint id, newid;

    g_return_if_fail(mode & RUN_MODES);
    gwy_clear1(args);

    args.params = gwy_params_new_from_settings(define_module_params_apply());
    gwy_data_browser_get_current(GWY_APP_FIELD_ID, &id,
                                 GWY_APP_FIELD, &args.field,
                                 0);
    g_return_if_fail(args.field);

    args.nn = ensure_network(args.params);
    gwy_debug("switching args->nn to %s", gwy_resource_get_name(GWY_RESOURCE(args.nn)));

    if (mode == GWY_RUN_INTERACTIVE)
        outcome = run_gui_apply(&args);
    if (outcome == GWY_DIALOG_CANCEL)
        goto end;

    if (execute_apply(&args, data, id)) {
        newid = gwy_file_add_image(data, args.result);
        gwy_file_set_visible(data, GWY_FILE_IMAGE, newid, TRUE);
        gwy_file_set_title(data, GWY_FILE_IMAGE, newid, _("Evaluated signal"), TRUE);
        gwy_file_sync_items(data, GWY_FILE_IMAGE, id,
                            data, GWY_FILE_IMAGE, newid,
                            GWY_FILE_ITEM_PALETTE, FALSE);
        gwy_log_add_full(data, GWY_FILE_IMAGE, id, newid, "image::neural_apply", "settings-name", "neural", NULL);
    }

end:
    g_clear_object(&args.result);
    gwy_params_save_to_settings(args.params);
    g_object_unref(args.params);
}

/* This assumes model and singal are compatible! */
static void
setup_images(NeuralTrainGUI *gui)
{
    GwyParams *params = gui->args->params;
    GwyField *signal = gwy_params_get_image(params, PARAM_SIGNAL);

    g_clear_object(&gui->result);
    g_clear_object(&gui->diff);
    gui->result = gwy_field_new_alike(signal, TRUE);
    gui->diff = gwy_field_new_alike(signal, TRUE);
}

static void
network_cell_renderer(G_GNUC_UNUSED GtkTreeViewColumn *column,
                      GtkCellRenderer *cell,
                      GtkTreeModel *model,
                      GtkTreeIter *piter,
                      gpointer data)
{
    GwyNeuralNetwork *network;
    gulong id;
    const gchar *name;
    gchar *s;

    id = GPOINTER_TO_UINT(data);
    g_assert(id < NETWORK_LAST);
    gtk_tree_model_get(model, piter, 0, &network, -1);
    if (id == NETWORK_NAME) {
        name = gwy_resource_get_name(GWY_RESOURCE(network));
        if (gwy_strequal(name, GWY_NEURAL_NETWORK_UNTITLED))
            /* TRANSLATORS: Unnamed neural network that is/was in training. */
            name = _("In training");
        g_object_set(cell, "text", name, NULL);
    }
    else if (id == NETWORK_SIZE) {
        s = g_strdup_printf("%u×%u", network->data.width, network->data.height);
        g_object_set(cell, "text", s, NULL);
        g_free(s);
    }
    else if (id == NETWORK_HIDDEN) {
        s = g_strdup_printf("%u", network->data.nhidden);
        g_object_set(cell, "text", s, NULL);
        g_free(s);
    }
}

static GtkWidget*
create_network_list(GtkTreeModel *model, GtkWidget **scroll)
{
    static const GwyEnum columns[] = {
        { N_("Name"),   NETWORK_NAME,   },
        { N_("Size"),   NETWORK_SIZE,   },
        { N_("Hidden"), NETWORK_HIDDEN, },
    };

    GtkWidget *networklist = gtk_tree_view_new_with_model(model);

    for (guint i = 0; i < G_N_ELEMENTS(columns); i++) {
        GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
        GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes(_(columns[i].name), renderer, NULL);
        gtk_tree_view_column_set_cell_data_func(column, renderer,
                                                network_cell_renderer, GUINT_TO_POINTER(columns[i].value), NULL);
        gtk_tree_view_append_column(GTK_TREE_VIEW(networklist), column);
    }

    *scroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(*scroll), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
    gtk_container_add(GTK_CONTAINER(*scroll), networklist);

    return networklist;
}

static GwyDialogOutcome
run_gui_train(NeuralTrainArgs *args)
{
    NeuralTrainGUI gui;
    GwyDialog *dialog;
    GtkWidget *hbox, *vbox, *notebook, *graph;
    GwyGraphCurveModel *gcmodel;
    GwyDialogOutcome outcome;

    gwy_clear1(gui);
    gui.args = args;
    gui.calculated = FALSE;
    gui.compatible = TRUE;

    setup_images(&gui);

    gui.dialog = gwy_dialog_new(_("Neural Network Training"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
    gwy_dialog_add_content(dialog, hbox, TRUE, TRUE, 4);

    vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4);
    gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 4);

    gui.dataview = gwy_create_preview(gwy_params_get_image(args->params, PARAM_MODEL), NULL, PREVIEW_SMALL_SIZE);
    gtk_box_pack_start(GTK_BOX(vbox), gui.dataview, FALSE, FALSE, 0);

    gui.gmodel = gwy_graph_model_new();
    g_object_set(gui.gmodel,
                 "title", _("Training error"),
                 "axis-label-left", _("error"),
                 "axis-label-bottom", "n",
                 NULL);
    graph = gwy_graph_new(gui.gmodel);
    gtk_widget_set_size_request(graph, -1, 200);
    gwy_graph_enable_user_input(GWY_GRAPH(graph), FALSE);
    gtk_box_pack_start(GTK_BOX(vbox), graph, TRUE, TRUE, 0);

    gcmodel = gwy_graph_curve_model_new();
    g_object_set(gcmodel, "description", _("NN training error"), NULL);
    gwy_graph_model_add_curve(gui.gmodel, gcmodel);
    g_object_unref(gcmodel);

    notebook = gtk_notebook_new();
    gtk_box_pack_start(GTK_BOX(hbox), notebook, TRUE, TRUE, 4);

    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), training_tab_new(&gui), gtk_label_new(_("Training")));
    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), parameters_tab_new(&gui), gtk_label_new(_("Parameters")));
    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), networks_tab_new(&gui), gtk_label_new(_("Networks")));

    load_network_to_param_table(&gui, gui.args->nn);

    g_signal_connect_swapped(gui.table_training, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(gui.table_network, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(dialog, "response", G_CALLBACK(dialog_response), &gui);
    /* There is no preview function here. The thing is which plays its role is called ‘Train’. */

    outcome = gwy_dialog_run(dialog);

    g_clear_object(&gui.result);
    g_clear_object(&gui.diff);
    g_object_unref(gui.gmodel);

    return outcome;
}

static GtkWidget*
training_tab_new(NeuralTrainGUI *gui)
{
    GwyParamTable *table;

    gui->table_training = table = gwy_param_table_new(gui->args->params);

    gwy_param_table_append_image_id(table, PARAM_MODEL);
    gwy_param_table_append_image_id(table, PARAM_SIGNAL);
    gwy_param_table_append_slider(table, PARAM_TRAINSTEPS);
    gwy_param_table_append_separator(table);
    gwy_param_table_append_radio(table, PARAM_PREVIEW);
    gwy_param_table_append_button(table, BUTTON_TRAIN, -1, RESPONSE_TRAIN, C_("verb", "_Train"));
    gwy_param_table_append_button(table, BUTTON_REINITIALIZE, BUTTON_TRAIN, RESPONSE_REINITIALIZE, _("Re_initialize"));
    gwy_param_table_append_message(table, MESSAGE_TRAINING, NULL);
    gwy_param_table_append_separator(table);
    gwy_param_table_append_radio(table, PARAM_MASKING);
    /* TODO: make it sensitive depending on mask presence? */

    gwy_param_table_radio_set_sensitive(table, PARAM_PREVIEW, PREVIEW_RESULT, FALSE);
    gwy_param_table_radio_set_sensitive(table, PARAM_PREVIEW, PREVIEW_DIFFERENCE, FALSE);

    return gwy_param_table_widget(table);
}

static GtkWidget*
parameters_tab_new(NeuralTrainGUI *gui)
{
    GwyParamTable *table;

    gui->table_network = table = gwy_param_table_new(gui->args->params);

    gwy_param_table_append_header(table, -1, _("Network"));
    gwy_param_table_append_slider(table, PARAM_WIN_WIDTH);
    gwy_param_table_set_unitstr(table, PARAM_WIN_WIDTH, _("px"));
    gwy_param_table_append_slider(table, PARAM_WIN_HEIGHT);
    gwy_param_table_set_unitstr(table, PARAM_WIN_HEIGHT, _("px"));
    gwy_param_table_append_slider(table, PARAM_NHIDDEN);

    gwy_param_table_append_header(table, -1, _("Result Units"));
    gwy_param_table_append_slider(table, PARAM_INPOWER_XY);
    gwy_param_table_append_slider(table, PARAM_INPOWER_Z);
    gwy_param_table_append_entry(table, PARAM_OUTUNITS);

    return gwy_param_table_widget(table);
}

static GtkWidget*
networks_tab_new(NeuralTrainGUI *gui)
{
    GtkTreeSelection *tselect;
    GtkWidget *vbox, *scroll, *hbox, *bbox, *button, *label;
    GtkTreeModel *filtermodel;

    vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);

    gui->store = gwy_inventory_store_new(gwy_neural_networks());
    filtermodel = gwy_create_inventory_model_without_default(gui->store);
    gui->networklist = create_network_list(filtermodel, &scroll);
    g_object_unref(gui->store);
    g_object_unref(filtermodel);
    gtk_box_pack_start(GTK_BOX(vbox), scroll, TRUE, TRUE, 0);

    bbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
    gtk_box_set_homogeneous(GTK_BOX(bbox), TRUE);
    gtk_box_pack_start(GTK_BOX(vbox), bbox, FALSE, FALSE, 0);

    button = gtk_button_new_with_mnemonic(C_("verb", "_Load"));
    gui->load = button;
    gtk_container_add(GTK_CONTAINER(bbox), button);
    g_signal_connect_swapped(button, "clicked", G_CALLBACK(network_load), gui);

    button = gtk_button_new_with_mnemonic(C_("verb", "_Store"));
    gui->save = button;
    gtk_container_add(GTK_CONTAINER(bbox), button);
    g_signal_connect_swapped(button, "clicked", G_CALLBACK(network_store), gui);

    button = gtk_button_new_with_mnemonic(_("_Rename"));
    gui->rename = button;
    gtk_container_add(GTK_CONTAINER(bbox), button);
    g_signal_connect_swapped(button, "clicked", G_CALLBACK(network_rename), gui);

    button = gtk_button_new_with_mnemonic(_("_Delete"));
    gui->delete = button;
    gtk_container_add(GTK_CONTAINER(bbox), button);
    g_signal_connect_swapped(button, "clicked", G_CALLBACK(network_delete), gui);

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
    gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 4);

    gui->networkname = gtk_entry_new();
    gtk_entry_set_max_length(GTK_ENTRY(gui->networkname), 40);
    label = gtk_label_new_with_mnemonic(_("Network _name:"));
    gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(hbox), gui->networkname, TRUE, TRUE, 0);
    gtk_label_set_mnemonic_widget(GTK_LABEL(label), gui->networkname);

    tselect = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->networklist));
    gtk_tree_selection_set_mode(tselect, GTK_SELECTION_SINGLE);
    g_signal_connect_swapped(tselect, "changed", G_CALLBACK(network_train_selected), gui);

    return vbox;
}

static GwyDialogOutcome
run_gui_apply(NeuralApplyArgs *args)
{
    NeuralApplyGUI gui;
    GtkWidget *scroll;
    GwyParamTable *table;
    GwyDialog *dialog;
    GtkTreeSelection *tselect;

    gui.args = args;

    gui.dialog = gwy_dialog_new(_("Apply Neural Network"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);
    gtk_window_set_default_size(GTK_WINDOW(dialog), -1, 320);

    gui.store = gwy_inventory_store_new(gwy_neural_networks());
    gui.networklist = create_network_list(GTK_TREE_MODEL(gui.store), &scroll);
    g_object_unref(gui.store);
    gwy_dialog_add_content(dialog, scroll, TRUE, TRUE, 0);

    tselect = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui.networklist));
    gtk_tree_selection_set_select_function(tselect, can_select_network, args->field, NULL);
    gtk_tree_selection_set_mode(tselect, GTK_SELECTION_BROWSE);
    g_signal_connect_swapped(tselect, "changed", G_CALLBACK(network_apply_selected), &gui);
    if (!gtk_tree_selection_get_selected(tselect, NULL, NULL))
        gtk_dialog_set_response_sensitive(GTK_DIALOG(gui.dialog), GTK_RESPONSE_OK, FALSE);

    table = gwy_param_table_new(args->params);
    gwy_param_table_append_checkbox(table, PARAM_SCALE_OUTPUT);
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), FALSE, FALSE, 0);


    return gwy_dialog_run(dialog);
}

static gboolean
can_select_network(G_GNUC_UNUSED GtkTreeSelection *selection,
                   GtkTreeModel *model,
                   GtkTreePath *path,
                   G_GNUC_UNUSED gboolean path_currently_selected,
                   gpointer data)
{
    GwyField *field = (GwyField*)data;
    GwyNeuralNetwork *network;
    GtkTreeIter iter;

    if (!gtk_tree_model_get_iter(model, &iter, path))
        return FALSE;

    gtk_tree_model_get(model, &iter, 0, &network, -1);
    return (gwy_field_get_xres(field) > network->data.width
            && gwy_field_get_yres(field) > network->data.height);
}

static void
param_changed(NeuralTrainGUI *gui, gint id)
{
    GwyParams *params = gui->args->params;

    if (id < 0 || id == PARAM_MODEL || id == PARAM_SIGNAL) {
        NeuralNetworkData *nndata = &gui->args->nn->data;
        GwyParamTable *table = gui->table_training;
        GwyField *model = gwy_params_get_image(params, PARAM_MODEL);
        GwyField *signal = gwy_params_get_image(params, PARAM_SIGNAL);
        PreviewType previewtype = gwy_params_get_enum(params, PARAM_PREVIEW);
        gboolean ok;
        const gchar *message = "";

        ok = !gwy_field_is_incompatible(model, signal,
                                        GWY_DATA_MISMATCH_RES
                                        | GWY_DATA_MISMATCH_REAL
                                        | GWY_DATA_MISMATCH_LATERAL);
        if (!ok)
            message = _("Model and signal are not compatible.");

        if (ok && (gwy_field_get_xres(model) <= nndata->width
                   || gwy_field_get_yres(model) <= nndata->height
                   || gwy_field_get_xres(signal) <= nndata->width
                   || gwy_field_get_yres(signal) <= nndata->height)) {
            ok = FALSE;
            message = _("A field dimension is too small for chosen window size.");
        }

        gwy_param_table_set_label(table, MESSAGE_TRAINING, message);
        gwy_param_table_set_sensitive(table, BUTTON_TRAIN, ok);

        gui->calculated = FALSE;
        gui->compatible = ok;
        setup_images(gui);
        if (previewtype != PREVIEW_MODEL && previewtype != PREVIEW_SIGNAL) {
            previewtype = (id == PARAM_SIGNAL ? PREVIEW_SIGNAL : PREVIEW_MODEL);
            gwy_param_table_set_enum(table, PARAM_PREVIEW, previewtype);
        }
        gwy_param_table_radio_set_sensitive(table, PARAM_PREVIEW, PREVIEW_RESULT, FALSE);
        gwy_param_table_radio_set_sensitive(table, PARAM_PREVIEW, PREVIEW_DIFFERENCE, FALSE);
    }

    if (id < 0 || id == PARAM_PREVIEW || id == PARAM_MODEL || id == PARAM_SIGNAL) {
        switch_preview(gui);
        gwy_set_data_preview_size(GWY_DATA_VIEW(gui->dataview), PREVIEW_SMALL_SIZE);
    }

    /* We are getting updates with id < 0, but these do not mean the network parameters has changed. */
    if (!gui->loading_network
        && (id == PARAM_WIN_WIDTH || id == PARAM_WIN_HEIGHT || id == PARAM_NHIDDEN
            || id == PARAM_INPOWER_XY || id == PARAM_INPOWER_Z || id == PARAM_OUTUNITS)) {
        NeuralNetworkData *nndata = &gui->args->nn->data;
        nndata->width = gwy_params_get_int(params, PARAM_WIN_WIDTH);
        nndata->height = gwy_params_get_int(params, PARAM_WIN_HEIGHT);
        nndata->nlayers = gwy_params_get_int(params, PARAM_NLAYERS);
        nndata->noutput = gwy_params_get_int(params, PARAM_NOUTPUT);
        nndata->nhidden = gwy_params_get_int(params, PARAM_NHIDDEN);
        nndata->inpowerxy = gwy_params_get_int(params, PARAM_INPOWER_XY);
        nndata->inpowerz = gwy_params_get_int(params, PARAM_INPOWER_Z);
        gwy_assign_string(&nndata->outunits, gwy_params_get_string(params, PARAM_OUTUNITS));
        if (id == PARAM_WIN_WIDTH || id == PARAM_WIN_HEIGHT || id == PARAM_NHIDDEN)
            neural_network_data_resize(nndata);
        gwy_resource_data_changed(GWY_RESOURCE(gui->args->nn));
        gui->calculated = FALSE;
    }
}

static void
dialog_response(NeuralTrainGUI *gui, gint response)
{
    if (response == RESPONSE_REINITIALIZE) {
        NeuralNetworkData *nndata = &gui->args->nn->data;
        neural_network_data_init(nndata, NULL);
        gui->calculated = FALSE;
        gwy_resource_data_changed(GWY_RESOURCE(gui->args->nn));
    }
    else if (response == RESPONSE_TRAIN) {
        train_network(gui);
    }
}

static void
calculate_scaling(GwyField *field, gdouble *factor, gdouble *shift)
{
    gdouble min, max;

    gwy_field_min_max(field, &min, &max);
    *shift = min;
    *factor = 1.0/(max - *shift);
}

/* See libgwyddion/internal.h */
static inline gint
nielded_included(const gint *m, GwyMaskingType masking)
{
    if (masking == GWY_MASK_INCLUDE)
        return *m > 0;
    if (masking == GWY_MASK_EXCLUDE)
        return *m <= 0;
    return 1;
}

static gboolean
train_do(GwyNeuralNetwork *nn, GwyLine *errors, GwyGraphCurveModel *gcmodel,
         GwyField *model, GwyField *signal, GwyNield *mask,
         GwyMaskingType masking, gdouble sfactor, gdouble sshift,
         guint trainsteps)
{
    NeuralNetworkData *nndata = &nn->data;
    guint width = nndata->width, height = nndata->height;
    gboolean ok = FALSE;

    /* Not only optimisation, also prevents changing scaling parameters. */
    if (!trainsteps)
        return TRUE;

    gwy_graph_curve_model_set_data_from_line(gcmodel, errors, 0, 1);
    if (!gwy_app_wait_set_message(_("Training...")))
        return FALSE;

    nndata->outfactor = sfactor;
    nndata->outshift = sshift;
    calculate_scaling(model, &nndata->infactor, &nndata->inshift);

    GwyField *scaled = gwy_field_copy(model);
    gwy_field_normalize(scaled);
    gint xres = gwy_field_get_xres(scaled), yres = gwy_field_get_yres(scaled);
    const gdouble *dtmodel = gwy_field_get_data_const(scaled);
    gdouble *dtsignal = gwy_field_get_data(signal);
    const gint *dtmask = mask ? gwy_nield_get_data_const(mask) : NULL;

    guint *indices = g_new(guint, (xres - width)*(yres - height));
    guint npixels = 0;
    for (guint row = height/2; row < yres + height/2 - height; row++) {
        for (guint col = width/2; col < xres + width/2 - width; col++) {
            if (nielded_included(dtmask + row*xres + col, masking))
                indices[npixels++] = (row - height/2)*xres + col - width/2;
        }
    }
    g_assert(dtmask || npixels == (xres - width)*(yres - height));

    GTimer *timer = g_timer_new();
    gdouble eo = 0.0, eh = 0.0, lasttime = 0.0;
    for (guint n = 0; n < trainsteps; n++) {
        /* FIXME: Randomisation leads to weird spiky NN error curves. */
        /* shuffle(indices, (xres - width)*(yres - height), rng); even though
         * it may improve convergence. */
        for (guint k = 0; k < npixels; k++) {
            for (guint irow = 0; irow < height; irow++)
                gwy_assign(nn->input + irow*width, dtmodel + indices[k] + irow*xres, width);
            nn->target[0] = sfactor*(dtsignal[indices[k] + height/2*xres + width/2] - sshift);
            gwy_neural_network_train_step(nn, 0.3, 0.3, &eo, &eh);
        }
        gwy_line_set_val(errors, n, eo + eh);
        if (g_timer_elapsed(timer, NULL) - lasttime >= 0.2) {
            gwy_graph_curve_model_set_data_from_line(gcmodel, errors, 0, n+1);
            if (!gwy_app_wait_set_fraction((gdouble)n/trainsteps))
                goto fail;
            lasttime = g_timer_elapsed(timer, NULL);
        }
    }
    ok = TRUE;

fail:
    g_timer_destroy(timer);
    g_object_unref(scaled);
    g_free(indices);

    return ok;
}

static gboolean
evaluate(GwyNeuralNetwork *nn,
         GwyField *model, GwyField *result,
         gdouble sfactor, gdouble sshift)
{
    NeuralNetworkData *nndata = &nn->data;
    GwyField *scaled;
    GwyUnit *unit;
    guint width = nndata->width, height = nndata->height, xres, yres;
    guint col, row, irow;
    const gdouble *drmodel;
    gdouble *dresult;
    gdouble avg;
    gboolean ok = FALSE;

    if (!gwy_app_wait_set_message(_("Evaluating...")))
        return FALSE;

    scaled = gwy_field_copy(model);
    gwy_field_normalize(scaled);
    xres = gwy_field_get_xres(scaled);
    yres = gwy_field_get_yres(scaled);
    drmodel = gwy_field_get_data_const(scaled);
    dresult = gwy_field_get_data(result);

    for (row = height/2; row < yres + height/2 - height; row++) {
        for (col = width/2; col < xres + width/2 - width; col++) {
            for (irow = 0; irow < height; irow++)
                gwy_assign(nn->input + irow*width, drmodel + ((row + irow - height/2)*xres + col - width/2), width);
            gwy_neural_network_forward_feed(nn);
            dresult[row*xres + col] = nn->output[0]/sfactor + sshift;
        }
        if (row % 32 == 31 && !gwy_app_wait_set_fraction((gdouble)row/yres))
            goto fail;
    }
    ok = TRUE;
    unit = gwy_field_get_unit_z(result);
    gwy_unit_set_from_string(unit, nndata->outunits);
    gwy_unit_power_multiply(unit, unit, 1, gwy_field_get_unit_xy(model), nndata->inpowerxy);
    gwy_unit_power_multiply(unit, unit, 1, gwy_field_get_unit_z(model), nndata->inpowerz);

    /* Fill the borders with the average of result. */
    avg = gwy_field_area_mean(result, NULL, GWY_MASK_IGNORE, width/2, height/2, xres - width, yres - height);
    gwy_field_area_fill(result, NULL, GWY_MASK_IGNORE, 0, 0, xres, height/2, avg);
    gwy_field_area_fill(result, NULL, GWY_MASK_IGNORE, 0, height/2, width/2, yres - height, avg);
    gwy_field_area_fill(result, NULL, GWY_MASK_IGNORE, xres + width/2 - width, height/2, width - width/2, yres - height, avg);
    gwy_field_area_fill(result, NULL, GWY_MASK_IGNORE, 0, yres + height/2 - height, xres, height - height/2, avg);

fail:
    g_object_unref(scaled);
    return ok;
}

static gdouble
calculate_mean_error(GwyField *field)
{
    guint xres, yres, k;
    const gdouble *data;
    gdouble s = 0.0;

    xres = gwy_field_get_xres(field);
    yres = gwy_field_get_yres(field);
    data = gwy_field_get_data_const(field);
    for (k = xres*yres; k; k--, data++)
        s += fabs(*data);

    return s/(xres*yres);
}

static void
train_network(NeuralTrainGUI *gui)
{
    NeuralTrainArgs *args = gui->args;
    GwyParams *params = args->params;
    gint trainsteps = gwy_params_get_int(params, PARAM_TRAINSTEPS);
    GwyParamTable *table = gui->table_training;
    GwyNeuralNetwork *nn = args->nn;
    GwyField *model = gwy_params_get_image(params, PARAM_MODEL);
    GwyField *signal = gwy_params_get_image(params, PARAM_SIGNAL);
    GwyNield *mask = gwy_params_get_image_mask(params, PARAM_SIGNAL);
    GwyMaskingType masking = gwy_params_get_masking(params, PARAM_MASKING, &mask);
    GwyField *result = gui->result, *diff = gui->diff;
    GwyLine *errors;
    GwyGraphCurveModel *gcmodel;
    NeuralNetworkData backup;
    GwyValueFormat *vf;
    gdouble sfactor, sshift;
    gchar *s;
    gboolean ok;

    gwy_app_wait_start(GTK_WINDOW(gui->dialog), _("Initializing..."));

    errors = gwy_line_new(trainsteps, trainsteps, TRUE);
    gcmodel = gwy_graph_model_get_curve(gui->gmodel, 0);
    calculate_scaling(signal, &sfactor, &sshift);

    gwy_clear1(backup);
    neural_network_data_copy(&nn->data, &backup);

    gwy_neural_network_ensure_state(nn);
    ok = (train_do(nn, errors, gcmodel, model, signal, mask, masking, sfactor, sshift, trainsteps)
          && evaluate(nn, model, result, sfactor, sshift));
    gwy_neural_network_free_state(nn);

    gwy_app_wait_finish();

    if (!ok)
        neural_network_data_copy(&backup, &nn->data);
    neural_network_data_free(&backup);
    g_object_unref(errors);

    if (!ok) {
        gwy_param_table_set_label(table, MESSAGE_TRAINING, _("Training was canceled."));
        return;
    }

    gwy_field_subtract_fields(diff, result, signal);
    gwy_field_data_changed(result);
    gwy_field_data_changed(diff);

    vf = gwy_field_get_value_format_z(diff, GWY_UNIT_FORMAT_VFMARKUP, NULL);
    s = g_strdup_printf(_("Mean difference: %.*f %s"),
                        vf->precision, calculate_mean_error(diff)/vf->magnitude, vf->units);
    gwy_value_format_free(vf);
    gwy_param_table_set_label(table, MESSAGE_TRAINING, s);
    g_free(s);

    gui->calculated = TRUE;
    gwy_resource_data_changed(GWY_RESOURCE(gui->args->nn));
    gwy_param_table_radio_set_sensitive(table, PARAM_PREVIEW, PREVIEW_RESULT, TRUE);
    gwy_param_table_radio_set_sensitive(table, PARAM_PREVIEW, PREVIEW_DIFFERENCE, TRUE);
}

static gboolean
execute_apply(NeuralApplyArgs *args, GwyFile *data, gint id)
{
    GwyParams *params = args->params;
    const gchar *name = gwy_params_get_string(params, PARAM_NAME);
    gboolean scale_output = gwy_params_get_boolean(params, PARAM_SCALE_OUTPUT);
    GwyNeuralNetwork *network;
    NeuralNetworkData *nndata;
    gdouble factor, shift;
    gboolean ok;

    gwy_app_wait_start(gwy_data_browser_get_window_for_data(data, GWY_FILE_IMAGE, id), _("Evaluating..."));

    network = gwy_inventory_get_item(gwy_neural_networks(), name);
    g_assert(network);
    nndata = &network->data;

    gwy_neural_network_ensure_state(network);
    args->result = gwy_field_new_alike(args->field, TRUE);
    factor = nndata->outfactor;
    shift = nndata->outshift;
    if (scale_output) {
        gdouble ifactor, ishift;
        calculate_scaling(args->field, &ifactor, &ishift);
        factor /= ifactor/nndata->infactor;
    }
    ok = evaluate(network, args->field, args->result, factor, shift);
    gwy_neural_network_free_state(network);

    gwy_app_wait_finish();

    return ok;
}

static void
load_network_to_param_table(NeuralTrainGUI *gui, GwyNeuralNetwork *network)
{
    GwyParamTable *table = gui->table_network;
    const NeuralNetworkData *nndata = &network->data;
    const gchar *name = gwy_resource_get_name(GWY_RESOURCE(network));

    gui->loading_network = TRUE;

    gwy_params_set_resource(gui->args->params, PARAM_NAME, name);

    gwy_param_table_set_int(table, PARAM_WIN_WIDTH, nndata->width);
    gwy_param_table_set_int(table, PARAM_WIN_HEIGHT, nndata->height);
    gwy_param_table_set_int(table, PARAM_NHIDDEN, nndata->nhidden);
    gwy_param_table_set_int(table, PARAM_INPOWER_XY, nndata->inpowerxy);
    gwy_param_table_set_int(table, PARAM_INPOWER_Z, nndata->inpowerz);
    gwy_param_table_set_string(table, PARAM_OUTUNITS, nndata->outunits);

    gwy_params_set_int(gui->args->params, PARAM_NLAYERS, nndata->nlayers);
    gwy_params_set_int(gui->args->params, PARAM_NOUTPUT, nndata->noutput);

    gui->loading_network = FALSE;

    gwy_param_table_param_changed(table, -1);
}

static void
network_load(NeuralTrainGUI *gui)
{
    GtkTreeModel *store;
    GtkTreeSelection *tselect;
    GtkTreeIter iter;

    tselect = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->networklist));
    if (!gtk_tree_selection_get_selected(tselect, &store, &iter))
        return;

    gtk_tree_model_get(store, &iter, 0, &gui->args->nn, -1);
    gwy_debug("switching args->nn to %s", gwy_resource_get_name(GWY_RESOURCE(gui->args->nn)));
    load_network_to_param_table(gui, gui->args->nn);
    gui->calculated = FALSE;
}

static void
network_store(NeuralTrainGUI *gui)
{
    GwyNeuralNetwork *network;
    NeuralNetworkData *nndata;
    const gchar *name;

    nndata = &gui->args->nn->data;
    name = gtk_entry_get_text(GTK_ENTRY(gui->networkname));
    if (!network_validate_name(gui, name, TRUE))
        return;
    gwy_debug("Now I'm saving `%s'", name);
    network = gwy_inventory_get_item(gwy_neural_networks(), name);
    if (!network) {
        gwy_debug("Appending `%s'", name);
        network = gwy_neural_network_new(name, nndata, FALSE);
        gwy_inventory_insert_item(gwy_neural_networks(), network);
        g_object_unref(network);
    }
    else {
        gwy_debug("Setting `%s'", name);
        neural_network_data_copy(nndata, &network->data);
        gwy_resource_data_changed(GWY_RESOURCE(network));
    }
    gwy_resource_data_changed(GWY_RESOURCE(network));
    gwy_neural_network_save(network);

    gwy_select_in_filtered_inventory_treeeview(GTK_TREE_VIEW(gui->networklist), name);
}

static void
network_delete(NeuralTrainGUI *gui)
{
    GwyNeuralNetwork *network;
    GtkTreeModel *model;
    GtkTreeSelection *tselect;
    GtkTreeIter iter;

    tselect = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->networklist));
    if (!gtk_tree_selection_get_selected(tselect, &model, &iter))
        return;

    gtk_tree_model_get(model, &iter, 0, &network, -1);
    gwy_resource_delete(GWY_RESOURCE(network));
}

static void
network_rename(NeuralTrainGUI *gui)
{
    GwyNeuralNetwork *network;
    GwyInventory *inventory;
    GtkTreeModel *model;
    GtkTreeSelection *tselect;
    GtkTreeIter iter;
    const gchar *newname, *oldname;

    tselect = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->networklist));
    if (!gtk_tree_selection_get_selected(tselect, &model, &iter))
        return;

    inventory = gwy_neural_networks();
    gtk_tree_model_get(model, &iter, 0, &network, -1);
    oldname = gwy_resource_get_name(GWY_RESOURCE(network));
    newname = gtk_entry_get_text(GTK_ENTRY(gui->networkname));
    if (gwy_strequal(newname, oldname)
        || !network_validate_name(gui, newname, TRUE)
        || gwy_inventory_get_item(inventory, newname))
        return;

    gwy_debug("Now I will rename `%s' to `%s'", oldname, newname);
    gwy_resource_rename(GWY_RESOURCE(network), newname);

    gwy_select_in_filtered_inventory_treeeview(GTK_TREE_VIEW(gui->networklist), newname);
}

static void
network_train_selected(NeuralTrainGUI *gui)
{
    GwyNeuralNetwork *network;
    GtkTreeModel *store;
    GtkTreeSelection *tselect;
    GtkTreeIter iter;
    const gchar *name;

    tselect = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->networklist));
    g_return_if_fail(tselect);
    if (!gtk_tree_selection_get_selected(tselect, &store, &iter)) {
        gtk_widget_set_sensitive(gui->load, FALSE);
        gtk_widget_set_sensitive(gui->delete, FALSE);
        gtk_widget_set_sensitive(gui->rename, FALSE);
        gtk_entry_set_text(GTK_ENTRY(gui->networkname), "");
        gwy_debug("Nothing is selected");
        return;
    }

    gtk_tree_model_get(store, &iter, 0, &network, -1);
    name = gwy_resource_get_name(GWY_RESOURCE(network));
    if (gwy_strequal(name, GWY_NEURAL_NETWORK_UNTITLED))
        name = "";
    gtk_entry_set_text(GTK_ENTRY(gui->networkname), name);

    gtk_widget_set_sensitive(gui->load, TRUE);
    gtk_widget_set_sensitive(gui->delete, TRUE);
    gtk_widget_set_sensitive(gui->rename, TRUE);
}

static void
network_apply_selected(NeuralApplyGUI *gui)
{
    GwyNeuralNetwork *network;
    GtkTreeModel *store;
    GtkTreeSelection *tselect;
    GtkTreeIter iter;

    tselect = gtk_tree_view_get_selection(GTK_TREE_VIEW(gui->networklist));
    if (gtk_tree_selection_get_selected(tselect, &store, &iter)) {
        gtk_tree_model_get(store, &iter, 0, &network, -1);
        gwy_params_set_resource(gui->args->params, PARAM_NAME, gwy_resource_get_name(GWY_RESOURCE(network)));
        gtk_dialog_set_response_sensitive(GTK_DIALOG(gui->dialog), GTK_RESPONSE_OK, TRUE);
    }
}

static gboolean
network_validate_name(NeuralTrainGUI *gui,
                      const gchar *name,
                      gboolean show_warning)
{
    GtkWidget *dialog, *parent;

    if (*name && !strchr(name, '/') && !strchr(name, '\\'))
        return TRUE;
    if (!show_warning)
        return FALSE;

    parent = gui->dialog;
    dialog = gtk_message_dialog_new(GTK_WINDOW(parent),
                                    GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
                                    GTK_MESSAGE_INFO,
                                    GTK_BUTTONS_CLOSE,
                                    _("The name `%s' is invalid."),
                                    name);
    gwy_run_subdialog(GTK_DIALOG(dialog));

    return FALSE;
}

static void
switch_preview(NeuralTrainGUI *gui)
{
    NeuralTrainArgs *args = gui->args;
    GwyParams *params = args->params;
    PreviewType display = gwy_params_get_enum(args->params, PARAM_PREVIEW);
    GwyDataView *dataview = GWY_DATA_VIEW(gui->dataview);
    gint param = (display == PREVIEW_MODEL ? PARAM_MODEL : PARAM_SIGNAL);
    GwyField *model = gwy_params_get_image(params, param);
    GwyAppDataId dataid = gwy_params_get_data_id(params, param);
    GwyFile *data = gwy_data_browser_get_file(dataid.datano);

    if (display == PREVIEW_MODEL || display == PREVIEW_SIGNAL) {
        gwy_data_view_set_field(dataview, model);
        gwy_setup_data_view(dataview, data, GWY_FILE_IMAGE, dataid.id,
                            GWY_FILE_ITEM_REAL_SQUARE | GWY_FILE_ITEM_COLOR_MAPPING | GWY_FILE_ITEM_RANGE);
    }
    else if (display == PREVIEW_RESULT) {
        gwy_data_view_set_field(dataview, gui->result);
        gwy_data_view_set_color_mapping(dataview, GWY_COLOR_MAPPING_FULL);
    }
    else {
        gwy_data_view_set_field(dataview, gui->diff);
        gwy_data_view_set_color_mapping(dataview, GWY_COLOR_MAPPING_FULL);
    }

    /* Use signals' gradient for eveything except the model which we show in its own colours. */
    gwy_setup_data_view(dataview, data, GWY_FILE_IMAGE, dataid.id, GWY_FILE_ITEM_PALETTE);
}

static GwyNeuralNetwork*
ensure_network(GwyParams *params)
{
    GwyNeuralNetwork *nn;

    if ((nn = gwy_inventory_get_item(gwy_neural_networks(), gwy_params_get_string(params, PARAM_NAME))))
        return nn;

    nn = gwy_neural_networks_create_untitled();
    gwy_neural_network_save(nn);
    return nn;
}

static gboolean
gwy_neural_network_save(GwyNeuralNetwork *nn)
{
    GwyResource *resource = GWY_RESOURCE(nn);
    GError *error = NULL;

    if (!gwy_resource_is_modified(resource))
        return TRUE;

    if (!gwy_resource_is_modifiable(resource)) {
        g_warning("Non-modifiable resource was modified and is about to be saved");
        return FALSE;
    }
    if (!gwy_resource_save(resource, &error)) {
        /* FIXME: GUIze this */
        g_warning("Cannot save resource %s: %s", gwy_resource_get_name(resource), error->message);
        g_clear_error(&error);
        return FALSE;
    }

    return TRUE;
}

/* vim: set cin columns=120 tw=118 et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */
