[GRASS-SVN] r57557 - sandbox/turek/scatter_plot
svn_grass at osgeo.org
svn_grass at osgeo.org
Fri Aug 30 06:52:44 PDT 2013
Author: turek
Date: 2013-08-30 06:52:44 -0700 (Fri, 30 Aug 2013)
New Revision: 57557
Modified:
sandbox/turek/scatter_plot/testing_patch.diff
Log:
scatter plots: various plotting improvemnts, bug fixing
Modified: sandbox/turek/scatter_plot/testing_patch.diff
===================================================================
--- sandbox/turek/scatter_plot/testing_patch.diff 2013-08-30 09:49:39 UTC (rev 57556)
+++ sandbox/turek/scatter_plot/testing_patch.diff 2013-08-30 13:52:44 UTC (rev 57557)
@@ -1,1648 +1,579 @@
-Index: lib/vector/Vlib/open.c
+Index: include/defs/imagery.h
===================================================================
---- lib/vector/Vlib/open.c (revision 57546)
-+++ lib/vector/Vlib/open.c (working copy)
-@@ -240,7 +240,9 @@
- }
- else {
- char file_path[GPATH_MAX];
--
-+ /* reduce to current mapset if search path was set */
-+ if(strcmp(Map->mapset, "") == 0)
-+ Map->mapset = G_store(G_mapset());
- /* temporary map: reduce to current mapset if search path
- * was set */
- if (strcmp(Map->mapset, "") == 0)
-Index: lib/imagery/scatt.c
-===================================================================
---- lib/imagery/scatt.c (revision 0)
-+++ lib/imagery/scatt.c (working copy)
-@@ -0,0 +1,746 @@
-+/*!
-+ \file lib/imagery/scatt.c
+--- include/defs/imagery.h (revision 57556)
++++ include/defs/imagery.h (working copy)
+@@ -110,6 +110,23 @@
+ FILE *I_fopen_subgroup_ref_new(const char *, const char *);
+ FILE *I_fopen_subgroup_ref_old(const char *, const char *);
+
++/* scatt_plt.c */
++void I_sc_init_cats(struct scCats *, int, int);
++void I_sc_free_cats(struct scCats *);
++int I_sc_add_cat(struct scCats *);
++int I_sc_insert_scatt_data(struct scCats *, struct scdScattData *, int, int);
+
-+ \brief Imagery library - functions for wx Scatter Plot Tool.
++void I_scd_init_scatt_data(struct scdScattData *, int, int, void *);
+
-+ Low level functions used by wx Scatter Plot Tool.
++int I_compute_scatts(struct Cell_head *, struct scCats *, const char **,
++ const char **, int, struct scCats *, const char **);
+
-+ Copyright (C) 2013 by the GRASS Development Team
++int I_create_cat_rast(struct Cell_head *, const char *);
++int I_insert_patch_to_cat_rast(const char *, struct Cell_head *, const char *);
+
-+ This program is free software under the GNU General Public License
-+ (>=v2). Read the file COPYING that comes with GRASS for details.
++int I_id_scatt_to_bands(const int, const int, int *, int *);
++int I_bands_to_id_scatt(const int, const int, const int, int *);
+
-+ \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
-+ */
+ /* sig.c */
+ int I_init_signatures(struct Signature *, int);
+ int I_new_signature(struct Signature *);
+Index: include/defs/vedit.h
+===================================================================
+--- include/defs/vedit.h (revision 57556)
++++ include/defs/vedit.h (working copy)
+@@ -33,6 +33,8 @@
+ int Vedit_merge_lines(struct Map_info *, struct ilist *);
+
+ /* move.c */
++int Vedit_move_areas(struct Map_info *, struct Map_info **, int,
++ struct ilist *, double, double, double, int, double);
+ int Vedit_move_lines(struct Map_info *, struct Map_info **, int,
+ struct ilist *, double, double, double, int, double);
+
+Index: include/imagery.h
+===================================================================
+--- include/imagery.h (revision 57556)
++++ include/imagery.h (working copy)
+@@ -135,6 +135,56 @@
+
+ } IClass_statistics;
+
++/* Scatter Plot backend */
+
-+#include <grass/raster.h>
-+#include <grass/imagery.h>
-+#include <grass/gis.h>
-+#include <grass/glocale.h>
++#define SC_SCATT_DATA 0
++#define SC_SCATT_CONDITIONS 1
+
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <math.h>
-+#include <string.h>
+
-+
-+struct rast_row
++/*! Holds list of all catagories.
++ It can contain selected areas for scatter plots (SC_SCATT_CONDITIONS type) or computed scatter plots (SC_SCATT_DATA type).
++*/
++struct scCats
+{
-+ CELL * row;
-+ char * null_row;
-+ struct Range rast_range; /*Range of whole raster.*/
-+};
++ int type; /*!< SC_SCATT_DATA -> computed scatter plots, SC_SCATT_CONDITIONS -> set conditions for scatter plots to be computed*/
+
-+/*!
-+ \brief Create pgm header.
-+
-+ Scatter plot internally generates pgm files. These pgms have header in format created by this function.
++ int n_cats; /*!< number of alocated categories */
+
-+ \param region region to be pgm header generated for
-+ \param [out] header header of pgm file
-+ */
-+static int get_cat_rast_header(struct Cell_head * region, char * header){
-+ return sprintf(header, "P5\n%d\n%d\n1\n", region->cols, region->rows);
-+}
++ int n_bands; /*!< number of analyzed bands */
++ int n_scatts; /*!< number of possible scattter plot which can be created from bands */
+
-+/*!
-+ \brief Create category raster conditions file.
-+
-+ \param cat_rast_region region to be file generated for
-+ \param cat_rast path of generated category raster file
-+ */
-+int I_create_cat_rast(struct Cell_head * cat_rast_region, const char * cat_rast)
-+{
-+ FILE * f_cat_rast;
-+ char cat_rast_header[1024];//TODO magic number
-+ int i_row, i_col;
-+ int head_nchars;
++ int n_a_cats; /*!< number of used/active categories */
++ int * cats_ids; /*!< (cat_idx->cat_id) array index is internal idx (position in cats_arr) and id is saved in it's position*/
++ int * cats_idxs; /*!< (cat_id->cat_idx) array index is id and internal idx is saved in it's position*/
+
-+ unsigned char * row_data;
++ struct scScatts ** cats_arr; /*!< array of pointers to struct scScatts */
++};
+
-+ f_cat_rast = fopen(cat_rast, "wb");
-+ if(!f_cat_rast) {
-+ G_warning("Unable to create category raster condition file <%s>.", cat_rast);
-+ return -1;
-+ }
+
-+ head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
-+
-+ fwrite(cat_rast_header, sizeof(char), head_nchars/sizeof(char), f_cat_rast);
-+ if (ferror(f_cat_rast)){
-+ fclose(f_cat_rast);
-+ G_warning(_("Unable to write header into category raster condition file <%s>."), cat_rast);
-+ return -1;
-+ }
-+
-+ row_data = (unsigned char *) G_malloc(cat_rast_region->cols * sizeof(unsigned char));
-+ for(i_col = 0; i_col < cat_rast_region->cols; i_col++)
-+ row_data[i_col] = 0 & 255;
-+
-+ for(i_row = 0; i_row < cat_rast_region->rows; i_row++) {
-+ fwrite(row_data, sizeof(unsigned char), (cat_rast_region->cols)/sizeof(unsigned char), f_cat_rast);
-+ if (ferror(f_cat_rast))
-+ {
-+ fclose(f_cat_rast);
-+ G_warning(_("Unable to write into category raster condition file <%s>."), cat_rast);
-+ return -1;
-+ }
-+ }
-+
-+ fclose(f_cat_rast);
-+ return 0;
-+}
-+
-+static int print_reg(struct Cell_head * intersec, const char * pref, int dbg_level)
-+{
-+ G_debug(dbg_level, "%s:\n n:%f\ns:%f\ne:%f\nw:%f\nns_res:%f\new_res:%f", pref, intersec->north, intersec->south,
-+ intersec->east, intersec->west, intersec->ns_res, intersec->ew_res);
-+}
-+
-+/*!
-+ \brief Find intersection region of two regions.
-+
-+ \param A pointer to intersected region
-+ \param B pointer to intersected region
-+ \param [out] intersec pointer to intersection region of regions A B (relevant params of the region are: south, north, east, west)
-+
-+ \return 0 if interection exists
-+ \return -1 if regions does not intersect
-+ */
-+static int regions_intersecion(struct Cell_head * A, struct Cell_head * B, struct Cell_head * intersec)
-+{
-+
-+ if(B->north < A->south) return -1;
-+ else if(B->north > A->north) intersec->north = A->north;
-+ else intersec->north = B->north;
-+
-+ if(B->south > A->north) return -1;
-+ else if(B->south < A->south) intersec->south = A->south;
-+ else intersec->south = B->south;
-+
-+ if(B->east < A->west) return -1;
-+ else if(B->east > A->east) intersec->east = A->east;
-+ else intersec->east = B->east;
-+
-+ if(B->west > A->east) return -1;
-+ else if(B->west < A->west) intersec->west = A->west;
-+ else intersec->west = B->west;
-+
-+ if(intersec->north == intersec->south) return -1;
-+
-+ if(intersec->east == intersec->west) return -1;
-+
-+ return 0;
-+
-+}
-+
-+/*!
-+ \brief Get rows and cols numbers, which defines intersection of the regions.
-+
-+ \param A pointer to intersected region
-+ \param B pointer to intersected region (A and B must have same resolution)
-+ \param [out] A_bounds rows and cols numbers of A stored in south, north, east, west, which defines intersection of A and B
-+ \param [out] B_bounds rows and cols numbers of B stored in south, north, east, west, which defines intersection of A and B
-+
-+ \return 0 if interection exists
-+ \return -1 if regions do not intersect
-+ \return -2 resolution of regions is not same
++/*! Holds list of all scatter plots, which belongs to category.
+*/
-+static int get_rows_and_cols_bounds(struct Cell_head * A, struct Cell_head * B, struct Cell_head * A_bounds, struct Cell_head * B_bounds)
++struct scScatts
+{
-+ float ns_res, ew_res;
-+
-+ struct Cell_head intersec;
-+
-+ /* TODO is it right check? */
-+ if(abs(A->ns_res - B->ns_res) > GRASS_EPSILON) {
-+ G_debug(0, "'get_rows_and_cols_bounds' ns_res does not fit, A->ns_res: %f B->ns_res: %f", A->ns_res, B->ns_res);
-+ return -2;
-+ }
-+
-+ if(abs(A->ew_res - B->ew_res) > GRASS_EPSILON) {
-+ G_debug(0, "'get_rows_and_cols_bounds' ew_res does not fit, A->ew_res: %f B->ew_res: %f", A->ew_res, B->ew_res);
-+ return -2;
-+ }
-+
-+ ns_res = A->ns_res;
-+ ew_res = A->ew_res;
-+
-+ if(regions_intersecion(A, B, &intersec) == -1)
-+ return -1;
-+
-+ A_bounds->north = ceil((A->north - intersec.north - ns_res * 0.5) / ns_res);
-+ A_bounds->south = ceil((A->north - intersec.south - ns_res * 0.5) / ns_res);
-+
-+ A_bounds->east = ceil((intersec.east - A->west - ew_res * 0.5) / ew_res);
-+ A_bounds->west = ceil((intersec.west - A->west - ew_res * 0.5) / ew_res);
-+
-+ B_bounds->north = ceil((B->north - intersec.north - ns_res * 0.5) / ns_res);
-+ B_bounds->south = ceil((B->north - intersec.south - ns_res * 0.5) / ns_res);
-+
-+ B_bounds->east = ceil((intersec.east - B->west - ew_res * 0.5) / ew_res);
-+ B_bounds->west = ceil((intersec.west - B->west - ew_res * 0.5) / ew_res);
-+
-+ return 0;
-+}
-+
-+/*!
-+ \brief Insert raster map patch into pgm file.
-+
-+ \param patch_rast name of raster map
-+ \param cat_rast_region region of category raster file
-+ \param cat_rast path to category raster file
-+
-+ \return 0 on success
-+ \return -1 on failure
-+*/
-+int I_insert_patch_to_cat_rast(const char * patch_rast, struct Cell_head * cat_rast_region, const char * cat_rast)
-+{
-+
-+ FILE * f_cat_rast;
-+ struct Cell_head patch_region, patch_bounds, cat_rast_bounds;
-+ char cat_rast_header[1024];//TODO magic number
-+ int i_row, i_col, ncols, nrows, cat_rast_col, patch_col, val;
-+ int head_nchars, ret;
-+ int fd_patch_rast, init_shift, step_shift;
-+ unsigned char * patch_data;
-+
-+ char * null_chunk_row;
-+
-+ const char *mapset;
-+
-+ struct Cell_head patch_lines, cat_rast_lines;
-+
-+ unsigned char * row_data;
-+
-+ f_cat_rast = fopen(cat_rast, "rb+");
-+ if(!f_cat_rast) {
-+ G_warning(_("Unable to open category raster condtions file <%s>."), cat_rast);
-+ return -1;
-+ }
-+
-+ head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
-+ if ((mapset = G_find_raster(patch_rast,"")) == NULL) {
-+ fclose(f_cat_rast);
-+ G_warning(_("Unable to find patch raster <%s>."), patch_rast);
-+ return -1;
-+ }
-+
-+ Rast_get_cellhd(patch_rast, mapset, &patch_region);
-+ Rast_set_window(&patch_region);
-+
-+ if ((fd_patch_rast = Rast_open_old(patch_rast, mapset)) < 0) {
-+ fclose(f_cat_rast);
-+ return -1;
-+ }
-+
-+ ret = get_rows_and_cols_bounds(cat_rast_region, &patch_region, &cat_rast_bounds, &patch_bounds);
-+ if(ret == -2) {
-+ G_warning(_("Resolutions of patch <%s> and patched file <%s> are not same."), patch_rast, cat_rast);
-+
-+ Rast_close(fd_patch_rast);
-+ fclose(f_cat_rast);
-+
-+ return -1;
-+ }
-+ else if (ret == -1){
-+
-+ Rast_close(fd_patch_rast);
-+ fclose(f_cat_rast);
-+
-+ return 0;
-+ }
-+
-+ ncols = cat_rast_bounds.east - cat_rast_bounds.west;
-+ nrows = cat_rast_bounds.south - cat_rast_bounds.north;
-+
-+ patch_data = (unsigned char *) G_malloc(ncols * sizeof(unsigned char));
-+
-+ init_shift = head_nchars + cat_rast_region->cols * cat_rast_bounds.north + cat_rast_bounds.west;
-+
-+ if(fseek(f_cat_rast, init_shift, SEEK_SET) != 0) {
-+ G_warning(_("Corrupted category raster conditions file <%s> (fseek failed)"), cat_rast);
-+
-+ Rast_close(fd_patch_rast);
-+ G_free(null_chunk_row);
-+ fclose(f_cat_rast);
-+
-+ return -1;
-+ }
-+
-+ step_shift = cat_rast_region->cols - ncols;
-+
-+ null_chunk_row = Rast_allocate_null_buf();
++ int n_a_scatts; /*!< number of used/active scatter plots*/
+
-+ for(i_row = 0; i_row < nrows; i_row++) {
-+ Rast_get_null_value_row (fd_patch_rast, null_chunk_row, i_row + patch_bounds.north);
++ int * scatts_bands; /*!< array of bands for which represents the scatter plots,
++ every scatter plot has assigned two bads (size of array is n_a_scatts * 2)*/
++ int * scatt_idxs; /*!< (scatt_id->scatt_idx) internal idx of the scatter plot (position in scatts_arr)*/
+
-+ for(i_col = 0; i_col < ncols; i_col++) {
-+ patch_col = patch_bounds.west + i_col;
++ struct scdScattData ** scatts_arr; /*!< array of pointers to scdScattData */
++};
+
-+ if(null_chunk_row[patch_col] != 1)
-+ patch_data[i_col] = 1 & 255;
-+ else {
-+ patch_data[i_col] = 0 & 255;
-+ }
-+ }
-+
-+ fwrite(patch_data, sizeof(unsigned char), (ncols)/sizeof(unsigned char), f_cat_rast);
-+ if (ferror(f_cat_rast))
-+ {
-+ G_warning(_("Unable to write into category raster conditions file <%s>"), cat_rast);
-+
-+ Rast_close(fd_patch_rast);
-+ G_free(null_chunk_row);
-+ fclose(f_cat_rast);
-+
-+ return -1;
-+ }
-+ if(fseek(f_cat_rast, step_shift, SEEK_CUR) != 0) {
-+ G_warning(_("Corrupted category raster conditions file <%s> (fseek failed)"), cat_rast);
-+
-+ Rast_close(fd_patch_rast);
-+ G_free(null_chunk_row);
-+ fclose(f_cat_rast);
-+
-+ return -1;
-+ }
-+ }
-+
-+ Rast_close(fd_patch_rast);
-+ G_free(null_chunk_row);
-+ fclose(f_cat_rast);
-+ return 0;
-+}
-+
-+/*!
-+ \brief Updates scatter plots data in category by pixels which meets category conditions.
-+
-+ \param bands_rows data represents data describig one row from raster band
-+ \param belongs_pix array which defines which pixels belongs to category (1 value) and which not (0 value)
-+ \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, which are modified according to values in belongs_pix
++/*! Holds scatter plot data.
+*/
-+static inline void update_cat_scatt_plts(struct rast_row * bands_rows, unsigned short * belongs_pix, struct scScatts * scatts)
++struct scdScattData
+{
-+ int band_axis_1, band_axis_2, i_scatt, array_idx, cat_idx, i_chunk_rows_pix, max_arr_idx;
++ int n_vals; /*!< Number of values in scatter plot. */
+
-+ CELL * b_1_row;
-+ CELL * b_2_row;
-+ char * b_1_null_row,* b_2_null_row;
-+ struct rast_row b_1_rast_row, b_2_rast_row;
++ unsigned char * b_conds_arr; /*!< array of selected areas (used for SC_SCATT_CONDITIONS type) otherwise NULL */
++ unsigned int * scatt_vals_arr; /*!< array of computed areas (used for SC_SCATT_DATA type) otherwise NULL */
++};
+
-+ struct Range b_1_range, b_2_range;
-+ int b_1_range_size;
+
-+ int row_size = Rast_window_cols();
+ #define SIGNATURE_TYPE_MIXED 1
+
+ #define GROUPFILE "CURGROUP"
+Index: gui/wxpython/scatt_plot/gthreading.py
+===================================================================
+--- gui/wxpython/scatt_plot/gthreading.py (revision 0)
++++ gui/wxpython/scatt_plot/gthreading.py (working copy)
+@@ -0,0 +1,133 @@
++"""!
++ at package scatt_plot.gthreading
+
-+ int * scatts_bands = scatts->scatts_bands;
++Classes:
+
-+ for(i_scatt = 0; i_scatt < scatts->n_a_scatts; i_scatt++)
-+ {
-+ b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
-+ b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
++(C) 2013 by the GRASS Development Team
+
-+ b_1_row = b_1_rast_row.row;
-+ b_2_row = b_2_rast_row.row;
++This program is free software under the GNU General Public License
++(>=v2). Read the file COPYING that comes with GRASS for details.
+
-+ b_1_null_row = b_1_rast_row.null_row;
-+ b_2_null_row = b_2_rast_row.null_row;
++ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
++"""
+
-+ b_1_range = b_1_rast_row.rast_range;
-+ b_2_range = b_2_rast_row.rast_range;
-+
-+ b_1_range_size = b_1_range.max - b_1_range.min + 1;
-+ max_arr_idx = (b_1_range.max - b_1_range.min + 1) * (b_2_range.max - b_2_range.min + 1);
++import os
++import sys
++import time
++import threading
++import Queue
+
-+ for(i_chunk_rows_pix = 0; i_chunk_rows_pix < row_size; i_chunk_rows_pix++)
-+ {
-+ /* pixel does not belongs to scatter plot or has null value in one of the bands */
-+ if(!belongs_pix[i_chunk_rows_pix] ||
-+ b_1_null_row[i_chunk_rows_pix] == 1 ||
-+ b_2_null_row[i_chunk_rows_pix] == 1)
-+ continue;
++import wx
++from core.gconsole import wxCmdRun, wxCmdDone, wxCmdPrepare
+
-+ /* index in scatter plot array */
-+ array_idx = b_1_row[i_chunk_rows_pix] - b_1_range.min + (b_2_row[i_chunk_rows_pix] - b_2_range.min) * b_1_range_size;
++class gThread(threading.Thread):
++ """!Thread for GRASS commands"""
++ requestId = 0
+
-+ if(array_idx < 0 || array_idx >= max_arr_idx) {
-+ G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
-+ continue;
-+ }
++ def __init__(self, receiver, requestQ=None, resultQ=None, **kwds):
++ """!
++ @param receiver event receiver (used in PostEvent)
++ """
++ threading.Thread.__init__(self, **kwds)
+
-+ /* increment scatter plot value */
-+ ++scatts->scatts_arr[i_scatt]->scatt_vals_arr[array_idx];
-+ }
-+ }
-+}
++ if requestQ is None:
++ self.requestQ = Queue.Queue()
++ else:
++ self.requestQ = requestQ
+
-+/*!
-+ \brief Computes scatter plots data from chunk_rows.
++ if resultQ is None:
++ self.resultQ = Queue.Queue()
++ else:
++ self.resultQ = resultQ
+
-+ \param scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
-+ \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are selected areas (condtitions)stored
++ self.setDaemon(True)
+
-+ \param chunk_rows data arrays of chunk_rows from analyzed raster bands (all data in chunk_rows, null_chunk_rows and belongs_pix arrays represents same region)
-+ \param null_chunk_rows null data arrays of chunk_rows from analyzed raster bands
-+ \param row_size size of data in chunk_rows, null_chunk_rows and belongs_pix arrays
-+ \param f_cats_rasts_conds file which stores selected areas (conditions) from mapwindow see I_create_cat_rast() and I_pa
-+ \param fd_cats_rasts array of openedraster maps which represents all selected pixels for category
-+ \param region analysis region
++ self.receiver = receiver
++ self._want_abort_all = False
+
-+ \return 0 on success
-+ \return -1 on failure
-+*/
-+static inline int compute_scatts_from_chunk_row(struct Cell_head *region, struct scCats * scatt_conds,
-+ FILE ** f_cats_rasts_conds, struct rast_row * bands_rows,
-+ struct scCats * scatts, int * fd_cats_rasts)
-+{
++ self.start()
+
-+ int i_rows_pix, i_cat, i_scatt, n_a_scatts, n_pixs;
-+ int cat_id, scatt_plts_cat_idx, array_idx, max_arr_idx;
-+ char * b_1_null_row,* b_2_null_row;
-+ struct rast_row b_1_rast_row, b_2_rast_row;
-+ CELL * cat_rast_row;
++ def Run(self, *args, **kwds):
++ """!Run command in queue
+
-+ struct scScatts * scatts_conds;
-+ struct scScatts * scatts_scatt_plts;
-+ struct scdScattData * conds;
++ @param args unnamed command arguments
++ @param kwds named command arguments
+
-+ struct Range b_1_range, b_2_range;
-+ int b_1_range_size;
++ @return request id in queue
++ """
++ gThread.requestId += 1
++ self.requestQ.put((gThread.requestId, args, kwds))
+
-+ int * scatts_bands;
-+ struct scdScattData ** scatts_arr;
++ return gThread.requestId
+
-+ CELL * b_1_row;
-+ CELL * b_2_row;
-+ unsigned char * i_scatt_conds;
++ def GetId(self):
++ """!Get id for next command"""
++ return gThread.requestId + 1
+
-+ int row_size = Rast_window_cols();
++ def SetId(self, id):
++ """!Set starting id"""
++ gThread.requestId = id
+
-+ unsigned short * belongs_pix = (unsigned short *) G_malloc(row_size * sizeof(unsigned short));
-+ unsigned char * rast_pixs = (unsigned char *) G_malloc(row_size * sizeof(unsigned char));
-+ cat_rast_row = Rast_allocate_c_buf();
++ def run(self):
++ os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
++ while True:
++ requestId, args, kwds = self.requestQ.get()
++ for key in ('callable', 'onDone', 'onPrepare', 'userData'):
++ if key in kwds:
++ vars()[key] = kwds[key]
++ del kwds[key]
++ else:
++ vars()[key] = None
+
-+
-+ for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
-+ {
-+ scatts_conds = scatt_conds->cats_arr[i_cat];
++ requestTime = time.time()
+
-+ cat_id = scatt_conds->cats_ids[i_cat];
++ #if self._want_abort_all and self.requestCmd is not None:
++ # self.requestCmd.abort()
++ # if self.requestQ.empty():
++ # self._want_abort_all = False
+
-+ scatt_plts_cat_idx = scatts->cats_idxs[cat_id];
-+ if(scatt_plts_cat_idx < 0)
-+ continue;
-+ scatts_scatt_plts = scatts->cats_arr[scatt_plts_cat_idx];
++ # prepare
++ if self.receiver:
++ event = wxCmdPrepare(type = 'method',
++ time=requestTime,
++ pid=requestId)
+
-+ G_zero(belongs_pix, row_size * sizeof(unsigned short));
++ wx.PostEvent(self.receiver, event)
+
-+ /* if category has no conditions defined, scatter plots without any constraint are computed (default scatter plots) */
-+ if(!scatts_conds->n_a_scatts && !f_cats_rasts_conds[i_cat]) {
-+ for(i_scatt = 0; i_scatt < scatts_scatt_plts->n_a_scatts; i_scatt++)
-+ {
-+ /* all pixels belongs */
-+ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
-+ belongs_pix[i_rows_pix] = 1;
-+ }
-+ }
-+ /* compute belonging pixels for defined conditions */
-+ else
-+ {
-+ scatts_bands = scatts_conds->scatts_bands;
++ # run command
++ event = wxCmdRun(type = 'method',
++ pid=requestId)
+
-+ /* check conditions from category raster condtitions file */
-+ if(f_cats_rasts_conds[i_cat]) {
-+ n_pixs = fread(rast_pixs, sizeof(unsigned char), (row_size)/sizeof(unsigned char), f_cats_rasts_conds[i_cat]);
++ wx.PostEvent(self.receiver, event)
+
-+ if (ferror(f_cats_rasts_conds[i_cat]))
-+ {
-+ G_free(rast_pixs);
-+ G_free(belongs_pix);
-+ G_warning(_("Unable to read from category raster condtition file."));
-+ return -1;
-+ }
-+ if (n_pixs != n_pixs) {
-+ G_free(rast_pixs);
-+ G_free(belongs_pix);
-+ G_warning(_("Invalid size of category raster conditions file."));
-+ return -1;
++ time.sleep(.1)
+
-+ }
-+
-+ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
-+ {
-+ if(rast_pixs[i_rows_pix] != 0 & 255)
-+ belongs_pix[i_rows_pix] = 1;
-+ }
-+ }
-+
-+ /* check condtions defined in scatter plots*/
-+ for(i_scatt = 0; i_scatt < scatts_conds->n_a_scatts; i_scatt++)
-+ {
-+ b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
-+ b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
-+
-+ b_1_row = b_1_rast_row.row;
-+ b_2_row = b_2_rast_row.row;
-+
-+ b_1_null_row = b_1_rast_row.null_row;
-+ b_2_null_row = b_2_rast_row.null_row;
-+
-+ b_1_range = b_1_rast_row.rast_range;
-+ b_2_range = b_2_rast_row.rast_range;
-+
-+ b_1_range_size = b_1_range.max - b_1_range.min + 1;
-+ max_arr_idx = (b_1_range.max - b_1_range.min + 1) * (b_2_range.max - b_2_range.min + 1);
-+
-+ i_scatt_conds = scatts_conds->scatts_arr[i_scatt]->b_conds_arr;
-+
-+ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
-+ {
-+ /* pixels already belongs to category from category raster conditions file or contains null value in one of the bands */
-+ if(belongs_pix[i_rows_pix] ||
-+ b_1_null_row[i_rows_pix] == 1 ||
-+ b_2_null_row[i_rows_pix] == 1)
-+ continue;
-+
-+ array_idx = b_1_row[i_rows_pix] - b_1_range.min + (b_2_row[i_rows_pix] - b_2_range.min) * b_1_range_size;
-+ if(array_idx < 0 || array_idx >= max_arr_idx) {
-+ G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
-+ continue;
-+ }
-+ /* pixels meets condtion defined in scatter plot */
-+ if(i_scatt_conds[array_idx])
-+ belongs_pix[i_rows_pix] = 1;
-+ }
-+ }
-+ }
-+
-+ /* update category raster with belonging pixels */
-+ if(fd_cats_rasts[i_cat] >= 0) {
-+ Rast_set_null_value(cat_rast_row, Rast_window_cols(), CELL_TYPE);
-+
-+ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
-+ if(belongs_pix[i_rows_pix])
-+ cat_rast_row[i_rows_pix] = belongs_pix[i_rows_pix];
-+
-+ Rast_put_c_row (fd_cats_rasts[i_cat], cat_rast_row);
-+ }
-+
-+ /* update scatter plots with belonging pixels */
-+ update_cat_scatt_plts(bands_rows, belongs_pix, scatts_scatt_plts);
-+ }
-+
-+ G_free(cat_rast_row);
-+ G_free(rast_pixs);
-+ G_free(belongs_pix);
-+
-+ return 0;
-+}
-+
-+/*!
-+ \brief Get list if bands needed to be opened for analysis from scCats struct.
-+*/
-+static void get_needed_bands(struct scCats * cats, int * b_needed_bands)
-+{
-+ // results in b_needed_bands - array of bools - if item has value 1, band (defined by item index) is needed to be opened
-+ int i_cat, i_scatt, cat_id;
-+
-+ for(i_cat = 0; i_cat < cats->n_a_cats; i_cat++)
-+ {
-+ for(i_scatt = 0; i_scatt < cats->cats_arr[i_cat]->n_a_scatts; i_scatt++)
-+ {
-+ G_debug(3, "Active scatt %d in catt %d", i_scatt, i_cat);
-+
-+ b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2]] = 1;
-+ b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2 + 1]] = 1;
-+ }
-+ }
-+ return;
-+}
-+
-+/*!
-+ \brief Helper function for clean up.
-+*/
-+static void free_compute_scatts_data(int * fd_bands, struct rast_row * bands_rows, int n_a_bands, int * bands_ids,
-+ int * fd_cats_rasts, FILE ** f_cats_rasts_conds, int n_a_cats)
-+{
-+ int i, band_id;
-+
-+ for(i = 0; i < n_a_bands; i++)
-+ {
-+ band_id = bands_ids[i];
-+ if(band_id >= 0) {
-+ Rast_close(fd_bands[i]);
-+ G_free(bands_rows[band_id].row);
-+ G_free(bands_rows[band_id].null_row);
-+ }
-+ }
-+
-+ if(f_cats_rasts_conds)
-+ for(i = 0; i < n_a_cats; i++)
-+ if(f_cats_rasts_conds[i])
-+ fclose(f_cats_rasts_conds[i]);
-+
-+ if(fd_cats_rasts)
-+ for(i = 0; i < n_a_cats; i++)
-+ if(fd_cats_rasts[i] >= 0)
-+ Rast_close(fd_cats_rasts[i]);
-+
-+}
-+
-+/*!
-+ \brief Compute scatter plots data.
-+
-+ If category has not defined no category raster condition file and no scatter plot with consdtion,
-+ default scatter plot is computed.
-+
-+ \param region analysis region, beaware that all input data must be prepared for this region (bands (their ranges), cats_rasts_conds rasters...)
-+ \param region function calls Rast_set_window for this region
-+ \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are stored selected areas (conditions) in scatter plots
-+ \param cats_rasts_conds paths to category raster conditions files representing selected areas (conditions) in rasters for every category
-+ \param cats_rasts_conds index in array represents corresponding category id
-+ \param cats_rasts_conds for manupulation with category raster conditions file see also I_id_scatt_to_bands() and I_insert_patch_to_cat_rast()
-+ \param bands names of analyzed bands, order of bands is defined by their id
-+ \param n_bands number of bands
-+ \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
-+ \param [out] cats_rasts array of raster maps names where will be stored all selected pixels for every category
-+
-+ \return 0 on success
-+ \return -1 on failure
-+*/
-+int I_compute_scatts(struct Cell_head *region, struct scCats * scatt_conds, const char ** cats_rasts_conds,
-+ const char ** bands, int n_bands, struct scCats * scatts, const char ** cats_rasts)
-+{
-+ const char *mapset;
-+ char header[1024];
-+
-+ int fd_cats_rasts[scatt_conds->n_a_cats];
-+ FILE * f_cats_rasts_conds[scatt_conds->n_a_cats];
-+
-+ struct rast_row bands_rows[n_bands];
-+
-+ RASTER_MAP_TYPE data_type;
-+
-+ int nrows, i_band, n_a_bands, band_id,
-+ i, i_row, head_nchars, i_cat, id_cat;
-+
-+ int fd_bands[n_bands];
-+ int bands_ids[n_bands];
-+ int b_needed_bands[n_bands];
-+
-+ Rast_set_window(region);
-+
-+ for(i_band = 0; i_band < n_bands; i_band++)
-+ fd_bands[i_band] = -1;
-+
-+ for(i_band = 0; i_band < n_bands; i_band++)
-+ bands_ids[i_band] = -1;
-+
-+ if (n_bands != scatts->n_bands ||
-+ n_bands != scatt_conds->n_bands)
-+ return -1;
-+
-+ memset(b_needed_bands, 0, (size_t)n_bands * sizeof(int));
-+
-+ get_needed_bands(scatt_conds, &b_needed_bands[0]);
-+ get_needed_bands(scatts, &b_needed_bands[0]);
-+
-+ n_a_bands = 0;
-+
-+ /* open band rasters, which are needed for computation */
-+ for(band_id = 0; band_id < n_bands; band_id++)
-+ {
-+ if(b_needed_bands[band_id])
-+ {
-+ G_debug(3, "Opening raster no. %d with name: %s", band_id, bands[band_id]);
-+
-+ if ((mapset = G_find_raster2(bands[band_id],"")) == NULL) {
-+ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands,
-+ bands_ids, NULL, NULL, scatt_conds->n_a_cats);
-+ G_warning(_("Unbale to read find raster <%s>"), bands[band_id]);
-+ return -1;
-+ }
++ ret = None
++ exception = None
+
-+ if ((fd_bands[n_a_bands] = Rast_open_old(bands[band_id], mapset)) < 0) {
-+ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands,
-+ bands_ids, NULL, NULL, scatt_conds->n_a_cats);
-+ G_warning(_("Unbale to open raster <%s>"), bands[band_id]);
-+ return -1;
-+ }
++ #to
++ #try:
++ ret = vars()['callable'](*args, **kwds)
++ #except Exception as e:
++ # exception = e;
+
-+ data_type = Rast_get_map_type(fd_bands[n_a_bands]);
-+ if(data_type != CELL_TYPE) {
-+ G_warning(_("Raster <%s> type is not <%s>"), bands[band_id], "CELL");
-+ return -1;
-+ }
++ self.resultQ.put((requestId, ret))
+
-+ bands_rows[band_id].row = Rast_allocate_c_buf();
-+ bands_rows[band_id].null_row = Rast_allocate_null_buf();
++ time.sleep(.1)
+
-+ if(Rast_read_range(bands[band_id], mapset, &bands_rows[band_id].rast_range) != 1){
-+ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands,
-+ bands_ids, NULL, NULL, scatt_conds->n_a_cats);
-+ G_warning(_("Unable to read range of raster <%s>"), bands[band_id]);
-+ return -1;
-+ }
++ if self.receiver:
++ event = wxCmdDone(kwds = kwds,
++ args = args, #TODO expand args to kwds
++ ret=ret,
++ exception=exception,
++ pid=requestId)
+
-+ bands_ids[n_a_bands] = band_id;
-+ ++n_a_bands;
-+ }
-+ }
++ # send event
++ wx.PostEvent(self.receiver, event)
+
-+ /* open category rasters condition files and category rasters */
-+ for(i_cat = 0; i_cat < scatts->n_a_cats; i_cat++)
-+ {
-+ id_cat = scatts->cats_ids[i_cat];
-+ if(cats_rasts[id_cat]) {
-+ fd_cats_rasts[i_cat] = Rast_open_new(cats_rasts[id_cat], CELL_TYPE);
-+ }
-+ else
-+ fd_cats_rasts[i_cat] = -1;
-+
-+ if(cats_rasts_conds[id_cat]) {
-+ f_cats_rasts_conds[i_cat] = fopen(cats_rasts_conds[id_cat], "r");
-+ if(!f_cats_rasts_conds[i_cat]) {
-+ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids,
-+ f_cats_rasts_conds, f_cats_rasts_conds, scatt_conds->n_a_cats);
-+ G_warning(_("Unable to open category raster condtition file <%s>"), bands[band_id]);
-+ return -1;
-+ }
-+ }
-+ else
-+ f_cats_rasts_conds[i_cat] = NULL;
-+ }
-+
-+ head_nchars = get_cat_rast_header(region, header);
-+ for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
-+ if(f_cats_rasts_conds[i_cat])
-+ if( fseek(f_cats_rasts_conds[i_cat] , head_nchars, SEEK_SET) != 0) {
-+ G_warning(_("Corrupted category raster conditions file (fseek failed)"));
-+ return -1;
-+ }
-+
-+ nrows = Rast_window_rows();
-+
-+ /* analyze bands by rows */
-+ for (i_row = 0; i_row < nrows; i_row++)
-+ {
-+ for(i_band = 0; i_band < n_a_bands; i_band++)
-+ {
-+ band_id = bands_ids[i_band];
-+ Rast_get_c_row(fd_bands[i_band], bands_rows[band_id].row, i_row);
-+ Rast_get_null_value_row (fd_bands[i_band], bands_rows[band_id].null_row, i_row);
-+ }
-+ if(compute_scatts_from_chunk_row(region, scatt_conds, f_cats_rasts_conds, bands_rows, scatts, fd_cats_rasts) == -1)
-+ {
-+ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, fd_cats_rasts,
-+ f_cats_rasts_conds, scatt_conds->n_a_cats);
-+ return -1;
-+ }
-+
-+ }
-+ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids,
-+ fd_cats_rasts, f_cats_rasts_conds, scatt_conds->n_a_cats);
-+ return 0;
-+}
++ def abort(self, abortall=True):
++ """!Abort command(s)"""
++ if abortall:
++ self._want_abort_all = True
++ if self.requestQ.empty():
++ self._want_abort_all = False
\ No newline at end of file
-Index: lib/imagery/scatt_sccats.c
+Index: gui/wxpython/scatt_plot/dialogs.py
===================================================================
---- lib/imagery/scatt_sccats.c (revision 0)
-+++ lib/imagery/scatt_sccats.c (working copy)
-@@ -0,0 +1,405 @@
-+/*!
-+ \file lib/imagery/scatt_cat_rast.c
+--- gui/wxpython/scatt_plot/dialogs.py (revision 0)
++++ gui/wxpython/scatt_plot/dialogs.py (working copy)
+@@ -0,0 +1,142 @@
++"""!
++ at package scatt_plot.dialogs
+
-+ \brief Imagery library - functions for manipulation with scatter plot structs.
++ at brief GUI.
+
-+ Copyright (C) 2013 by the GRASS Development Team
++Classes:
+
-+ This program is free software under the GNU General Public License
-+ (>=v2). Read the file COPYING that comes with GRASS for details.
++(C) 2013 by the GRASS Development Team
+
-+ \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
-+ */
++This program is free software under the GNU General Public License
++(>=v2). Read the file COPYING that comes with GRASS for details.
+
-+#include <grass/raster.h>
-+#include <grass/imagery.h>
-+#include <grass/gis.h>
++ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
++"""
++import os
++import sys
+
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <math.h>
-+#include <string.h>
++import wx
++from scatt_plot.scatt_core import idBandsToidScatt
+
-+/*!
-+ \brief Compute band ids from scatter plot id.
++class AddScattPlotDialog(wx.Dialog):
+
-+ Scatter plot id describes which bands defines the scatter plot.
++ def __init__(self, parent, bands, id = wx.ID_ANY):
++
++ wx.Dialog.__init__(self, parent, title = ("Add scatter plot"), id = id)
+
-+ Let say we have 3 bands, their ids are 0, 1 and 2.
-+ Scatter plot with id 0 consists of band 1 (b_1_id) 0 and band 2 (b_2_id) 1.
-+ All scatter plots:
-+ scatt_id b_1_id b_2_id
-+ 0 0 1
-+ 1 0 2
-+ 2 1 2
++ self.bands = bands
+
-+ \param scatt_id scatter plot id
-+ \param n_bands number of bands
-+ \param [out] b_1_id id of band1
-+ \param[out] b_2_id id of band2
++ self.scatt_id = None
+
-+ \return 0
-+ */
-+int I_id_scatt_to_bands(const int scatt_id, const int n_bands, int * b_1_id, int * b_2_id)
-+{
-+ int n_b1 = n_bands - 1;
++ self._createWidgets()
+
-+ * b_1_id = (int) ((2 * n_b1 + 1 - sqrt((double)((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2);
++ def _createWidgets(self):
+
-+ * b_2_id = scatt_id - ((* b_1_id) * (2 * n_b1 + 1) - (* b_1_id) * (* b_1_id)) / 2 + (* b_1_id) + 1;
++ self.labels = {}
++ self.params = {}
+
-+ return 0;
-+}
++ self.band_1_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Band 1:"))
+
++ self.band_1_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
++ choices = self.bands,
++ style = wx.CB_READONLY, size = (350, 30))
+
-+/*!
-+ \brief Compute scatter plot id from band ids.
++ self.band_2_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Band 2:"))
+
-+ See also I_id_scatt_to_bands().
++ self.band_2_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
++ choices = self.bands,
++ style = wx.CB_READONLY, size = (350, 30))
+
-+ \param n_bands number of bands
-+ \param b_1_id id of band1
-+ \param b_1_id id of band2
-+ \param [out] scatt_id scatter plot id
++ # buttons
++ self.btn_close = wx.Button(parent = self, id = wx.ID_CANCEL)
++
++ self.btn_ok = wx.Button(parent = self, id = wx.ID_OK, label = _("&OK"))
+
-+ \return 0
-+ */
-+int I_bands_to_id_scatt(const int b_1_id, const int b_2_id, const int n_bands, int * scatt_id)
-+{
-+ int n_b1 = n_bands - 1;
++ self._layout()
+
-+ * scatt_id = (b_1_id * (2 * n_b1 + 1) - b_1_id * b_1_id) / 2 + b_2_id - b_1_id - 1;
++ def _layout(self):
+
-+ return 0;
-+}
++ border = wx.BoxSizer(wx.VERTICAL)
++ dialogSizer = wx.BoxSizer(wx.VERTICAL)
+
-+/*!
-+ \brief Initialize structure for storing scatter plots data.
++ regionSizer = wx.BoxSizer(wx.HORIZONTAL)
+
-+ \param cats pointer to scCats struct
-+ \param n_bands number of bands
-+ \param type SC_SCATT_DATA - stores scatter plots
-+ \param type SC_SCATT_CONDITIONS - stores selected areas in scatter plots
-+ */
-+void I_sc_init_cats(struct scCats * cats, int n_bands, int type)
-+{
-+ int i_cat;
++ dialogSizer.Add(item = self._addSelectSizer(title = self.band_1_label,
++ sel = self.band_1_ch))
+
-+ cats->type = type;
++ dialogSizer.Add(item = self._addSelectSizer(title = self.band_2_label,
++ sel = self.band_2_ch))
+
-+ cats->n_cats = 100;
-+ cats->n_a_cats = 0;
++ # buttons
++ self.btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
+
-+ cats->n_bands = n_bands;
-+ cats->n_scatts = (n_bands - 1) * n_bands / 2;
++ self.btnsizer.Add(item = self.btn_close, proportion = 0,
++ flag = wx.ALL | wx.ALIGN_CENTER,
++ border = 10)
++
++ self.btnsizer.Add(item = self.btn_ok, proportion = 0,
++ flag = wx.ALL | wx.ALIGN_CENTER,
++ border = 10)
+
-+ cats->cats_arr = (struct scScatts **) G_malloc(cats->n_cats * sizeof(struct scScatts *));
-+ memset(cats->cats_arr, 0, cats-> n_cats * sizeof(struct scScatts *));
++ dialogSizer.Add(item = self.btnsizer, proportion = 0,
++ flag = wx.ALIGN_CENTER)
+
-+ cats->cats_ids = (int *) G_malloc(cats->n_cats * sizeof(int));
-+ cats->cats_idxs =(int *) G_malloc(cats->n_cats * sizeof(int));
++ border.Add(item = dialogSizer, proportion = 0,
++ flag = wx.ALL, border = 5)
+
-+ for(i_cat = 0; i_cat < cats->n_cats; i_cat++)
-+ cats->cats_idxs[i_cat] = -1;
++ self.SetSizer(border)
++ self.Layout()
++ self.Fit()
+
-+ return;
-+}
++ # bindings
++ self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
++ self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
+
-+/*!
-+ \brief Free data of struct scCats, the structure itself remains alocated.
++ def _addSelectSizer(self, title, sel):
++ """!Helper layout function.
++ """
++ selSizer = wx.BoxSizer(orient = wx.VERTICAL)
+
-+ \param cats pointer to existing scCats struct
-+ */
-+void I_sc_free_cats(struct scCats * cats)
-+{
-+ int i_cat;
++ selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
++ selTitleSizer.Add(item = title, proportion = 1,
++ flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
+
-+ for(i_cat = 0; i_cat < cats->n_a_cats; i_cat++)
-+ {
-+ if(cats->cats_arr[i_cat])
-+ {
-+ G_free(cats->cats_arr[i_cat]->scatt_idxs);
-+ G_free(cats->cats_arr[i_cat]->scatts_bands);
-+ G_free(cats->cats_arr[i_cat]->scatts_arr);
-+ G_free(cats->cats_arr[i_cat]);
-+ }
-+ }
++ selSizer.Add(item = selTitleSizer, proportion = 0,
++ flag = wx.EXPAND)
+
-+ G_free(cats->cats_ids);
-+ G_free(cats->cats_idxs);
-+ G_free(cats->cats_arr);
++ selSizer.Add(item = sel, proportion = 1,
++ flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
++ border = 5)
+
-+ cats->n_cats = 0;
-+ cats->n_a_cats = 0;
-+ cats->n_bands = 0;
-+ cats->n_scatts = 0;
-+ cats->type = -1;
++ return selSizer
+
-+ return;
-+}
++ def OnClose(self, event):
++ """!Close dialog
++ """
++ if not self.IsModal():
++ self.Destroy()
++ event.Skip()
+
-+#if 0
-+void I_sc_get_active_categories(int * a_cats_ids, int * n_a_cats, struct scCats * cats)
-+{
-+ a_cats_ids = cats->cats_ids;
-+ * n_a_cats = cats->n_a_cats;
-+}
-+#endif
++ def OnOk(self, event):
++ """!
++ """
++ band_1 = self.band_1_ch.GetSelection()
++ band_2 = self.band_2_ch.GetSelection()
+
-+/*!
-+ \brief Add category.
-+
-+ Category represents group of scatter plots.
+
-+ \param cats pointer to scCats struct
++ if band_1 == band_2:
++ GError(_("Selected bands must be different."))
++ return
++
++ #TODO axes selection
++ if band_1 > band_2:
++ tmp_band = band_2
++ band_2 = band_1
++ band_1 = band_2
+
-+ \return assigned category id (starts with 0)
-+ \return -1 if maximum nuber of categories was reached
-+ */
-+int I_sc_add_cat(struct scCats * cats)
-+{
-+ int i_scatt, i_cat_id, cat_id;
-+ int n_a_cats = cats->n_a_cats;
++ self.scatt_id = idBandsToidScatt(band_1, band_2, len(self.bands))
+
-+ if(cats->n_a_cats >= cats->n_cats)
-+ return -1;
++ event.Skip()
+
-+ for(i_cat_id = 0; i_cat_id < cats->n_cats; i_cat_id++)
-+ if(cats->cats_idxs[i_cat_id] < 0) {
-+ cat_id = i_cat_id;
-+ break;
-+ }
-+
-+ cats->cats_ids[n_a_cats] = cat_id;
-+ cats->cats_idxs[cat_id] = n_a_cats;
-+
-+ cats->cats_arr[n_a_cats] = (struct scScatts *) G_malloc(sizeof(struct scScatts));
-+
-+ cats->cats_arr[n_a_cats]->scatts_arr = (struct scdScattData **) G_malloc(cats->n_scatts * sizeof(struct scdScattData *));
-+ memset((cats->cats_arr[n_a_cats]->scatts_arr), 0, cats->n_scatts * sizeof(struct scdScattData *));
-+
-+ cats->cats_arr[n_a_cats]->n_a_scatts = 0;
-+
-+ cats->cats_arr[n_a_cats]->scatts_bands = (int *) G_malloc(cats->n_scatts * 2 * sizeof(int));
-+
-+ cats->cats_arr[n_a_cats]->scatt_idxs = (int *) G_malloc(cats->n_scatts * sizeof(int));
-+ for(i_scatt = 0; i_scatt < cats->n_scatts; i_scatt++)
-+ cats->cats_arr[n_a_cats]->scatt_idxs[i_scatt] = -1;
-+
-+ ++cats->n_a_cats;
-+
-+ return cat_id;
-+}
-+
-+#if 0
-+int I_sc_delete_cat(struct scCats * cats, int cat_id)
-+{
-+ int cat_idx, i_cat;
-+
-+ if(cat_id < 0 || cat_id >= cats->n_cats)
-+ return -1;
-+
-+ cat_idx = cats->cats_idxs[cat_id];
-+ if(cat_idx < 0)
-+ return -1;
-+
-+ G_free(cats->cats_arr[cat_idx]->scatt_idxs);
-+ G_free(cats->cats_arr[cat_idx]->scatts_bands);
-+ G_free(cats->cats_arr[cat_idx]->scatts_arr);
-+ G_free(cats->cats_arr[cat_idx]);
-+
-+ for(i_cat = cat_idx; i_cat < cats->n_a_cats - 1; i_cat++)
-+ {
-+ cats->cats_arr[i_cat] = cats->cats_arr[i_cat + 1];
-+ cats->cats_ids[i_cat] = cats->cats_ids[i_cat + 1];
-+ }
-+ cats->cats_idxs[cat_id] = -1;
-+
-+ --cats->n_a_cats;
-+
-+ return 0;
-+}
-+#endif
-+
-+/*!
-+ \brief Insert scatter plot data .
-+ Inserted scatt_data struct must have same type as cats struct (SC_SCATT_DATA or SC_SCATT_CONDITIONS).
-+
-+ \param cats pointer to scCats struct
-+ \param cat_id id number of category.
-+ \param scatt_id id number of scatter plot.
-+
-+ \return 0 on success
-+ \return -1 on failure
-+ */
-+int I_sc_insert_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
-+{
-+ int band_1, band_2, cat_idx, n_a_scatts;
-+ struct scScatts * scatts;
-+
-+ if(cat_id < 0 || cat_id >= cats->n_cats)
-+ return -1;
-+
-+ cat_idx = cats->cats_idxs[cat_id];
-+ if(cat_idx < 0)
-+ return -1;
-+
-+ if(scatt_id < 0 && scatt_id >= cats->n_scatts)
-+ return -1;
-+
-+ scatts = cats->cats_arr[cat_idx];
-+ if(scatts->scatt_idxs[scatt_id] >= 0)
-+ return -1;
-+
-+ if(!scatt_data->b_conds_arr && cats->type == SC_SCATT_CONDITIONS)
-+ return -1;
-+
-+ if(!scatt_data->scatt_vals_arr && cats->type == SC_SCATT_DATA)
-+ return -1;
-+
-+ n_a_scatts = scatts->n_a_scatts;
-+
-+ scatts->scatt_idxs[scatt_id] = n_a_scatts;
-+
-+ I_id_scatt_to_bands(scatt_id, cats->n_bands, &band_1, &band_2);
-+
-+ scatts->scatts_bands[n_a_scatts * 2] = band_1;
-+ scatts->scatts_bands[n_a_scatts * 2 + 1] = band_2;
-+
-+ scatts->scatts_arr[n_a_scatts] = scatt_data;
-+ ++scatts->n_a_scatts;
-+
-+ return 0;
-+}
-+
-+#if 0
-+int I_sc_remove_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
-+{
-+ int cat_idx, scatt_idx, n_init_scatts, i_scatt;
-+ struct scScatts * scatts;
-+
-+ if(cat_id < 0 && cat_id >= cats->n_cats)
-+ return -1;
-+
-+ cat_idx = cats->cats_idxs[cat_id];
-+ if(cat_idx < 0)
-+ return -1;
-+
-+ if(scatt_id < 0 || scatt_id >= cats->n_scatts)
-+ return -1;
-+
-+ scatts = cats->cats_arr[cat_idx];
-+ if(scatts->scatt_idxs[scatt_id] < 0)
-+ return -1;
-+
-+ scatt_data = scatts->scatts_arr[scatt_idx];
-+
-+ for(i_scatt = scatt_idx; i_scatt < scatts->n_a_scatts - 1; i_scatt++)
-+ {
-+ scatts->scatts_arr[i_scatt] = scatts->scatts_arr[i_scatt + 1];
-+ scatts->scatts_bands[i_scatt * 2] = scatts->scatts_bands[(i_scatt + 1)* 2];
-+ scatts->scatts_bands[i_scatt * 2 + 1] = scatts->scatts_bands[(i_scatt + 1) * 2 + 1];
-+ }
-+ scatts->scatts_arr[scatts->n_a_scatts] = NULL;
-+
-+ scatts->scatt_idxs[scatt_id] = -1;
-+
-+ scatt_data = scatts->scatts_arr[scatt_id];
-+ scatts->n_a_scatts--;
-+
-+ return 0;
-+}
-+
-+int I_sc_set_value(struct scCats * cats, int cat_id, int scatt_id, int value_idx, int value)
-+{
-+ int n_a_scatts = cats->cats_arr[cat_id]->n_a_scatts;
-+ int cat_idx, scatt_idx, ret;
-+
-+ cat_idx = cats->cats_idxs[cat_id];
-+ if(cat_idx < 0)
-+ return -1;
-+
-+ if(cats->cats_arr[cat_idx]->scatt_idxs[scatt_id] < 0)
-+ return -1;
-+
-+ cat_idx = cats->cats_idxs[cat_id];
-+ scatt_idx = cats->cats_arr[cat_idx]->scatt_idxs[scatt_id];
-+
-+ I_scd_set_value(cats->cats_arr[cat_idx]->scatts_arr[scatt_idx], value_idx, value);
-+
-+ return 0;
-+}
-+#endif
-+
-+/*!
-+ \brief Insert scatter plot data.
-+
-+ \param scatt_data pointer to existing struct scdScattData
-+ \param type SC_SCATT_DATA for scatter plots or SC_SCATT_CONDITIONS for selected areas in scatter plot
-+ \param n_vals number of data values
-+ \param data array of values (unsigned char for SC_SCATT_CONDITIONS, unsigned int for SC_SCATT_DATA)
-+ */
-+void I_scd_init_scatt_data(struct scdScattData * scatt_data, int type, int n_vals, void * data)
-+{
-+ scatt_data->n_vals = n_vals;
-+
-+ if(type == SC_SCATT_DATA)
-+ {
-+ if(data)
-+ scatt_data->scatt_vals_arr = (unsigned int *) data;
-+ else {
-+ scatt_data->scatt_vals_arr = (unsigned int *) G_malloc(n_vals * sizeof(unsigned int));
-+ memset(scatt_data->scatt_vals_arr, 0, n_vals * sizeof(unsigned int));
-+ }
-+ scatt_data->b_conds_arr = NULL;
-+ }
-+ else if(type == SC_SCATT_CONDITIONS)
-+ {
-+ if(data)
-+ scatt_data->b_conds_arr = (unsigned char *) data;
-+ else {
-+ scatt_data->b_conds_arr = (unsigned char *) G_malloc(n_vals * sizeof(unsigned char));
-+ memset(scatt_data->b_conds_arr, 0, n_vals * sizeof(unsigned char));
-+ }
-+ scatt_data->scatt_vals_arr = NULL;
-+ }
-+
-+ return;
-+}
-+
-+
-+#if 0
-+void I_scd_get_range_min_max(struct scdScattData * scatt_data, CELL * band_1_min, CELL * band_1_max, CELL * band_2_min, CELL * band_2_max)
-+{
-+
-+ Rast_get_range_min_max(&(scatt_data->band_1_range), band_1_min, band_2_min);
-+ Rast_get_range_min_max(&(scatt_data->band_2_range), band_2_min, band_2_max);
-+
-+ return;
-+}
-+s
-+void * I_scd_get_data_ptr(struct scdScattData * scatt_data)
-+{
-+ if(!scatt_data->b_conds_arr)
-+ return scatt_data->b_conds_arr;
-+ else if(!scatt_data->scatt_vals_arr)
-+ return scatt_data->scatt_vals_arr;
-+
-+ return NULL;
-+}
-+
-+int I_scd_set_value(struct scdScattData * scatt_data, unsigned int val_idx, unsigned int val)
-+{
-+ if(val_idx < 0 && val_idx > scatt_data->n_vals)
-+ return -1;
-+
-+ if(scatt_data->b_conds_arr)
-+ scatt_data->b_conds_arr[val_idx] = val;
-+ else if(scatt_data->scatt_vals_arr)
-+ scatt_data->scatt_vals_arr[val_idx] = val;
-+ else
-+ return -1;
-+
-+ return 0;
-+}
-+#endif
-Index: include/imagery.h
++ def GetScattId(self):
++ return self.scatt_id
+Index: gui/wxpython/scatt_plot/toolbars.py
===================================================================
---- include/imagery.h (revision 57546)
-+++ include/imagery.h (working copy)
-@@ -135,6 +135,56 @@
-
- } IClass_statistics;
-
-+/* Scatter Plot backend */
+--- gui/wxpython/scatt_plot/toolbars.py (revision 0)
++++ gui/wxpython/scatt_plot/toolbars.py (working copy)
+@@ -0,0 +1,178 @@
++"""!
++ at package scatt_plot.toolbars
+
-+#define SC_SCATT_DATA 0
-+#define SC_SCATT_CONDITIONS 1
++ at brief Scatter plot - toolbars
+
++Classes:
++ - toolbars::MainToolbar
+
-+/*! Holds list of all catagories.
-+ It can contain selected areas for scatter plots (SC_SCATT_CONDITIONS type) or computed scatter plots (SC_SCATT_DATA type).
-+*/
-+struct scCats
-+{
-+ int type; /*!< SC_SCATT_DATA -> computed scatter plots, SC_SCATT_CONDITIONS -> set conditions for scatter plots to be computed*/
++(C) 2013 by the GRASS Development Team
+
-+ int n_cats; /*!< number of alocated categories */
-+
-+ int n_bands; /*!< number of analyzed bands */
-+ int n_scatts; /*!< number of possible scattter plot which can be created from bands */
++This program is free software under the GNU General Public License
++(>=v2). Read the file COPYING that comes with GRASS for details.
+
-+ int n_a_cats; /*!< number of used/active categories */
-+ int * cats_ids; /*!< (cat_idx->cat_id) array index is internal idx (position in cats_arr) and id is saved in it's position*/
-+ int * cats_idxs; /*!< (cat_id->cat_idx) array index is id and internal idx is saved in it's position*/
++ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
++"""
++import wx
+
-+ struct scScatts ** cats_arr; /*!< array of pointers to struct scScatts */
-+};
++from icons.icon import MetaIcon
++from gui_core.toolbars import BaseToolbar, BaseIcons
++from core.gcmd import RunCommand
++from core.gcmd import GException, GError, RunCommand
++from scatt_plot.scatt_core import idBandsToidScatt
+
+
-+/*! Holds list of all scatter plots, which belongs to category.
-+*/
-+struct scScatts
-+{
-+ int n_a_scatts; /*!< number of used/active scatter plots*/
-+
-+ int * scatts_bands; /*!< array of bands for which represents the scatter plots,
-+ every scatter plot has assigned two bads (size of array is n_a_scatts * 2)*/
-+ int * scatt_idxs; /*!< (scatt_id->scatt_idx) internal idx of the scatter plot (position in scatts_arr)*/
++class MainToolbar(BaseToolbar):
++ """!Main toolbar
++ """
++ def __init__(self, parent, scatt_mgr):
++ BaseToolbar.__init__(self, parent)
++ self.scatt_mgr = scatt_mgr
+
-+ struct scdScattData ** scatts_arr; /*!< array of pointers to scdScattData */
-+};
++ self.InitToolbar(self._toolbarData())
++
++ # realize the toolbar
++ self.Realize()
+
-+/*! Holds scatter plot data.
-+*/
-+struct scdScattData
-+{
-+ int n_vals; /*!< Number of values in scatter plot. */
++ def _toolbarData(self):
+
-+ unsigned char * b_conds_arr; /*!< array of selected areas (used for SC_SCATT_CONDITIONS type) otherwise NULL */
-+ unsigned int * scatt_vals_arr; /*!< array of computed areas (used for SC_SCATT_DATA type) otherwise NULL */
-+};
++ icons = {
++ 'settings' : BaseIcons['settings'].SetLabel( _('Ssettings')),
++ 'help' : MetaIcon(img = 'help',
++ label = _('Show manual')),
++ 'add_scatt_pl' : MetaIcon(img = 'layer-raster-analyze',
++ label = _('Add scatter plot')),
++ 'selCatPol' : MetaIcon(img = 'polygon-create',
++ label = _('Select area with polygon')),
++ 'pan' : MetaIcon(img = 'pan',
++ label = _('Pan'),
++ desc = _('Pan scatter plot')),
++ 'zoomIn' : MetaIcon(img = 'zoom-in',
++ label = _('Zoom'),
++ desc = _('Zoom whith mouse wheel')),
++ 'cats_mgr' : MetaIcon(img = 'table-manager',
++ label = _('Show/hide class manager'))
++ }
+
++ return self._getToolbarData((
++ ("cats_mgr", icons['cats_mgr'],
++ lambda event: self.parent.ShowCategoryPanel(event.Checked()), wx.ITEM_CHECK),
++ (None, ),
++ ("pan", icons["pan"],
++ lambda event: self.SetPloltsMode(event, 'pan'),
++ wx.ITEM_CHECK),
++ ("zoom", icons["zoomIn"],
++ lambda event: self.SetPloltsMode(event, 'zoom'),
++ wx.ITEM_CHECK),
++ ('sel_pol_mode', icons['selCatPol'],
++ self.ActivateSelectionPolygonMode,
++ wx.ITEM_CHECK),
++ (None, ),
++ ('add_scatt', icons["add_scatt_pl"],
++ lambda event : self.scatt_mgr.AddScattPlot())
++ #('settings', icon["settings"],
++ # self.parent.OnSettings),
++ #('help', icons["help"],
++ # self.OnHelp),
++ ))
+
- #define SIGNATURE_TYPE_MIXED 1
-
- #define GROUPFILE "CURGROUP"
-Index: include/defs/imagery.h
-===================================================================
---- include/defs/imagery.h (revision 57546)
-+++ include/defs/imagery.h (working copy)
-@@ -110,6 +110,23 @@
- FILE *I_fopen_subgroup_ref_new(const char *, const char *);
- FILE *I_fopen_subgroup_ref_old(const char *, const char *);
-
-+/* scatt_plt.c */
-+void I_sc_init_cats(struct scCats *, int, int);
-+void I_sc_free_cats(struct scCats *);
-+int I_sc_add_cat(struct scCats *);
-+int I_sc_insert_scatt_data(struct scCats *, struct scdScattData *, int, int);
++ def GetToolId(self, toolName): #TODO can be useful in base
+
-+void I_scd_init_scatt_data(struct scdScattData *, int, int, void *);
++ return vars(self)[toolName]
+
-+int I_compute_scatts(struct Cell_head *, struct scCats *, const char **,
-+ const char **, int, struct scCats *, const char **);
++ def SetPloltsMode(self, event, tool_name):
+
-+int I_create_cat_rast(struct Cell_head *, const char *);
-+int I_insert_patch_to_cat_rast(const char *, struct Cell_head *, const char *);
++ if event.Checked() == True:
++ for i_tool_data in self._data:
++ i_tool_name = i_tool_data[0]
++ if not i_tool_name or i_tool_name == "cats_mgr":
++ continue
++ if i_tool_name == tool_name:
++ continue
++ i_tool_id = vars(self)[i_tool_name]
++ self.ToggleTool(i_tool_id, False)
+
-+int I_id_scatt_to_bands(const int, const int, int *, int *);
-+int I_bands_to_id_scatt(const int, const int, const int, int *);
-+
- /* sig.c */
- int I_init_signatures(struct Signature *, int);
- int I_new_signature(struct Signature *);
-Index: include/defs/vedit.h
-===================================================================
---- include/defs/vedit.h (revision 57546)
-+++ include/defs/vedit.h (working copy)
-@@ -33,6 +33,8 @@
- int Vedit_merge_lines(struct Map_info *, struct ilist *);
-
- /* move.c */
-+int Vedit_move_areas(struct Map_info *, struct Map_info **, int,
-+ struct ilist *, double, double, double, int, double);
- int Vedit_move_lines(struct Map_info *, struct Map_info **, int,
- struct ilist *, double, double, double, int, double);
-
-Index: gui/wxpython/mapdisp/toolbars.py
-===================================================================
---- gui/wxpython/mapdisp/toolbars.py (revision 57546)
-+++ gui/wxpython/mapdisp/toolbars.py (working copy)
-@@ -239,7 +239,8 @@
- (MapIcons["scatter"], self.parent.OnScatterplot),
- (MapIcons["histogram"], self.parent.OnHistogramPyPlot),
- (BaseIcons["histogramD"], self.parent.OnHistogram),
-- (MapIcons["vnet"], self.parent.OnVNet)))
-+ (MapIcons["vnet"], self.parent.OnVNet),
-+ (MapIcons["scatter"], self.parent.OnScatterplot2)))
-
- def OnDecoration(self, event):
- """!Decorations overlay menu
-Index: gui/wxpython/mapdisp/frame.py
-===================================================================
---- gui/wxpython/mapdisp/frame.py (revision 57546)
-+++ gui/wxpython/mapdisp/frame.py (working copy)
-@@ -225,6 +225,7 @@
- #
- self.dialogs = {}
- self.dialogs['attributes'] = None
-+ self.dialogs['scatt_plot'] = None
- self.dialogs['category'] = None
- self.dialogs['barscale'] = None
- self.dialogs['legend'] = None
-@@ -1168,6 +1169,19 @@
- """!Returns toolbar with zooming tools"""
- return self.toolbars['map']
-
-+ def OnScatterplot2(self, event):
-+ """!Init interactive scatterplot tools
-+ """
-+ if self.dialogs['scatt_plot']:
-+ self.dialogs['scatt_plot'].Raise()
-+ return
-+
-+ from scatt_plot.dialogs import ScattPlotMainDialog
-+ self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface)
-+
-+ self.dialogs['scatt_plot'].CenterOnScreen()
-+ self.dialogs['scatt_plot'].Show()
-+
- def OnVNet(self, event):
- """!Dialog for v.net* modules
- """
-Index: gui/wxpython/iclass/dialogs.py
-===================================================================
---- gui/wxpython/iclass/dialogs.py (revision 57546)
-+++ gui/wxpython/iclass/dialogs.py (working copy)
-@@ -333,13 +333,19 @@
- toolbar.SetCategories(catNames = catNames, catIdx = cats)
- if name in catNames:
- toolbar.choice.SetStringSelection(name)
-+ cat = toolbar.GetSelectedCategoryIdx()
- elif catNames:
- toolbar.choice.SetSelection(0)
--
-+ cat = toolbar.GetSelectedCategoryIdx()
++ self.scatt_mgr.SetPlotsMode(mode = tool_name)
+ else:
-+ cat = None
++ self.scatt_mgr.SetPlotsMode(mode = None)
+
- if toolbar.choice.IsEmpty():
- toolbar.EnableControls(False)
- else:
- toolbar.EnableControls(True)
++ def ActivateSelectionPolygonMode(self, event):
+
-+ self.mapWindow.CategoryChanged(cat)
- # don't forget to update maps, histo, ...
-
- def GetSelectedIndices(self, state = wx.LIST_STATE_SELECTED):
-Index: gui/wxpython/iclass/toolbars.py
-===================================================================
---- gui/wxpython/iclass/toolbars.py (revision 57546)
-+++ gui/wxpython/iclass/toolbars.py (working copy)
-@@ -46,9 +46,7 @@
- 'importAreas' : MetaIcon(img = 'layer-import',
- label = _('Import training areas from vector map')),
- 'addRgb' : MetaIcon(img = 'layer-rgb-add',
-- label = _('Add RGB map layer')),
-- 'scatt_plot' : MetaIcon(img = 'layer-raster-analyze',
-- label = _('Open Scatter Plot Tool (EXPERIMENTAL GSoC 2013)')),
-+ label = _('Add RGB map layer'))
- }
-
- class IClassMapToolbar(BaseToolbar):
-@@ -117,10 +115,7 @@
- ("zoomBack", icons["zoomBack"],
- self.parent.OnZoomBack),
- ("zoomToMap", icons["zoomExtent"],
-- self.parent.OnZoomToMap),
-- (None, ),
-- ("scatt_plot", iClassIcons["scatt_plot"],
-- self.parent.OnScatterplot)
-+ self.parent.OnZoomToMap)
- ))
- class IClassToolbar(BaseToolbar):
- """!IClass toolbar
-@@ -156,7 +151,7 @@
- """!Toolbar data"""
- icons = iClassIcons
- return self._getToolbarData((("selectGroup", icons['selectGroup'],
-- self.parent.OnAddBands),
-+ lambda event : self.parent.AddBands()),
- (None, ),
- ("classManager", icons['classManager'],
- self.parent.OnCategoryManager),
-Index: gui/wxpython/iclass/frame.py
-===================================================================
---- gui/wxpython/iclass/frame.py (revision 57546)
-+++ gui/wxpython/iclass/frame.py (working copy)
-@@ -64,6 +64,8 @@
- IClassExportAreasDialog, IClassMapDialog
- from iclass.plots import PlotPanel
-
-+from grass.pydispatch.signal import Signal
++ activated = self.scatt_mgr.ActivateSelectionPolygonMode(event.Checked())
++ self.parent.ShowPlotEditingToolbar(activated)
+
- class IClassMapFrame(DoubleMapFrame):
- """! wxIClass main frame
-
-@@ -114,6 +116,10 @@
- lambda:
- self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(None))
- self.SetSize(size)
++ i_tool_id = vars(self)['sel_pol_mode']
++ self.ToggleTool(i_tool_id, activated)
+
-+ self.groupSet = Signal("IClassMapFrame.groupSet")
-+ self.categoryChanged = Signal('IClassMapFrame.categoryChanged')
++class EditingToolbar(BaseToolbar):
++ """!Main toolbar
++ """
++ def __init__(self, parent, scatt_mgr):
++ BaseToolbar.__init__(self, parent)
++ self.scatt_mgr = scatt_mgr
+
- #
- # Add toolbars
- #
-@@ -177,7 +183,7 @@
- self.dialogs['category'] = None
-
- # PyPlot init
-- self.plotPanel = PlotPanel(self, stats_data = self.stats_data)
-+ self.plotPanel = PlotPanel(self, giface = self._giface, stats_data = self.stats_data)
-
- self._addPanes()
- self._mgr.Update()
-@@ -237,7 +243,7 @@
- return False
-
- return vectorName
--
-+
- def RemoveTempVector(self):
- """!Removes temporary vector map with training areas"""
- ret = RunCommand(prog = 'g.remove',
-@@ -477,7 +483,7 @@
-
- self.Render(self.GetFirstWindow())
-
-- def OnAddBands(self, event):
-+ def AddBands(self):
- """!Add imagery group"""
- dlg = IClassGroupDialog(self, group = self.group)
- if dlg.ShowModal() == wx.ID_OK:
-@@ -488,7 +494,8 @@
- """!Set imagery group"""
- group = grass.find_file(name = name, element = 'group')
- if group['name']:
-- self.group = group['name']
-+ self.group = group['name']
-+ self.groupSet.emit(group = group['name'])
- else:
- GError(_("Group <%s> not found") % name, parent = self)
-
-@@ -768,17 +775,20 @@
-
- Updates number of stddev, histograms, layer in preview display.
- """
-- stat = self.stats_data.GetStatistics(currentCat)
-- nstd = stat.nstd
-- self.toolbars['iClass'].UpdateStddev(nstd)
--
-- self.plotPanel.UpdateCategory(currentCat)
-- self.plotPanel.OnPlotTypeSelected(None)
-+ if currentCat:
-+ stat = self.stats_data.GetStatistics(currentCat)
-+ nstd = stat.nstd
-+ self.toolbars['iClass'].UpdateStddev(nstd)
-+
-+ self.plotPanel.UpdateCategory(currentCat)
-+ self.plotPanel.OnPlotTypeSelected(None)
-
-- name = stat.rasterName
-- name = self.previewMapManager.GetAlias(name)
-- if name:
-- self.previewMapManager.SelectLayer(name)
-+ name = stat.rasterName
-+ name = self.previewMapManager.GetAlias(name)
-+ if name:
-+ self.previewMapManager.SelectLayer(name)
++ self.InitToolbar(self._toolbarData())
++
++ # realize the toolbar
++ self.Realize()
+
-+ self.categoryChanged.emit(cat = currentCat)
-
- def DeleteAreas(self, cats):
- """!Removes all training areas of given categories
-@@ -1105,27 +1115,6 @@
- self.GetFirstWindow().SetModePointer()
- self.GetSecondWindow().SetModePointer()
-
-- def OnScatterplot(self, event):
-- """!Init interactive scatterplot tools
-- """
-- if self.dialogs['scatt_plot']:
-- self.dialogs['scatt_plot'].Raise()
-- return
--
-- try:
-- from scatt_plot.dialogs import ScattPlotMainDialog
-- except:
-- GError(parent = self, message = _("The Scatter Plot Tool is not installed."))
-- return
--
-- self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface, iclass_mapwin = self.GetFirstWindow())
--
-- scatt_mgr = self.dialogs['scatt_plot'].GetScattMgr()
-- scatt_mgr.DigitDataChanged(self.toolbars['vdigit'].mapLayer.GetName(), self.GetFirstWindow().GetDigit())
--
-- self.dialogs['scatt_plot'].CenterOnScreen()
-- self.dialogs['scatt_plot'].Show()
--
- class MapManager:
- """! Class for managing map renderer.
-
-Index: gui/wxpython/iclass/plots.py
-===================================================================
---- gui/wxpython/iclass/plots.py (revision 57546)
-+++ gui/wxpython/iclass/plots.py (working copy)
-@@ -28,7 +28,7 @@
- for each band and for one category. Coincidence plots show min max range
- of classes for each band.
- """
-- def __init__(self, parent, stats_data):
-+ def __init__(self, parent, giface, stats_data):
- scrolled.ScrolledPanel.__init__(self, parent)
-
- self.SetupScrolling(scroll_x = False, scroll_y = True)
-@@ -38,26 +38,64 @@
- self.stats_data = stats_data
- self.currentCat = None
-
-+ self._giface = giface
-+
- self.mainSizer = wx.BoxSizer(wx.VERTICAL)
--
-+
- self._createControlPanel()
--
-+ self._createPlotPanel()
-+ self._createScatterPlotPanel()
-+
- self.SetSizer(self.mainSizer)
- self.mainSizer.Fit(self)
- self.Layout()
--
-+
-+ def _createPlotPanel(self):
-+
-+ self.canvasPanel = wx.Panel(parent=self)
-+ self.mainSizer.Add(item = self.canvasPanel, proportion = 1, flag = wx.EXPAND, border = 0)
-+ self.canvasSizer = wx.BoxSizer(wx.VERTICAL)
-+ self.canvasPanel.SetSizer(self.canvasSizer)
-+
- def _createControlPanel(self):
- self.plotSwitch = wx.Choice(self, id = wx.ID_ANY,
- choices = [_("Histograms"),
-- _("Coincident plots")])
-+ _("Coincident plots"),
-+ _("Scatter plots")])
- self.mainSizer.Add(self.plotSwitch, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
- self.plotSwitch.Bind(wx.EVT_CHOICE, self.OnPlotTypeSelected)
--
-+
-+ def _createScatterPlotPanel(self):
-+ """!Init interactive scatterplot tools
++ def _toolbarData(self):
++ """!Toolbar data
+ """
-+ try:
-+ from scatt_plot.frame import IClassScatterPlotsPanel
-+ self.scatt_plot_panel = IClassScatterPlotsPanel(parent=self, giface=self._giface, iclass_mapwin = self.parent.GetFirstWindow())
-+ self.mainSizer.Add(self.scatt_plot_panel, proportion = 1, flag = wx.EXPAND, border = 0)
-+ self.scatt_plot_panel.Hide()
-+ except ImportError as e:#TODO
-+ print "ahoj"
-+ print e
-+ self.scatt_plot_panel = None
++ self.icons = {
++ 'sel_add' : MetaIcon(img = 'layer-add',
++ label = _('Include selected area to class.'),
++ desc = _('Include selected area to class.')),
++ 'sel_remove' : MetaIcon(img = 'layer-remove',
++ label = _('Exclude selected area from class.'),
++ desc = _('Exclude selected area from class.')),
++ 'addVertex' : MetaIcon(img = 'vertex-create',
++ label = _('Add new vertex'),
++ desc = _('Add new vertex to polygon boundary scatter plot')),
++ 'editLine' : MetaIcon(img = 'line-edit',
++ label = _('Edit line/boundary'),
++ desc = _('Add new vertex between last and first points of the boundary')),
++ 'moveVertex' : MetaIcon(img = 'vertex-move',
++ label = _('Move vertex'),
++ desc = _('Move boundary vertex')),
++ 'removeVertex' : MetaIcon(img = 'vertex-delete',
++ label = _('Remove vertex'),
++ desc = _('Remove boundary vertex.')),
++ }
+
- def OnPlotTypeSelected(self, event):
- """!Plot type selected"""
++ return self._getToolbarData((
++ ("sel_add", self.icons["sel_add"],
++ lambda event: self.scatt_mgr.ProcessSelectionPolygons('add')),
++ ("sel_remove", self.icons['sel_remove'],
++ lambda event: self.scatt_mgr.ProcessSelectionPolygons('remove')),
++ (None, ),
++ ("add_vertex", self.icons["editLine"],
++ lambda event: self.SetMode(event, 'add_vertex'),
++ wx.ITEM_CHECK),
++ ("add_boundary_vertex", self.icons['addVertex'],
++ lambda event: self.SetMode(event, 'add_boundary_vertex'),
++ wx.ITEM_CHECK),
++ ("move_vertex", self.icons["moveVertex"],
++ lambda event: self.SetMode(event, 'move_vertex'),
++ wx.ITEM_CHECK),
++ ('delete_vertex', self.icons['removeVertex'],
++ lambda event: self.SetMode(event, 'delete_vertex'),
++ wx.ITEM_CHECK)
++ ))
+
-+ if self.plotSwitch.GetSelection() in [0, 1]:
-+ self.SetupScrolling(scroll_x = False, scroll_y = True)
-+ self.scatt_plot_panel.Hide()
-+ self.canvasPanel.Show()
-+ self.Layout()
++ def SetMode(self, event, tool_name):
++ if event.Checked() == True:
++ for i_tool_data in self._data:
++ i_tool_name = i_tool_data[0]
++ if not i_tool_name:
++ continue
++ if i_tool_name == tool_name:
++ continue
++ i_tool_id = vars(self)[i_tool_name]
++ self.ToggleTool(i_tool_id, False)
++ self.scatt_mgr.SetPlotsEditingMode(tool_name)
++ else:
++ self.scatt_mgr.SetPlotsEditingMode(None)
+
-+ elif self.plotSwitch.GetSelection() == 2:
-+ self.SetupScrolling(scroll_x = False, scroll_y = False)
-+ self.scatt_plot_panel.Show()
-+ self.canvasPanel.Hide()
-+ self.Layout()
-+
- if self.currentCat is None:
- return
--
-+
- if self.plotSwitch.GetSelection() == 0:
- stat = self.stats_data.GetStatistics(self.currentCat)
- if not stat.IsReady():
-@@ -66,7 +104,10 @@
- self.DrawHistograms(stat)
- else:
- self.DrawCoincidencePlots()
--
-+
-+ self.Layout()
-+
-+
- def StddevChanged(self):
- """!Standard deviation multiplier changed, redraw histograms"""
- if self.plotSwitch.GetSelection() == 0:
-@@ -89,7 +130,7 @@
- panel.Destroy()
-
- self.canvasList = []
--
-+
- def ClearPlots(self):
- """!Clears plot canvases"""
- for bandIdx in range(len(self.bandList)):
-@@ -104,15 +145,15 @@
- def CreatePlotCanvases(self):
- """!Create plot canvases according to the number of bands"""
- for band in self.bandList:
-- canvas = plot.PlotCanvas(self)
-+ canvas = plot.PlotCanvas(self.canvasPanel)
- canvas.SetMinSize((-1, 140))
- canvas.SetFontSizeTitle(10)
- canvas.SetFontSizeAxis(8)
- self.canvasList.append(canvas)
-
-- self.mainSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
--
-- self.SetVirtualSize(self.GetBestVirtualSize())
-+ self.canvasSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
-+
-+ self.SetVirtualSize(self.GetBestVirtualSize())
- self.Layout()
-
- def UpdatePlots(self, group, currentCat, stats_data):
-@@ -138,7 +179,7 @@
-
- def UpdateCategory(self, cat):
- self.currentCat = cat
--
-+
- def DrawCoincidencePlots(self):
- """!Draw coincidence plots"""
- for bandIdx in range(len(self.bandList)):
++ def GetToolId(self, toolName):
++ return vars(self)[toolName]
Index: gui/wxpython/scatt_plot/scatt_core.py
===================================================================
--- gui/wxpython/scatt_plot/scatt_core.py (revision 0)
+++ gui/wxpython/scatt_plot/scatt_core.py (working copy)
-@@ -0,0 +1,785 @@
+@@ -0,0 +1,784 @@
+"""!
+ at package scatt_plot.scatt_plot
+
@@ -1742,7 +673,7 @@
+ bbox[k] = self._validExtend(v)
+
+ arr[bbox['btm_y'] : bbox['up_y'], bbox['btm_x'] : bbox['up_x']] = value
-+ arr.flush()
++ #arr.flush()
+ #del arr
+
+ start_time = time.clock()
@@ -1806,7 +737,7 @@
+ arr = self.scatt_conds_dt.GetValuesArr(cat_id, scatt_id)
+
+ arr[raster_ind] = value
-+ arr.flush()
++ #arr.flush()
+
+ rescaled = (255.0 / arr.max() * (arr - arr.min())).astype(np.uint8)
+ im = Image.fromarray(rescaled)
@@ -2114,7 +1045,6 @@
+ shape = (b_i['b2']['max'] - b_i['b2']['min'] + 1, b_i['b1']['max'] - b_i['b1']['min'] + 1)
+
+ np_vals = np.memmap(grass.tempfile(), dtype=self.dtype, mode='w+', shape = shape)
-+ np_vals.flush()
+
+ self.cats[cat_id][scatt_id] = {
+ 'np_vals' : np_vals,
@@ -2603,7 +1533,7 @@
===================================================================
--- gui/wxpython/scatt_plot/frame.py (revision 0)
+++ gui/wxpython/scatt_plot/frame.py (working copy)
-@@ -0,0 +1,494 @@
+@@ -0,0 +1,543 @@
+"""!
+ at package scatt_plot.dialogs
+
@@ -2624,13 +1554,12 @@
+import wx
+import wx.lib.scrolledpanel as scrolled
+import wx.lib.mixins.listctrl as listmix
-+import wx.lib.flatnotebook as FN
-+import wx.aui
+
+from core import globalvar
+from core.gcmd import GException, GError, RunCommand
+
+from gui_core.gselect import Select
++from gui_core.dialogs import SetOpacityDialog
+
+from scatt_plot.controllers import ScattsManager
+from scatt_plot.toolbars import MainToolbar, EditingToolbar
@@ -2756,10 +1685,8 @@
+ event.pane.window.CleanUp()
+
+ def OnScrollChanged(self, event):
-+ print "changed"
+ wx.CallAfter(self.Layout)
+
-+
+ def OnScroll(self, event):
+ if self.ignore_scroll > 0:
+ self.ignore_scroll -= 1
@@ -2799,7 +1726,8 @@
+
+ self._mgr.AddPane(scatt,
+ aui.AuiPaneInfo().Dockable(True).Floatable(True).
-+ Name("scatter plot %d" % scatt_id).MinSize((-1, 300)).Caption(("%s x: %s y: %s") % (_("scatter plot"), bands[b1_id], bands[b2_id])).
++ Name("scatter plot %d" % scatt_id).MinSize((-1, 300)).
++ Caption(("%s x: %s y: %s") % (_("scatter plot"), bands[b1_id], bands[b2_id])).
+ Center().Position(1).MaximizeButton(True).
+ MinimizeButton(True).CaptionVisible(True).
+ CloseButton(True).Layer(0))
@@ -2835,7 +1763,10 @@
+ listmix.ListCtrlAutoWidthMixin.__init__(self)
+
+ listmix.TextEditMixin.__init__(self)
-+
++
++ self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnCategoryRightUp) #wxMSW
++ self.Bind(wx.EVT_RIGHT_UP, self.OnCategoryRightUp) #wxGTK
++
+ self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnEdit)
+ self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSel)
+
@@ -2955,27 +1886,75 @@
+ def OnGetItemAttr(self, item):
+ return None
+
-+ def OnClassRightUp(self, event):
++ def OnCategoryRightUp(self, event):
+ """!Show context menu on right click"""
+ item, flags = self.HitTest((event.GetX(), event.GetY()))
+ if item != wx.NOT_FOUND and flags & wx.LIST_HITTEST_ONITEM:
+ self.rightClickedItemIdx = item
-+
-+ self.popupZoomtoAreas = wx.NewId()
-+ self.Bind(wx.EVT_MENU, self.OnZoomToAreasByCat, id = self.popupZoomtoAreas)
+
+ # generate popup-menu
++
++ cat_id = self.cats_mgr.GetCategories()[self.rightClickedItemIdx]
++ showed = self.cats_mgr.GetCategoryAttrs(cat_id)['show']
++
+ menu = wx.Menu()
-+ menu.Append(self.popupZoomtoAreas, _("Zoom to training areas of selected class"))
-+
++
++ if showed:
++ text = _("Hide")
++ else:
++ text = _("Show")
++
++ item_id = wx.NewId()
++ menu.Append(item_id, text = text)
++ self.Bind(wx.EVT_MENU, lambda event : self._setCatAttrs(cat_id=cat_id,
++ attrs={'show' : not showed}),
++ id=item_id)
++
++ menu.AppendSeparator()
++ """
++ item_id = wx.NewId()
++ menu.Append(item_id, text=_("Move item up"))
++ self.Bind(wx.EVT_MENU, self.OnPopupOpacityLevel, id=item_id)
++
++ item_id = wx.NewId()
++ menu.Append(item_id, text=_("Move item down"))
++ self.Bind(wx.EVT_MENU, self.OnPopupOpacityLevel, id=item_id)
++
++ menu.AppendSeparator()
++ """
++ item_id = wx.NewId()
++ menu.Append(item_id, text=_("Change opacity level"))
++ self.Bind(wx.EVT_MENU, self.OnPopupOpacityLevel, id=item_id)
++
+ self.PopupMenu(menu)
+ menu.Destroy()
-+
-+ def OnZoomToAreasByCat(self, event):
-+ """!Zoom to areas of given category"""
-+ cat = self.stats_data.GetCategories()[self.rightClickedItemIdx]
-+ self.mapWindow.ZoomToAreasByCat(cat)
+
++ def OnPopupOpacityLevel(self, event):
++ """!Popup opacity level indicator"""
++
++ cat_id = self.cats_mgr.GetCategories()[self.rightClickedItemIdx]
++ cat_attrs = self.cats_mgr.GetCategoryAttrs(cat_id)
++ value = cat_attrs['opacity'] * 100
++ name = cat_attrs['name']
++
++ dlg = SetOpacityDialog(self, opacity = value,
++ title = _("Change opacity of class <%s>" % name))
++
++ dlg.applyOpacity.connect(lambda value:
++ self._setCatAttrs(cat_id=cat_id, attrs={'opacity' : value}))
++ dlg.CentreOnParent()
++
++ if dlg.ShowModal() == wx.ID_OK:
++ self._setCatAttrs(cat_id=cat_id, attrs='opacity', value=dlg.GetOpacity())
++
++ dlg.Destroy()
++
++ def _setCatAttrs(self, cat_id, attrs):
++ self.cats_mgr.setCategoryAttrs.disconnect(self.Update)
++ self.cats_mgr.SetCategoryAttrs(cat_id, attrs)
++ self.cats_mgr.setCategoryAttrs.connect(self.Update)
++
++
+class AddScattPlotDialog(wx.Dialog):
+
+ def __init__(self, parent, bands, id = wx.ID_ANY):
@@ -3118,7 +2097,7 @@
===================================================================
--- gui/wxpython/scatt_plot/plots.py (revision 0)
+++ gui/wxpython/scatt_plot/plots.py (working copy)
-@@ -0,0 +1,667 @@
+@@ -0,0 +1,671 @@
+"""!
+ at package scatt_plot.dialogs
+
@@ -3135,16 +2114,13 @@
+"""
+import wx
+import numpy as np
-+from numpy.lib.stride_tricks import as_strided
-+import random
++#TODO
++#from numpy.lib.stride_tricks import as_strided
+from copy import deepcopy
+
-+import scipy.misc as misc
-+
+try:
-+ haveMatPlot = True
+ import matplotlib
-+ #matplotlib.use('WXAgg')
++ matplotlib.use('WXAgg')
+ from matplotlib.figure import Figure
+ from matplotlib.backends.backend_wxagg import \
+ FigureCanvasWxAgg as FigCanvas, \
@@ -3156,8 +2132,9 @@
+ import matplotlib.image as mi
+ import matplotlib.colors as mcolors
+ import matplotlib.cbook as cbook
-+except ImportError:
-+ haveMatPlot = False
++except ImportError as e:
++ raise ImportError(_("Unable to import matplotlib (try to install it).\n%s") % e)
++
+from grass.pydispatch.signal import Signal
+
+#class PlotImages()?
@@ -3299,6 +2276,11 @@
+ init = True
+
+ for cat_id, scatt in scatts.iteritems():
++ #TODO make more general
++ if cat_id != 0 and (styles[cat_id]['opacity'] == 0.0 or \
++ not styles[cat_id]['show']):
++ continue
++
+ b1_i = scatt['bands_info']['b1']
+ b2_i = scatt['bands_info']['b2']
+
@@ -3333,18 +2315,19 @@
+ else:
+ #c_img_a = np.memmap(grass.tempfile(), dtype="uint16", mode='w+', shape = shape)
+
-+ c_img_a = colored_cat.astype('uint16')[:,:,3]
-+ c_img_ai= 255 - colored_cat.astype('uint16')[:,:,3]
++ c_img_a = colored_cat.astype('uint16')[:,:,3] * styles[cat_id]['opacity']
+
-+ #TODO strides
++ #TODO apply strides and there will be no need for loop
+ #b = as_strided(a, strides=(0, a.strides[3], a.strides[3], a.strides[3]), shape=(3, a.shape[0], a.shape[1]))
+ for i in range(3):
+ m_i = merged_img[:,:,i]
-+ merged_img[:,:,i] = (m_i * c_img_ai + colored_cat[:,:,i] * c_img_a) / 256;
++ merged_img[:,:,i] = (m_i * (255 - c_img_a) + colored_cat[:,:,i] * c_img_a) / 255;
+
-+ merged_img[:,:,3] = (merged_img[:,:,3] * c_img_ai + 255 * c_img_a) / 256;
++ merged_img[:,:,3] = (merged_img[:,:,3] * (255 - c_img_a) + 255 * c_img_a) / 255;
+
+ del colored_cat
++ del c_img_a
++
+ del masked_cat
+
+ img = imshow(self.axes, merged_img,
@@ -3791,7 +2774,7 @@
===================================================================
--- gui/wxpython/scatt_plot/controllers.py (revision 0)
+++ gui/wxpython/scatt_plot/controllers.py (working copy)
-@@ -0,0 +1,606 @@
+@@ -0,0 +1,621 @@
+"""!
+ at package scatt_plot.controllers
+
@@ -3815,7 +2798,6 @@
+from core.gcmd import GException, GError, GMessage, RunCommand
+
+from scatt_plot.scatt_core import Core, idBandsToidScatt
-+from scatt_plot.plots import haveMatPlot
+
+from scatt_plot.dialogs import AddScattPlotDialog
+from scatt_plot.gthreading import gThread
@@ -3825,8 +2807,6 @@
+class ScattsManager(wx.EvtHandler):
+ def __init__(self, guiparent, giface, iclass_mapwin):
+ #TODO remove iclass parameter
-+ if not haveMatPlot:
-+ raise GException(_("The interactive scatter plot tool needs \"Matplotlib\" package to be installed."))
+
+ wx.EvtHandler.__init__(self)
+ self.giface = giface
@@ -3987,7 +2967,7 @@
+
+ self.thread.Run(callable = self.core.AddScattPlot, scatt_id = scatt_id)
+
-+ def RenderScattPlts(self, cats_ids = None):
++ def RenderScattPlts(self):
+
+ cats_attrs = self.cats_mgr.GetCategoriesAttrs()
+ for scatt_id, scatt in self.plots.iteritems():
@@ -4079,11 +3059,12 @@
+ def SetEditCatDataDone(self, event):
+
+ if event.exception:
-+ GError(_("Error occured during computation of scatter plot category:\n%s") , parent = self.guiparent, showTraceback = False)
++ GError(_("Error occured during computation of scatter plot category:\n%s"),
++ parent = self.guiparent, showTraceback = False)
+
+ cat_id = event.ret
+
-+ self.RenderScattPlts(cats_ids = [cat_id])
++ self.RenderScattPlts()
+
+ cat_id = event.kwds["cat_id"]
+
@@ -4180,8 +3161,11 @@
+
+ self.cats[cat_id] = {
+ 'name' : _('Category %s' % cat_id ),
-+ 'color' : "0:0:0"
++ 'color' : "0:0:0",
++ 'opacity' : 1.0,
++ 'show' : True
+ }
++
+ self.cats_ids.append(cat_id)
+
+ if name is not None:
@@ -4196,9 +3180,17 @@
+ return cat_id
+
+ def SetCategoryAttrs(self, cat_id, attrs_dict):
++ render = False
+ for k, v in attrs_dict.iteritems():
++ if not render and k in ['name', 'color', 'opacity', 'show']:
++ render = True
++
+ self.cats[cat_id][k] = v
+
++ #TODO optimization
++ if render:
++ self.scatt_mgr.RenderScattPlts()
++
+ self.setCategoryAttrs.emit(cat_id = cat_id, attrs_dict = attrs_dict)
+
+ def DeleteCategory(self, cat_id):
@@ -4228,6 +3220,12 @@
+ def GetCategories(self):
+ return self.cats_ids[:]
+
++ def SetCategoryPosition(self):
++ if newindex > oldindex:
++ newindex -= 1
++
++ self.cats_ids.insert(newindex, self.cats_ids.pop(oldindex))
++
+class MapWinConnection:
+ def __init__(self, scatt_mgr, mapWin, scatt_rast_updater):
+ self.mapWin = mapWin
@@ -4399,478 +3397,33 @@
+ bands = res.split('\n')
+ self.scatt_mgr.SetData(bands)
\ No newline at end of file
-Index: gui/wxpython/scatt_plot/gthreading.py
+Index: gui/wxpython/Makefile
===================================================================
---- gui/wxpython/scatt_plot/gthreading.py (revision 0)
-+++ gui/wxpython/scatt_plot/gthreading.py (working copy)
-@@ -0,0 +1,133 @@
-+"""!
-+ at package scatt_plot.gthreading
+--- gui/wxpython/Makefile (revision 57556)
++++ gui/wxpython/Makefile (working copy)
+@@ -13,7 +13,7 @@
+ $(wildcard animation/* core/*.py dbmgr/* gcp/*.py gmodeler/* \
+ gui_core/*.py iclass/* lmgr/*.py location_wizard/*.py mapwin/*.py mapdisp/*.py \
+ mapswipe/* modules/*.py nviz/*.py psmap/* rlisetup/* timeline/* vdigit/* \
+- vnet/*.py web_services/*.py wxplot/*.py) \
++ vnet/*.py web_services/*.py wxplot/*.py scatt_plot/*.py) \
+ gis_set.py gis_set_error.py wxgui.py README
+
+ DSTFILES := $(patsubst %,$(ETCDIR)/%,$(SRCFILES)) \
+@@ -21,8 +21,9 @@
+
+ PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,animation core dbmgr gcp gmodeler \
+ gui_core iclass lmgr location_wizard mapwin mapdisp modules nviz psmap \
+- mapswipe vdigit wxplot web_services rlisetup vnet timeline)
++ mapswipe vdigit wxplot web_services rlisetup vnet timeline scatt_plot)
+
+
-+Classes:
-+
-+(C) 2013 by the GRASS Development Team
-+
-+This program is free software under the GNU General Public License
-+(>=v2). Read the file COPYING that comes with GRASS for details.
-+
-+ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
-+"""
-+
-+import os
-+import sys
-+import time
-+import threading
-+import Queue
-+
-+import wx
-+from core.gconsole import wxCmdRun, wxCmdDone, wxCmdPrepare
-+
-+class gThread(threading.Thread):
-+ """!Thread for GRASS commands"""
-+ requestId = 0
-+
-+ def __init__(self, receiver, requestQ=None, resultQ=None, **kwds):
-+ """!
-+ @param receiver event receiver (used in PostEvent)
-+ """
-+ threading.Thread.__init__(self, **kwds)
-+
-+ if requestQ is None:
-+ self.requestQ = Queue.Queue()
-+ else:
-+ self.requestQ = requestQ
-+
-+ if resultQ is None:
-+ self.resultQ = Queue.Queue()
-+ else:
-+ self.resultQ = resultQ
-+
-+ self.setDaemon(True)
-+
-+ self.receiver = receiver
-+ self._want_abort_all = False
-+
-+ self.start()
-+
-+ def Run(self, *args, **kwds):
-+ """!Run command in queue
-+
-+ @param args unnamed command arguments
-+ @param kwds named command arguments
-+
-+ @return request id in queue
-+ """
-+ gThread.requestId += 1
-+ self.requestQ.put((gThread.requestId, args, kwds))
-+
-+ return gThread.requestId
-+
-+ def GetId(self):
-+ """!Get id for next command"""
-+ return gThread.requestId + 1
-+
-+ def SetId(self, id):
-+ """!Set starting id"""
-+ gThread.requestId = id
-+
-+ def run(self):
-+ os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
-+ while True:
-+ requestId, args, kwds = self.requestQ.get()
-+ for key in ('callable', 'onDone', 'onPrepare', 'userData'):
-+ if key in kwds:
-+ vars()[key] = kwds[key]
-+ del kwds[key]
-+ else:
-+ vars()[key] = None
-+
-+ requestTime = time.time()
-+
-+ #if self._want_abort_all and self.requestCmd is not None:
-+ # self.requestCmd.abort()
-+ # if self.requestQ.empty():
-+ # self._want_abort_all = False
-+
-+ # prepare
-+ if self.receiver:
-+ event = wxCmdPrepare(type = 'method',
-+ time=requestTime,
-+ pid=requestId)
-+
-+ wx.PostEvent(self.receiver, event)
-+
-+ # run command
-+ event = wxCmdRun(type = 'method',
-+ pid=requestId)
-+
-+ wx.PostEvent(self.receiver, event)
-+
-+ time.sleep(.1)
-+
-+ ret = None
-+ exception = None
-+
-+ #to
-+ #try:
-+ ret = vars()['callable'](*args, **kwds)
-+ #except Exception as e:
-+ # exception = e;
-+
-+ self.resultQ.put((requestId, ret))
-+
-+ time.sleep(.1)
-+
-+ if self.receiver:
-+ event = wxCmdDone(kwds = kwds,
-+ args = args, #TODO expand args to kwds
-+ ret=ret,
-+ exception=exception,
-+ pid=requestId)
-+
-+ # send event
-+ wx.PostEvent(self.receiver, event)
-+
-+ def abort(self, abortall=True):
-+ """!Abort command(s)"""
-+ if abortall:
-+ self._want_abort_all = True
-+ if self.requestQ.empty():
-+ self._want_abort_all = False
-\ No newline at end of file
-Index: gui/wxpython/scatt_plot/dialogs.py
-===================================================================
---- gui/wxpython/scatt_plot/dialogs.py (revision 0)
-+++ gui/wxpython/scatt_plot/dialogs.py (working copy)
-@@ -0,0 +1,142 @@
-+"""!
-+ at package scatt_plot.dialogs
-+
-+ at brief GUI.
-+
-+Classes:
-+
-+(C) 2013 by the GRASS Development Team
-+
-+This program is free software under the GNU General Public License
-+(>=v2). Read the file COPYING that comes with GRASS for details.
-+
-+ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
-+"""
-+import os
-+import sys
-+
-+import wx
-+from scatt_plot.scatt_core import idBandsToidScatt
-+
-+class AddScattPlotDialog(wx.Dialog):
-+
-+ def __init__(self, parent, bands, id = wx.ID_ANY):
-+
-+ wx.Dialog.__init__(self, parent, title = ("Add scatter plot"), id = id)
-+
-+ self.bands = bands
-+
-+ self.scatt_id = None
-+
-+ self._createWidgets()
-+
-+ def _createWidgets(self):
-+
-+ self.labels = {}
-+ self.params = {}
-+
-+ self.band_1_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Band 1:"))
-+
-+ self.band_1_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
-+ choices = self.bands,
-+ style = wx.CB_READONLY, size = (350, 30))
-+
-+ self.band_2_label = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Band 2:"))
-+
-+ self.band_2_ch = wx.ComboBox(parent = self, id = wx.ID_ANY,
-+ choices = self.bands,
-+ style = wx.CB_READONLY, size = (350, 30))
-+
-+ # buttons
-+ self.btn_close = wx.Button(parent = self, id = wx.ID_CANCEL)
-+
-+ self.btn_ok = wx.Button(parent = self, id = wx.ID_OK, label = _("&OK"))
-+
-+ self._layout()
-+
-+ def _layout(self):
-+
-+ border = wx.BoxSizer(wx.VERTICAL)
-+ dialogSizer = wx.BoxSizer(wx.VERTICAL)
-+
-+ regionSizer = wx.BoxSizer(wx.HORIZONTAL)
-+
-+ dialogSizer.Add(item = self._addSelectSizer(title = self.band_1_label,
-+ sel = self.band_1_ch))
-+
-+ dialogSizer.Add(item = self._addSelectSizer(title = self.band_2_label,
-+ sel = self.band_2_ch))
-+
-+ # buttons
-+ self.btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
-+
-+ self.btnsizer.Add(item = self.btn_close, proportion = 0,
-+ flag = wx.ALL | wx.ALIGN_CENTER,
-+ border = 10)
-+
-+ self.btnsizer.Add(item = self.btn_ok, proportion = 0,
-+ flag = wx.ALL | wx.ALIGN_CENTER,
-+ border = 10)
-+
-+ dialogSizer.Add(item = self.btnsizer, proportion = 0,
-+ flag = wx.ALIGN_CENTER)
-+
-+ border.Add(item = dialogSizer, proportion = 0,
-+ flag = wx.ALL, border = 5)
-+
-+ self.SetSizer(border)
-+ self.Layout()
-+ self.Fit()
-+
-+ # bindings
-+ self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
-+ self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
-+
-+ def _addSelectSizer(self, title, sel):
-+ """!Helper layout function.
-+ """
-+ selSizer = wx.BoxSizer(orient = wx.VERTICAL)
-+
-+ selTitleSizer = wx.BoxSizer(wx.HORIZONTAL)
-+ selTitleSizer.Add(item = title, proportion = 1,
-+ flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
-+
-+ selSizer.Add(item = selTitleSizer, proportion = 0,
-+ flag = wx.EXPAND)
-+
-+ selSizer.Add(item = sel, proportion = 1,
-+ flag = wx.EXPAND | wx.ALL| wx.ALIGN_CENTER_VERTICAL,
-+ border = 5)
-+
-+ return selSizer
-+
-+ def OnClose(self, event):
-+ """!Close dialog
-+ """
-+ if not self.IsModal():
-+ self.Destroy()
-+ event.Skip()
-+
-+ def OnOk(self, event):
-+ """!
-+ """
-+ band_1 = self.band_1_ch.GetSelection()
-+ band_2 = self.band_2_ch.GetSelection()
-+
-+
-+ if band_1 == band_2:
-+ GError(_("Selected bands must be different."))
-+ return
-+
-+ #TODO axes selection
-+ if band_1 > band_2:
-+ tmp_band = band_2
-+ band_2 = band_1
-+ band_1 = band_2
-+
-+ self.scatt_id = idBandsToidScatt(band_1, band_2, len(self.bands))
-+
-+ event.Skip()
-+
-+ def GetScattId(self):
-+ return self.scatt_id
-Index: gui/wxpython/scatt_plot/toolbars.py
-===================================================================
---- gui/wxpython/scatt_plot/toolbars.py (revision 0)
-+++ gui/wxpython/scatt_plot/toolbars.py (working copy)
-@@ -0,0 +1,178 @@
-+"""!
-+ at package scatt_plot.toolbars
-+
-+ at brief Scatter plot - toolbars
-+
-+Classes:
-+ - toolbars::MainToolbar
-+
-+(C) 2013 by the GRASS Development Team
-+
-+This program is free software under the GNU General Public License
-+(>=v2). Read the file COPYING that comes with GRASS for details.
-+
-+ at author Stepan Turek <stepan.turek seznam.cz> (mentor: Martin Landa)
-+"""
-+import wx
-+
-+from icons.icon import MetaIcon
-+from gui_core.toolbars import BaseToolbar, BaseIcons
-+from core.gcmd import RunCommand
-+from core.gcmd import GException, GError, RunCommand
-+from scatt_plot.scatt_core import idBandsToidScatt
-+
-+
-+class MainToolbar(BaseToolbar):
-+ """!Main toolbar
-+ """
-+ def __init__(self, parent, scatt_mgr):
-+ BaseToolbar.__init__(self, parent)
-+ self.scatt_mgr = scatt_mgr
-+
-+ self.InitToolbar(self._toolbarData())
-+
-+ # realize the toolbar
-+ self.Realize()
-+
-+ def _toolbarData(self):
-+
-+ icons = {
-+ 'settings' : BaseIcons['settings'].SetLabel( _('Ssettings')),
-+ 'help' : MetaIcon(img = 'help',
-+ label = _('Show manual')),
-+ 'add_scatt_pl' : MetaIcon(img = 'layer-raster-analyze',
-+ label = _('Add scatter plot')),
-+ 'selCatPol' : MetaIcon(img = 'polygon-create',
-+ label = _('Select area with polygon')),
-+ 'pan' : MetaIcon(img = 'pan',
-+ label = _('Pan'),
-+ desc = _('Pan scatter plot')),
-+ 'zoomIn' : MetaIcon(img = 'zoom-in',
-+ label = _('Zoom'),
-+ desc = _('Zoom whith mouse wheel')),
-+ 'cats_mgr' : MetaIcon(img = 'table-manager',
-+ label = _('Show/hide class manager'))
-+ }
-+
-+ return self._getToolbarData((
-+ ("cats_mgr", icons['cats_mgr'],
-+ lambda event: self.parent.ShowCategoryPanel(event.Checked()), wx.ITEM_CHECK),
-+ (None, ),
-+ ("pan", icons["pan"],
-+ lambda event: self.SetPloltsMode(event, 'pan'),
-+ wx.ITEM_CHECK),
-+ ("zoom", icons["zoomIn"],
-+ lambda event: self.SetPloltsMode(event, 'zoom'),
-+ wx.ITEM_CHECK),
-+ ('sel_pol_mode', icons['selCatPol'],
-+ self.ActivateSelectionPolygonMode,
-+ wx.ITEM_CHECK),
-+ (None, ),
-+ ('add_scatt', icons["add_scatt_pl"],
-+ lambda event : self.scatt_mgr.AddScattPlot())
-+ #('settings', icon["settings"],
-+ # self.parent.OnSettings),
-+ #('help', icons["help"],
-+ # self.OnHelp),
-+ ))
-+
-+ def GetToolId(self, toolName): #TODO can be useful in base
-+
-+ return vars(self)[toolName]
-+
-+ def SetPloltsMode(self, event, tool_name):
-+
-+ if event.Checked() == True:
-+ for i_tool_data in self._data:
-+ i_tool_name = i_tool_data[0]
-+ if not i_tool_name or i_tool_name == "cats_mgr":
-+ continue
-+ if i_tool_name == tool_name:
-+ continue
-+ i_tool_id = vars(self)[i_tool_name]
-+ self.ToggleTool(i_tool_id, False)
-+
-+ self.scatt_mgr.SetPlotsMode(mode = tool_name)
-+ else:
-+ self.scatt_mgr.SetPlotsMode(mode = None)
-+
-+ def ActivateSelectionPolygonMode(self, event):
-+
-+ activated = self.scatt_mgr.ActivateSelectionPolygonMode(event.Checked())
-+ self.parent.ShowPlotEditingToolbar(activated)
-+
-+ i_tool_id = vars(self)['sel_pol_mode']
-+ self.ToggleTool(i_tool_id, activated)
-+
-+class EditingToolbar(BaseToolbar):
-+ """!Main toolbar
-+ """
-+ def __init__(self, parent, scatt_mgr):
-+ BaseToolbar.__init__(self, parent)
-+ self.scatt_mgr = scatt_mgr
-+
-+ self.InitToolbar(self._toolbarData())
-+
-+ # realize the toolbar
-+ self.Realize()
-+
-+ def _toolbarData(self):
-+ """!Toolbar data
-+ """
-+ self.icons = {
-+ 'sel_add' : MetaIcon(img = 'layer-add',
-+ label = _('Include selected area to class.'),
-+ desc = _('Include selected area to class.')),
-+ 'sel_remove' : MetaIcon(img = 'layer-remove',
-+ label = _('Exclude selected area from class.'),
-+ desc = _('Exclude selected area from class.')),
-+ 'addVertex' : MetaIcon(img = 'vertex-create',
-+ label = _('Add new vertex'),
-+ desc = _('Add new vertex to polygon boundary scatter plot')),
-+ 'editLine' : MetaIcon(img = 'line-edit',
-+ label = _('Edit line/boundary'),
-+ desc = _('Add new vertex between last and first points of the boundary')),
-+ 'moveVertex' : MetaIcon(img = 'vertex-move',
-+ label = _('Move vertex'),
-+ desc = _('Move boundary vertex')),
-+ 'removeVertex' : MetaIcon(img = 'vertex-delete',
-+ label = _('Remove vertex'),
-+ desc = _('Remove boundary vertex.')),
-+ }
-+
-+ return self._getToolbarData((
-+ ("sel_add", self.icons["sel_add"],
-+ lambda event: self.scatt_mgr.ProcessSelectionPolygons('add')),
-+ ("sel_remove", self.icons['sel_remove'],
-+ lambda event: self.scatt_mgr.ProcessSelectionPolygons('remove')),
-+ (None, ),
-+ ("add_vertex", self.icons["editLine"],
-+ lambda event: self.SetMode(event, 'add_vertex'),
-+ wx.ITEM_CHECK),
-+ ("add_boundary_vertex", self.icons['addVertex'],
-+ lambda event: self.SetMode(event, 'add_boundary_vertex'),
-+ wx.ITEM_CHECK),
-+ ("move_vertex", self.icons["moveVertex"],
-+ lambda event: self.SetMode(event, 'move_vertex'),
-+ wx.ITEM_CHECK),
-+ ('delete_vertex', self.icons['removeVertex'],
-+ lambda event: self.SetMode(event, 'delete_vertex'),
-+ wx.ITEM_CHECK)
-+ ))
-+
-+ def SetMode(self, event, tool_name):
-+ if event.Checked() == True:
-+ for i_tool_data in self._data:
-+ i_tool_name = i_tool_data[0]
-+ if not i_tool_name:
-+ continue
-+ if i_tool_name == tool_name:
-+ continue
-+ i_tool_id = vars(self)[i_tool_name]
-+ self.ToggleTool(i_tool_id, False)
-+ self.scatt_mgr.SetPlotsEditingMode(tool_name)
-+ else:
-+ self.scatt_mgr.SetPlotsEditingMode(None)
-+
-+ def GetToolId(self, toolName):
-+ return vars(self)[toolName]
+ DSTDIRS := $(patsubst %,$(ETCDIR)/%,icons scripts xml)
+
+ default: $(DSTFILES)
Index: gui/wxpython/vdigit/wxdigit.py
===================================================================
---- gui/wxpython/vdigit/wxdigit.py (revision 57546)
+--- gui/wxpython/vdigit/wxdigit.py (revision 57556)
+++ gui/wxpython/vdigit/wxdigit.py (working copy)
@@ -17,7 +17,7 @@
(and NumPy would be an excellent candidate for acceleration via
@@ -5390,7 +3943,7 @@
def GetLineCats(self, line):
Index: gui/wxpython/vdigit/toolbars.py
===================================================================
---- gui/wxpython/vdigit/toolbars.py (revision 57546)
+--- gui/wxpython/vdigit/toolbars.py (revision 57556)
+++ gui/wxpython/vdigit/toolbars.py (working copy)
@@ -17,6 +17,7 @@
import wx
@@ -5417,27 +3970,1556 @@
return True
def StopEditing(self):
-Index: gui/wxpython/Makefile
+Index: gui/wxpython/mapdisp/toolbars.py
===================================================================
---- gui/wxpython/Makefile (revision 57546)
-+++ gui/wxpython/Makefile (working copy)
-@@ -13,7 +13,7 @@
- $(wildcard animation/* core/*.py dbmgr/* gcp/*.py gmodeler/* \
- gui_core/*.py iclass/* lmgr/*.py location_wizard/*.py mapwin/*.py mapdisp/*.py \
- mapswipe/* modules/*.py nviz/*.py psmap/* rlisetup/* timeline/* vdigit/* \
-- vnet/*.py web_services/*.py wxplot/*.py) \
-+ vnet/*.py web_services/*.py wxplot/*.py scatt_plot/*.py) \
- gis_set.py gis_set_error.py wxgui.py README
+--- gui/wxpython/mapdisp/toolbars.py (revision 57556)
++++ gui/wxpython/mapdisp/toolbars.py (working copy)
+@@ -239,7 +239,8 @@
+ (MapIcons["scatter"], self.parent.OnScatterplot),
+ (MapIcons["histogram"], self.parent.OnHistogramPyPlot),
+ (BaseIcons["histogramD"], self.parent.OnHistogram),
+- (MapIcons["vnet"], self.parent.OnVNet)))
++ (MapIcons["vnet"], self.parent.OnVNet),
++ (MapIcons["scatter"], self.parent.OnScatterplot2)))
+
+ def OnDecoration(self, event):
+ """!Decorations overlay menu
+Index: gui/wxpython/mapdisp/frame.py
+===================================================================
+--- gui/wxpython/mapdisp/frame.py (revision 57556)
++++ gui/wxpython/mapdisp/frame.py (working copy)
+@@ -225,6 +225,7 @@
+ #
+ self.dialogs = {}
+ self.dialogs['attributes'] = None
++ self.dialogs['scatt_plot'] = None
+ self.dialogs['category'] = None
+ self.dialogs['barscale'] = None
+ self.dialogs['legend'] = None
+@@ -1168,6 +1169,19 @@
+ """!Returns toolbar with zooming tools"""
+ return self.toolbars['map']
- DSTFILES := $(patsubst %,$(ETCDIR)/%,$(SRCFILES)) \
-@@ -21,8 +21,9 @@
++ def OnScatterplot2(self, event):
++ """!Init interactive scatterplot tools
++ """
++ if self.dialogs['scatt_plot']:
++ self.dialogs['scatt_plot'].Raise()
++ return
++
++ from scatt_plot.dialogs import ScattPlotMainDialog
++ self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface)
++
++ self.dialogs['scatt_plot'].CenterOnScreen()
++ self.dialogs['scatt_plot'].Show()
++
+ def OnVNet(self, event):
+ """!Dialog for v.net* modules
+ """
+Index: gui/wxpython/iclass/dialogs.py
+===================================================================
+--- gui/wxpython/iclass/dialogs.py (revision 57556)
++++ gui/wxpython/iclass/dialogs.py (working copy)
+@@ -333,13 +333,19 @@
+ toolbar.SetCategories(catNames = catNames, catIdx = cats)
+ if name in catNames:
+ toolbar.choice.SetStringSelection(name)
++ cat = toolbar.GetSelectedCategoryIdx()
+ elif catNames:
+ toolbar.choice.SetSelection(0)
+-
++ cat = toolbar.GetSelectedCategoryIdx()
++ else:
++ cat = None
++
+ if toolbar.choice.IsEmpty():
+ toolbar.EnableControls(False)
+ else:
+ toolbar.EnableControls(True)
++
++ self.mapWindow.CategoryChanged(cat)
+ # don't forget to update maps, histo, ...
+
+ def GetSelectedIndices(self, state = wx.LIST_STATE_SELECTED):
+Index: gui/wxpython/iclass/toolbars.py
+===================================================================
+--- gui/wxpython/iclass/toolbars.py (revision 57556)
++++ gui/wxpython/iclass/toolbars.py (working copy)
+@@ -46,9 +46,7 @@
+ 'importAreas' : MetaIcon(img = 'layer-import',
+ label = _('Import training areas from vector map')),
+ 'addRgb' : MetaIcon(img = 'layer-rgb-add',
+- label = _('Add RGB map layer')),
+- 'scatt_plot' : MetaIcon(img = 'layer-raster-analyze',
+- label = _('Open Scatter Plot Tool (EXPERIMENTAL GSoC 2013)')),
++ label = _('Add RGB map layer'))
+ }
+
+ class IClassMapToolbar(BaseToolbar):
+@@ -117,10 +115,7 @@
+ ("zoomBack", icons["zoomBack"],
+ self.parent.OnZoomBack),
+ ("zoomToMap", icons["zoomExtent"],
+- self.parent.OnZoomToMap),
+- (None, ),
+- ("scatt_plot", iClassIcons["scatt_plot"],
+- self.parent.OnScatterplot)
++ self.parent.OnZoomToMap)
+ ))
+ class IClassToolbar(BaseToolbar):
+ """!IClass toolbar
+@@ -156,7 +151,7 @@
+ """!Toolbar data"""
+ icons = iClassIcons
+ return self._getToolbarData((("selectGroup", icons['selectGroup'],
+- self.parent.OnAddBands),
++ lambda event : self.parent.AddBands()),
+ (None, ),
+ ("classManager", icons['classManager'],
+ self.parent.OnCategoryManager),
+Index: gui/wxpython/iclass/frame.py
+===================================================================
+--- gui/wxpython/iclass/frame.py (revision 57556)
++++ gui/wxpython/iclass/frame.py (working copy)
+@@ -64,6 +64,8 @@
+ IClassExportAreasDialog, IClassMapDialog
+ from iclass.plots import PlotPanel
- PYDSTDIRS := $(patsubst %,$(ETCDIR)/%,animation core dbmgr gcp gmodeler \
- gui_core iclass lmgr location_wizard mapwin mapdisp modules nviz psmap \
-- mapswipe vdigit wxplot web_services rlisetup vnet timeline)
-+ mapswipe vdigit wxplot web_services rlisetup vnet timeline scatt_plot)
++from grass.pydispatch.signal import Signal
++
+ class IClassMapFrame(DoubleMapFrame):
+ """! wxIClass main frame
+
+@@ -114,6 +116,10 @@
+ lambda:
+ self.statusbarManager.statusbarItems['coordinates'].SetAdditionalInfo(None))
+ self.SetSize(size)
++
++ self.groupSet = Signal("IClassMapFrame.groupSet")
++ self.categoryChanged = Signal('IClassMapFrame.categoryChanged')
++
+ #
+ # Add toolbars
+ #
+@@ -177,7 +183,7 @@
+ self.dialogs['category'] = None
+
+ # PyPlot init
+- self.plotPanel = PlotPanel(self, stats_data = self.stats_data)
++ self.plotPanel = PlotPanel(self, giface = self._giface, stats_data = self.stats_data)
+
+ self._addPanes()
+ self._mgr.Update()
+@@ -237,7 +243,7 @@
+ return False
+
+ return vectorName
+-
++
+ def RemoveTempVector(self):
+ """!Removes temporary vector map with training areas"""
+ ret = RunCommand(prog = 'g.remove',
+@@ -477,7 +483,7 @@
+
+ self.Render(self.GetFirstWindow())
+
+- def OnAddBands(self, event):
++ def AddBands(self):
+ """!Add imagery group"""
+ dlg = IClassGroupDialog(self, group = self.group)
+ if dlg.ShowModal() == wx.ID_OK:
+@@ -488,7 +494,8 @@
+ """!Set imagery group"""
+ group = grass.find_file(name = name, element = 'group')
+ if group['name']:
+- self.group = group['name']
++ self.group = group['name']
++ self.groupSet.emit(group = group['name'])
+ else:
+ GError(_("Group <%s> not found") % name, parent = self)
+
+@@ -768,17 +775,20 @@
+
+ Updates number of stddev, histograms, layer in preview display.
+ """
+- stat = self.stats_data.GetStatistics(currentCat)
+- nstd = stat.nstd
+- self.toolbars['iClass'].UpdateStddev(nstd)
+-
+- self.plotPanel.UpdateCategory(currentCat)
+- self.plotPanel.OnPlotTypeSelected(None)
++ if currentCat:
++ stat = self.stats_data.GetStatistics(currentCat)
++ nstd = stat.nstd
++ self.toolbars['iClass'].UpdateStddev(nstd)
++
++ self.plotPanel.UpdateCategory(currentCat)
++ self.plotPanel.OnPlotTypeSelected(None)
+
+- name = stat.rasterName
+- name = self.previewMapManager.GetAlias(name)
+- if name:
+- self.previewMapManager.SelectLayer(name)
++ name = stat.rasterName
++ name = self.previewMapManager.GetAlias(name)
++ if name:
++ self.previewMapManager.SelectLayer(name)
++
++ self.categoryChanged.emit(cat = currentCat)
+
+ def DeleteAreas(self, cats):
+ """!Removes all training areas of given categories
+@@ -1105,27 +1115,6 @@
+ self.GetFirstWindow().SetModePointer()
+ self.GetSecondWindow().SetModePointer()
+- def OnScatterplot(self, event):
+- """!Init interactive scatterplot tools
+- """
+- if self.dialogs['scatt_plot']:
+- self.dialogs['scatt_plot'].Raise()
+- return
+-
+- try:
+- from scatt_plot.dialogs import ScattPlotMainDialog
+- except:
+- GError(parent = self, message = _("The Scatter Plot Tool is not installed."))
+- return
+-
+- self.dialogs['scatt_plot'] = ScattPlotMainDialog(parent=self, giface=self._giface, iclass_mapwin = self.GetFirstWindow())
+-
+- scatt_mgr = self.dialogs['scatt_plot'].GetScattMgr()
+- scatt_mgr.DigitDataChanged(self.toolbars['vdigit'].mapLayer.GetName(), self.GetFirstWindow().GetDigit())
+-
+- self.dialogs['scatt_plot'].CenterOnScreen()
+- self.dialogs['scatt_plot'].Show()
+-
+ class MapManager:
+ """! Class for managing map renderer.
+
+Index: gui/wxpython/iclass/plots.py
+===================================================================
+--- gui/wxpython/iclass/plots.py (revision 57556)
++++ gui/wxpython/iclass/plots.py (working copy)
+@@ -19,6 +19,7 @@
+ import wx.lib.plot as plot
+ import wx.lib.scrolledpanel as scrolled
+ from core.utils import _
++from core.gcmd import GError
+
+ class PlotPanel(scrolled.ScrolledPanel):
+ """!Panel for drawing multiple plots.
+@@ -28,7 +29,7 @@
+ for each band and for one category. Coincidence plots show min max range
+ of classes for each band.
+ """
+- def __init__(self, parent, stats_data):
++ def __init__(self, parent, giface, stats_data):
+ scrolled.ScrolledPanel.__init__(self, parent)
+
+ self.SetupScrolling(scroll_x = False, scroll_y = True)
+@@ -38,26 +39,71 @@
+ self.stats_data = stats_data
+ self.currentCat = None
+
++ self._giface = giface
+
- DSTDIRS := $(patsubst %,$(ETCDIR)/%,icons scripts xml)
-
- default: $(DSTFILES)
+ self.mainSizer = wx.BoxSizer(wx.VERTICAL)
+-
++
+ self._createControlPanel()
+-
++ self._createPlotPanel()
++ self._createScatterPlotPanel()
++
+ self.SetSizer(self.mainSizer)
+ self.mainSizer.Fit(self)
+ self.Layout()
+-
++
++ def _createPlotPanel(self):
++
++ self.canvasPanel = wx.Panel(parent=self)
++ self.mainSizer.Add(item = self.canvasPanel, proportion = 1, flag = wx.EXPAND, border = 0)
++ self.canvasSizer = wx.BoxSizer(wx.VERTICAL)
++ self.canvasPanel.SetSizer(self.canvasSizer)
++
+ def _createControlPanel(self):
+ self.plotSwitch = wx.Choice(self, id = wx.ID_ANY,
+ choices = [_("Histograms"),
+- _("Coincident plots")])
++ _("Coincident plots"),
++ _("Scatter plots")])
+ self.mainSizer.Add(self.plotSwitch, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
+ self.plotSwitch.Bind(wx.EVT_CHOICE, self.OnPlotTypeSelected)
+-
++
++ def _createScatterPlotPanel(self):
++ """!Init interactive scatterplot tools
++ """
++ try:
++ from scatt_plot.frame import IClassScatterPlotsPanel
++ self.scatt_plot_panel = IClassScatterPlotsPanel(parent=self,
++ giface=self._giface,
++ iclass_mapwin = self.parent.GetFirstWindow())
++ self.mainSizer.Add(self.scatt_plot_panel, proportion = 1, flag = wx.EXPAND, border = 0)
++ self.scatt_plot_panel.Hide()
++ except ImportError as e:#TODO
++ self.scatt_error = _("Scatter plot functionality is disabled. Reason:\n" \
++ "Unable to import packages needed for scatter plot.\n%s" % e)
++ GError(self.scatt_error)
++ self.scatt_plot_panel = None
++
+ def OnPlotTypeSelected(self, event):
+ """!Plot type selected"""
++
++ if self.plotSwitch.GetSelection() in [0, 1]:
++ self.SetupScrolling(scroll_x = False, scroll_y = True)
++ if self.scatt_plot_panel:
++ self.scatt_plot_panel.Hide()
++ self.canvasPanel.Show()
++ self.Layout()
++
++ elif self.plotSwitch.GetSelection() == 2:
++ self.SetupScrolling(scroll_x = False, scroll_y = False)
++ if self.scatt_plot_panel:
++ self.scatt_plot_panel.Show()
++ else:
++ GError(self.scatt_error)
++ self.canvasPanel.Hide()
++ self.Layout()
++
+ if self.currentCat is None:
+ return
+-
++
+ if self.plotSwitch.GetSelection() == 0:
+ stat = self.stats_data.GetStatistics(self.currentCat)
+ if not stat.IsReady():
+@@ -66,7 +112,10 @@
+ self.DrawHistograms(stat)
+ else:
+ self.DrawCoincidencePlots()
+-
++
++ self.Layout()
++
++
+ def StddevChanged(self):
+ """!Standard deviation multiplier changed, redraw histograms"""
+ if self.plotSwitch.GetSelection() == 0:
+@@ -89,7 +138,7 @@
+ panel.Destroy()
+
+ self.canvasList = []
+-
++
+ def ClearPlots(self):
+ """!Clears plot canvases"""
+ for bandIdx in range(len(self.bandList)):
+@@ -104,15 +153,15 @@
+ def CreatePlotCanvases(self):
+ """!Create plot canvases according to the number of bands"""
+ for band in self.bandList:
+- canvas = plot.PlotCanvas(self)
++ canvas = plot.PlotCanvas(self.canvasPanel)
+ canvas.SetMinSize((-1, 140))
+ canvas.SetFontSizeTitle(10)
+ canvas.SetFontSizeAxis(8)
+ self.canvasList.append(canvas)
+
+- self.mainSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
+-
+- self.SetVirtualSize(self.GetBestVirtualSize())
++ self.canvasSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
++
++ self.SetVirtualSize(self.GetBestVirtualSize())
+ self.Layout()
+
+ def UpdatePlots(self, group, currentCat, stats_data):
+@@ -138,7 +187,7 @@
+
+ def UpdateCategory(self, cat):
+ self.currentCat = cat
+-
++
+ def DrawCoincidencePlots(self):
+ """!Draw coincidence plots"""
+ for bandIdx in range(len(self.bandList)):
+Index: lib/imagery/scatt_sccats.c
+===================================================================
+--- lib/imagery/scatt_sccats.c (revision 0)
++++ lib/imagery/scatt_sccats.c (working copy)
+@@ -0,0 +1,405 @@
++/*!
++ \file lib/imagery/scatt_cat_rast.c
++
++ \brief Imagery library - functions for manipulation with scatter plot structs.
++
++ Copyright (C) 2013 by the GRASS Development Team
++
++ This program is free software under the GNU General Public License
++ (>=v2). Read the file COPYING that comes with GRASS for details.
++
++ \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
++ */
++
++#include <grass/raster.h>
++#include <grass/imagery.h>
++#include <grass/gis.h>
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <math.h>
++#include <string.h>
++
++/*!
++ \brief Compute band ids from scatter plot id.
++
++ Scatter plot id describes which bands defines the scatter plot.
++
++ Let say we have 3 bands, their ids are 0, 1 and 2.
++ Scatter plot with id 0 consists of band 1 (b_1_id) 0 and band 2 (b_2_id) 1.
++ All scatter plots:
++ scatt_id b_1_id b_2_id
++ 0 0 1
++ 1 0 2
++ 2 1 2
++
++ \param scatt_id scatter plot id
++ \param n_bands number of bands
++ \param [out] b_1_id id of band1
++ \param[out] b_2_id id of band2
++
++ \return 0
++ */
++int I_id_scatt_to_bands(const int scatt_id, const int n_bands, int * b_1_id, int * b_2_id)
++{
++ int n_b1 = n_bands - 1;
++
++ * b_1_id = (int) ((2 * n_b1 + 1 - sqrt((double)((2 * n_b1 + 1) * (2 * n_b1 + 1) - 8 * scatt_id))) / 2);
++
++ * b_2_id = scatt_id - ((* b_1_id) * (2 * n_b1 + 1) - (* b_1_id) * (* b_1_id)) / 2 + (* b_1_id) + 1;
++
++ return 0;
++}
++
++
++/*!
++ \brief Compute scatter plot id from band ids.
++
++ See also I_id_scatt_to_bands().
++
++ \param n_bands number of bands
++ \param b_1_id id of band1
++ \param b_1_id id of band2
++ \param [out] scatt_id scatter plot id
++
++ \return 0
++ */
++int I_bands_to_id_scatt(const int b_1_id, const int b_2_id, const int n_bands, int * scatt_id)
++{
++ int n_b1 = n_bands - 1;
++
++ * scatt_id = (b_1_id * (2 * n_b1 + 1) - b_1_id * b_1_id) / 2 + b_2_id - b_1_id - 1;
++
++ return 0;
++}
++
++/*!
++ \brief Initialize structure for storing scatter plots data.
++
++ \param cats pointer to scCats struct
++ \param n_bands number of bands
++ \param type SC_SCATT_DATA - stores scatter plots
++ \param type SC_SCATT_CONDITIONS - stores selected areas in scatter plots
++ */
++void I_sc_init_cats(struct scCats * cats, int n_bands, int type)
++{
++ int i_cat;
++
++ cats->type = type;
++
++ cats->n_cats = 100;
++ cats->n_a_cats = 0;
++
++ cats->n_bands = n_bands;
++ cats->n_scatts = (n_bands - 1) * n_bands / 2;
++
++ cats->cats_arr = (struct scScatts **) G_malloc(cats->n_cats * sizeof(struct scScatts *));
++ memset(cats->cats_arr, 0, cats-> n_cats * sizeof(struct scScatts *));
++
++ cats->cats_ids = (int *) G_malloc(cats->n_cats * sizeof(int));
++ cats->cats_idxs =(int *) G_malloc(cats->n_cats * sizeof(int));
++
++ for(i_cat = 0; i_cat < cats->n_cats; i_cat++)
++ cats->cats_idxs[i_cat] = -1;
++
++ return;
++}
++
++/*!
++ \brief Free data of struct scCats, the structure itself remains alocated.
++
++ \param cats pointer to existing scCats struct
++ */
++void I_sc_free_cats(struct scCats * cats)
++{
++ int i_cat;
++
++ for(i_cat = 0; i_cat < cats->n_a_cats; i_cat++)
++ {
++ if(cats->cats_arr[i_cat])
++ {
++ G_free(cats->cats_arr[i_cat]->scatt_idxs);
++ G_free(cats->cats_arr[i_cat]->scatts_bands);
++ G_free(cats->cats_arr[i_cat]->scatts_arr);
++ G_free(cats->cats_arr[i_cat]);
++ }
++ }
++
++ G_free(cats->cats_ids);
++ G_free(cats->cats_idxs);
++ G_free(cats->cats_arr);
++
++ cats->n_cats = 0;
++ cats->n_a_cats = 0;
++ cats->n_bands = 0;
++ cats->n_scatts = 0;
++ cats->type = -1;
++
++ return;
++}
++
++#if 0
++void I_sc_get_active_categories(int * a_cats_ids, int * n_a_cats, struct scCats * cats)
++{
++ a_cats_ids = cats->cats_ids;
++ * n_a_cats = cats->n_a_cats;
++}
++#endif
++
++/*!
++ \brief Add category.
++
++ Category represents group of scatter plots.
++
++ \param cats pointer to scCats struct
++
++ \return assigned category id (starts with 0)
++ \return -1 if maximum nuber of categories was reached
++ */
++int I_sc_add_cat(struct scCats * cats)
++{
++ int i_scatt, i_cat_id, cat_id;
++ int n_a_cats = cats->n_a_cats;
++
++ if(cats->n_a_cats >= cats->n_cats)
++ return -1;
++
++ for(i_cat_id = 0; i_cat_id < cats->n_cats; i_cat_id++)
++ if(cats->cats_idxs[i_cat_id] < 0) {
++ cat_id = i_cat_id;
++ break;
++ }
++
++ cats->cats_ids[n_a_cats] = cat_id;
++ cats->cats_idxs[cat_id] = n_a_cats;
++
++ cats->cats_arr[n_a_cats] = (struct scScatts *) G_malloc(sizeof(struct scScatts));
++
++ cats->cats_arr[n_a_cats]->scatts_arr = (struct scdScattData **) G_malloc(cats->n_scatts * sizeof(struct scdScattData *));
++ memset((cats->cats_arr[n_a_cats]->scatts_arr), 0, cats->n_scatts * sizeof(struct scdScattData *));
++
++ cats->cats_arr[n_a_cats]->n_a_scatts = 0;
++
++ cats->cats_arr[n_a_cats]->scatts_bands = (int *) G_malloc(cats->n_scatts * 2 * sizeof(int));
++
++ cats->cats_arr[n_a_cats]->scatt_idxs = (int *) G_malloc(cats->n_scatts * sizeof(int));
++ for(i_scatt = 0; i_scatt < cats->n_scatts; i_scatt++)
++ cats->cats_arr[n_a_cats]->scatt_idxs[i_scatt] = -1;
++
++ ++cats->n_a_cats;
++
++ return cat_id;
++}
++
++#if 0
++int I_sc_delete_cat(struct scCats * cats, int cat_id)
++{
++ int cat_idx, i_cat;
++
++ if(cat_id < 0 || cat_id >= cats->n_cats)
++ return -1;
++
++ cat_idx = cats->cats_idxs[cat_id];
++ if(cat_idx < 0)
++ return -1;
++
++ G_free(cats->cats_arr[cat_idx]->scatt_idxs);
++ G_free(cats->cats_arr[cat_idx]->scatts_bands);
++ G_free(cats->cats_arr[cat_idx]->scatts_arr);
++ G_free(cats->cats_arr[cat_idx]);
++
++ for(i_cat = cat_idx; i_cat < cats->n_a_cats - 1; i_cat++)
++ {
++ cats->cats_arr[i_cat] = cats->cats_arr[i_cat + 1];
++ cats->cats_ids[i_cat] = cats->cats_ids[i_cat + 1];
++ }
++ cats->cats_idxs[cat_id] = -1;
++
++ --cats->n_a_cats;
++
++ return 0;
++}
++#endif
++
++/*!
++ \brief Insert scatter plot data .
++ Inserted scatt_data struct must have same type as cats struct (SC_SCATT_DATA or SC_SCATT_CONDITIONS).
++
++ \param cats pointer to scCats struct
++ \param cat_id id number of category.
++ \param scatt_id id number of scatter plot.
++
++ \return 0 on success
++ \return -1 on failure
++ */
++int I_sc_insert_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
++{
++ int band_1, band_2, cat_idx, n_a_scatts;
++ struct scScatts * scatts;
++
++ if(cat_id < 0 || cat_id >= cats->n_cats)
++ return -1;
++
++ cat_idx = cats->cats_idxs[cat_id];
++ if(cat_idx < 0)
++ return -1;
++
++ if(scatt_id < 0 && scatt_id >= cats->n_scatts)
++ return -1;
++
++ scatts = cats->cats_arr[cat_idx];
++ if(scatts->scatt_idxs[scatt_id] >= 0)
++ return -1;
++
++ if(!scatt_data->b_conds_arr && cats->type == SC_SCATT_CONDITIONS)
++ return -1;
++
++ if(!scatt_data->scatt_vals_arr && cats->type == SC_SCATT_DATA)
++ return -1;
++
++ n_a_scatts = scatts->n_a_scatts;
++
++ scatts->scatt_idxs[scatt_id] = n_a_scatts;
++
++ I_id_scatt_to_bands(scatt_id, cats->n_bands, &band_1, &band_2);
++
++ scatts->scatts_bands[n_a_scatts * 2] = band_1;
++ scatts->scatts_bands[n_a_scatts * 2 + 1] = band_2;
++
++ scatts->scatts_arr[n_a_scatts] = scatt_data;
++ ++scatts->n_a_scatts;
++
++ return 0;
++}
++
++#if 0
++int I_sc_remove_scatt_data(struct scCats * cats, struct scdScattData * scatt_data, int cat_id, int scatt_id)
++{
++ int cat_idx, scatt_idx, n_init_scatts, i_scatt;
++ struct scScatts * scatts;
++
++ if(cat_id < 0 && cat_id >= cats->n_cats)
++ return -1;
++
++ cat_idx = cats->cats_idxs[cat_id];
++ if(cat_idx < 0)
++ return -1;
++
++ if(scatt_id < 0 || scatt_id >= cats->n_scatts)
++ return -1;
++
++ scatts = cats->cats_arr[cat_idx];
++ if(scatts->scatt_idxs[scatt_id] < 0)
++ return -1;
++
++ scatt_data = scatts->scatts_arr[scatt_idx];
++
++ for(i_scatt = scatt_idx; i_scatt < scatts->n_a_scatts - 1; i_scatt++)
++ {
++ scatts->scatts_arr[i_scatt] = scatts->scatts_arr[i_scatt + 1];
++ scatts->scatts_bands[i_scatt * 2] = scatts->scatts_bands[(i_scatt + 1)* 2];
++ scatts->scatts_bands[i_scatt * 2 + 1] = scatts->scatts_bands[(i_scatt + 1) * 2 + 1];
++ }
++ scatts->scatts_arr[scatts->n_a_scatts] = NULL;
++
++ scatts->scatt_idxs[scatt_id] = -1;
++
++ scatt_data = scatts->scatts_arr[scatt_id];
++ scatts->n_a_scatts--;
++
++ return 0;
++}
++
++int I_sc_set_value(struct scCats * cats, int cat_id, int scatt_id, int value_idx, int value)
++{
++ int n_a_scatts = cats->cats_arr[cat_id]->n_a_scatts;
++ int cat_idx, scatt_idx, ret;
++
++ cat_idx = cats->cats_idxs[cat_id];
++ if(cat_idx < 0)
++ return -1;
++
++ if(cats->cats_arr[cat_idx]->scatt_idxs[scatt_id] < 0)
++ return -1;
++
++ cat_idx = cats->cats_idxs[cat_id];
++ scatt_idx = cats->cats_arr[cat_idx]->scatt_idxs[scatt_id];
++
++ I_scd_set_value(cats->cats_arr[cat_idx]->scatts_arr[scatt_idx], value_idx, value);
++
++ return 0;
++}
++#endif
++
++/*!
++ \brief Insert scatter plot data.
++
++ \param scatt_data pointer to existing struct scdScattData
++ \param type SC_SCATT_DATA for scatter plots or SC_SCATT_CONDITIONS for selected areas in scatter plot
++ \param n_vals number of data values
++ \param data array of values (unsigned char for SC_SCATT_CONDITIONS, unsigned int for SC_SCATT_DATA)
++ */
++void I_scd_init_scatt_data(struct scdScattData * scatt_data, int type, int n_vals, void * data)
++{
++ scatt_data->n_vals = n_vals;
++
++ if(type == SC_SCATT_DATA)
++ {
++ if(data)
++ scatt_data->scatt_vals_arr = (unsigned int *) data;
++ else {
++ scatt_data->scatt_vals_arr = (unsigned int *) G_malloc(n_vals * sizeof(unsigned int));
++ memset(scatt_data->scatt_vals_arr, 0, n_vals * sizeof(unsigned int));
++ }
++ scatt_data->b_conds_arr = NULL;
++ }
++ else if(type == SC_SCATT_CONDITIONS)
++ {
++ if(data)
++ scatt_data->b_conds_arr = (unsigned char *) data;
++ else {
++ scatt_data->b_conds_arr = (unsigned char *) G_malloc(n_vals * sizeof(unsigned char));
++ memset(scatt_data->b_conds_arr, 0, n_vals * sizeof(unsigned char));
++ }
++ scatt_data->scatt_vals_arr = NULL;
++ }
++
++ return;
++}
++
++
++#if 0
++void I_scd_get_range_min_max(struct scdScattData * scatt_data, CELL * band_1_min, CELL * band_1_max, CELL * band_2_min, CELL * band_2_max)
++{
++
++ Rast_get_range_min_max(&(scatt_data->band_1_range), band_1_min, band_2_min);
++ Rast_get_range_min_max(&(scatt_data->band_2_range), band_2_min, band_2_max);
++
++ return;
++}
++s
++void * I_scd_get_data_ptr(struct scdScattData * scatt_data)
++{
++ if(!scatt_data->b_conds_arr)
++ return scatt_data->b_conds_arr;
++ else if(!scatt_data->scatt_vals_arr)
++ return scatt_data->scatt_vals_arr;
++
++ return NULL;
++}
++
++int I_scd_set_value(struct scdScattData * scatt_data, unsigned int val_idx, unsigned int val)
++{
++ if(val_idx < 0 && val_idx > scatt_data->n_vals)
++ return -1;
++
++ if(scatt_data->b_conds_arr)
++ scatt_data->b_conds_arr[val_idx] = val;
++ else if(scatt_data->scatt_vals_arr)
++ scatt_data->scatt_vals_arr[val_idx] = val;
++ else
++ return -1;
++
++ return 0;
++}
++#endif
+Index: lib/imagery/scatt.c
+===================================================================
+--- lib/imagery/scatt.c (revision 0)
++++ lib/imagery/scatt.c (working copy)
+@@ -0,0 +1,746 @@
++/*!
++ \file lib/imagery/scatt.c
++
++ \brief Imagery library - functions for wx Scatter Plot Tool.
++
++ Low level functions used by wx Scatter Plot Tool.
++
++ Copyright (C) 2013 by the GRASS Development Team
++
++ This program is free software under the GNU General Public License
++ (>=v2). Read the file COPYING that comes with GRASS for details.
++
++ \author Stepan Turek <stepan.turek at seznam.cz> (Mentor: Martin Landa)
++ */
++
++#include <grass/raster.h>
++#include <grass/imagery.h>
++#include <grass/gis.h>
++#include <grass/glocale.h>
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <math.h>
++#include <string.h>
++
++
++struct rast_row
++{
++ CELL * row;
++ char * null_row;
++ struct Range rast_range; /*Range of whole raster.*/
++};
++
++/*!
++ \brief Create pgm header.
++
++ Scatter plot internally generates pgm files. These pgms have header in format created by this function.
++
++ \param region region to be pgm header generated for
++ \param [out] header header of pgm file
++ */
++static int get_cat_rast_header(struct Cell_head * region, char * header){
++ return sprintf(header, "P5\n%d\n%d\n1\n", region->cols, region->rows);
++}
++
++/*!
++ \brief Create category raster conditions file.
++
++ \param cat_rast_region region to be file generated for
++ \param cat_rast path of generated category raster file
++ */
++int I_create_cat_rast(struct Cell_head * cat_rast_region, const char * cat_rast)
++{
++ FILE * f_cat_rast;
++ char cat_rast_header[1024];//TODO magic number
++ int i_row, i_col;
++ int head_nchars;
++
++ unsigned char * row_data;
++
++ f_cat_rast = fopen(cat_rast, "wb");
++ if(!f_cat_rast) {
++ G_warning("Unable to create category raster condition file <%s>.", cat_rast);
++ return -1;
++ }
++
++ head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
++
++ fwrite(cat_rast_header, sizeof(char), head_nchars/sizeof(char), f_cat_rast);
++ if (ferror(f_cat_rast)){
++ fclose(f_cat_rast);
++ G_warning(_("Unable to write header into category raster condition file <%s>."), cat_rast);
++ return -1;
++ }
++
++ row_data = (unsigned char *) G_malloc(cat_rast_region->cols * sizeof(unsigned char));
++ for(i_col = 0; i_col < cat_rast_region->cols; i_col++)
++ row_data[i_col] = 0 & 255;
++
++ for(i_row = 0; i_row < cat_rast_region->rows; i_row++) {
++ fwrite(row_data, sizeof(unsigned char), (cat_rast_region->cols)/sizeof(unsigned char), f_cat_rast);
++ if (ferror(f_cat_rast))
++ {
++ fclose(f_cat_rast);
++ G_warning(_("Unable to write into category raster condition file <%s>."), cat_rast);
++ return -1;
++ }
++ }
++
++ fclose(f_cat_rast);
++ return 0;
++}
++
++static int print_reg(struct Cell_head * intersec, const char * pref, int dbg_level)
++{
++ G_debug(dbg_level, "%s:\n n:%f\ns:%f\ne:%f\nw:%f\nns_res:%f\new_res:%f", pref, intersec->north, intersec->south,
++ intersec->east, intersec->west, intersec->ns_res, intersec->ew_res);
++}
++
++/*!
++ \brief Find intersection region of two regions.
++
++ \param A pointer to intersected region
++ \param B pointer to intersected region
++ \param [out] intersec pointer to intersection region of regions A B (relevant params of the region are: south, north, east, west)
++
++ \return 0 if interection exists
++ \return -1 if regions does not intersect
++ */
++static int regions_intersecion(struct Cell_head * A, struct Cell_head * B, struct Cell_head * intersec)
++{
++
++ if(B->north < A->south) return -1;
++ else if(B->north > A->north) intersec->north = A->north;
++ else intersec->north = B->north;
++
++ if(B->south > A->north) return -1;
++ else if(B->south < A->south) intersec->south = A->south;
++ else intersec->south = B->south;
++
++ if(B->east < A->west) return -1;
++ else if(B->east > A->east) intersec->east = A->east;
++ else intersec->east = B->east;
++
++ if(B->west > A->east) return -1;
++ else if(B->west < A->west) intersec->west = A->west;
++ else intersec->west = B->west;
++
++ if(intersec->north == intersec->south) return -1;
++
++ if(intersec->east == intersec->west) return -1;
++
++ return 0;
++
++}
++
++/*!
++ \brief Get rows and cols numbers, which defines intersection of the regions.
++
++ \param A pointer to intersected region
++ \param B pointer to intersected region (A and B must have same resolution)
++ \param [out] A_bounds rows and cols numbers of A stored in south, north, east, west, which defines intersection of A and B
++ \param [out] B_bounds rows and cols numbers of B stored in south, north, east, west, which defines intersection of A and B
++
++ \return 0 if interection exists
++ \return -1 if regions do not intersect
++ \return -2 resolution of regions is not same
++*/
++static int get_rows_and_cols_bounds(struct Cell_head * A, struct Cell_head * B, struct Cell_head * A_bounds, struct Cell_head * B_bounds)
++{
++ float ns_res, ew_res;
++
++ struct Cell_head intersec;
++
++ /* TODO is it right check? */
++ if(abs(A->ns_res - B->ns_res) > GRASS_EPSILON) {
++ G_debug(0, "'get_rows_and_cols_bounds' ns_res does not fit, A->ns_res: %f B->ns_res: %f", A->ns_res, B->ns_res);
++ return -2;
++ }
++
++ if(abs(A->ew_res - B->ew_res) > GRASS_EPSILON) {
++ G_debug(0, "'get_rows_and_cols_bounds' ew_res does not fit, A->ew_res: %f B->ew_res: %f", A->ew_res, B->ew_res);
++ return -2;
++ }
++
++ ns_res = A->ns_res;
++ ew_res = A->ew_res;
++
++ if(regions_intersecion(A, B, &intersec) == -1)
++ return -1;
++
++ A_bounds->north = ceil((A->north - intersec.north - ns_res * 0.5) / ns_res);
++ A_bounds->south = ceil((A->north - intersec.south - ns_res * 0.5) / ns_res);
++
++ A_bounds->east = ceil((intersec.east - A->west - ew_res * 0.5) / ew_res);
++ A_bounds->west = ceil((intersec.west - A->west - ew_res * 0.5) / ew_res);
++
++ B_bounds->north = ceil((B->north - intersec.north - ns_res * 0.5) / ns_res);
++ B_bounds->south = ceil((B->north - intersec.south - ns_res * 0.5) / ns_res);
++
++ B_bounds->east = ceil((intersec.east - B->west - ew_res * 0.5) / ew_res);
++ B_bounds->west = ceil((intersec.west - B->west - ew_res * 0.5) / ew_res);
++
++ return 0;
++}
++
++/*!
++ \brief Insert raster map patch into pgm file.
++
++ \param patch_rast name of raster map
++ \param cat_rast_region region of category raster file
++ \param cat_rast path to category raster file
++
++ \return 0 on success
++ \return -1 on failure
++*/
++int I_insert_patch_to_cat_rast(const char * patch_rast, struct Cell_head * cat_rast_region, const char * cat_rast)
++{
++
++ FILE * f_cat_rast;
++ struct Cell_head patch_region, patch_bounds, cat_rast_bounds;
++ char cat_rast_header[1024];//TODO magic number
++ int i_row, i_col, ncols, nrows, cat_rast_col, patch_col, val;
++ int head_nchars, ret;
++ int fd_patch_rast, init_shift, step_shift;
++ unsigned char * patch_data;
++
++ char * null_chunk_row;
++
++ const char *mapset;
++
++ struct Cell_head patch_lines, cat_rast_lines;
++
++ unsigned char * row_data;
++
++ f_cat_rast = fopen(cat_rast, "rb+");
++ if(!f_cat_rast) {
++ G_warning(_("Unable to open category raster condtions file <%s>."), cat_rast);
++ return -1;
++ }
++
++ head_nchars = get_cat_rast_header(cat_rast_region, cat_rast_header);
++ if ((mapset = G_find_raster(patch_rast,"")) == NULL) {
++ fclose(f_cat_rast);
++ G_warning(_("Unable to find patch raster <%s>."), patch_rast);
++ return -1;
++ }
++
++ Rast_get_cellhd(patch_rast, mapset, &patch_region);
++ Rast_set_window(&patch_region);
++
++ if ((fd_patch_rast = Rast_open_old(patch_rast, mapset)) < 0) {
++ fclose(f_cat_rast);
++ return -1;
++ }
++
++ ret = get_rows_and_cols_bounds(cat_rast_region, &patch_region, &cat_rast_bounds, &patch_bounds);
++ if(ret == -2) {
++ G_warning(_("Resolutions of patch <%s> and patched file <%s> are not same."), patch_rast, cat_rast);
++
++ Rast_close(fd_patch_rast);
++ fclose(f_cat_rast);
++
++ return -1;
++ }
++ else if (ret == -1){
++
++ Rast_close(fd_patch_rast);
++ fclose(f_cat_rast);
++
++ return 0;
++ }
++
++ ncols = cat_rast_bounds.east - cat_rast_bounds.west;
++ nrows = cat_rast_bounds.south - cat_rast_bounds.north;
++
++ patch_data = (unsigned char *) G_malloc(ncols * sizeof(unsigned char));
++
++ init_shift = head_nchars + cat_rast_region->cols * cat_rast_bounds.north + cat_rast_bounds.west;
++
++ if(fseek(f_cat_rast, init_shift, SEEK_SET) != 0) {
++ G_warning(_("Corrupted category raster conditions file <%s> (fseek failed)"), cat_rast);
++
++ Rast_close(fd_patch_rast);
++ G_free(null_chunk_row);
++ fclose(f_cat_rast);
++
++ return -1;
++ }
++
++ step_shift = cat_rast_region->cols - ncols;
++
++ null_chunk_row = Rast_allocate_null_buf();
++
++ for(i_row = 0; i_row < nrows; i_row++) {
++ Rast_get_null_value_row (fd_patch_rast, null_chunk_row, i_row + patch_bounds.north);
++
++ for(i_col = 0; i_col < ncols; i_col++) {
++ patch_col = patch_bounds.west + i_col;
++
++ if(null_chunk_row[patch_col] != 1)
++ patch_data[i_col] = 1 & 255;
++ else {
++ patch_data[i_col] = 0 & 255;
++ }
++ }
++
++ fwrite(patch_data, sizeof(unsigned char), (ncols)/sizeof(unsigned char), f_cat_rast);
++ if (ferror(f_cat_rast))
++ {
++ G_warning(_("Unable to write into category raster conditions file <%s>"), cat_rast);
++
++ Rast_close(fd_patch_rast);
++ G_free(null_chunk_row);
++ fclose(f_cat_rast);
++
++ return -1;
++ }
++ if(fseek(f_cat_rast, step_shift, SEEK_CUR) != 0) {
++ G_warning(_("Corrupted category raster conditions file <%s> (fseek failed)"), cat_rast);
++
++ Rast_close(fd_patch_rast);
++ G_free(null_chunk_row);
++ fclose(f_cat_rast);
++
++ return -1;
++ }
++ }
++
++ Rast_close(fd_patch_rast);
++ G_free(null_chunk_row);
++ fclose(f_cat_rast);
++ return 0;
++}
++
++/*!
++ \brief Updates scatter plots data in category by pixels which meets category conditions.
++
++ \param bands_rows data represents data describig one row from raster band
++ \param belongs_pix array which defines which pixels belongs to category (1 value) and which not (0 value)
++ \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, which are modified according to values in belongs_pix
++*/
++static inline void update_cat_scatt_plts(struct rast_row * bands_rows, unsigned short * belongs_pix, struct scScatts * scatts)
++{
++ int band_axis_1, band_axis_2, i_scatt, array_idx, cat_idx, i_chunk_rows_pix, max_arr_idx;
++
++ CELL * b_1_row;
++ CELL * b_2_row;
++ char * b_1_null_row,* b_2_null_row;
++ struct rast_row b_1_rast_row, b_2_rast_row;
++
++ struct Range b_1_range, b_2_range;
++ int b_1_range_size;
++
++ int row_size = Rast_window_cols();
++
++ int * scatts_bands = scatts->scatts_bands;
++
++ for(i_scatt = 0; i_scatt < scatts->n_a_scatts; i_scatt++)
++ {
++ b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
++ b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
++
++ b_1_row = b_1_rast_row.row;
++ b_2_row = b_2_rast_row.row;
++
++ b_1_null_row = b_1_rast_row.null_row;
++ b_2_null_row = b_2_rast_row.null_row;
++
++ b_1_range = b_1_rast_row.rast_range;
++ b_2_range = b_2_rast_row.rast_range;
++
++ b_1_range_size = b_1_range.max - b_1_range.min + 1;
++ max_arr_idx = (b_1_range.max - b_1_range.min + 1) * (b_2_range.max - b_2_range.min + 1);
++
++ for(i_chunk_rows_pix = 0; i_chunk_rows_pix < row_size; i_chunk_rows_pix++)
++ {
++ /* pixel does not belongs to scatter plot or has null value in one of the bands */
++ if(!belongs_pix[i_chunk_rows_pix] ||
++ b_1_null_row[i_chunk_rows_pix] == 1 ||
++ b_2_null_row[i_chunk_rows_pix] == 1)
++ continue;
++
++ /* index in scatter plot array */
++ array_idx = b_1_row[i_chunk_rows_pix] - b_1_range.min + (b_2_row[i_chunk_rows_pix] - b_2_range.min) * b_1_range_size;
++
++ if(array_idx < 0 || array_idx >= max_arr_idx) {
++ G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
++ continue;
++ }
++
++ /* increment scatter plot value */
++ ++scatts->scatts_arr[i_scatt]->scatt_vals_arr[array_idx];
++ }
++ }
++}
++
++/*!
++ \brief Computes scatter plots data from chunk_rows.
++
++ \param scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
++ \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are selected areas (condtitions)stored
++
++ \param chunk_rows data arrays of chunk_rows from analyzed raster bands (all data in chunk_rows, null_chunk_rows and belongs_pix arrays represents same region)
++ \param null_chunk_rows null data arrays of chunk_rows from analyzed raster bands
++ \param row_size size of data in chunk_rows, null_chunk_rows and belongs_pix arrays
++ \param f_cats_rasts_conds file which stores selected areas (conditions) from mapwindow see I_create_cat_rast() and I_pa
++ \param fd_cats_rasts array of openedraster maps which represents all selected pixels for category
++ \param region analysis region
++
++ \return 0 on success
++ \return -1 on failure
++*/
++static inline int compute_scatts_from_chunk_row(struct Cell_head *region, struct scCats * scatt_conds,
++ FILE ** f_cats_rasts_conds, struct rast_row * bands_rows,
++ struct scCats * scatts, int * fd_cats_rasts)
++{
++
++ int i_rows_pix, i_cat, i_scatt, n_a_scatts, n_pixs;
++ int cat_id, scatt_plts_cat_idx, array_idx, max_arr_idx;
++ char * b_1_null_row,* b_2_null_row;
++ struct rast_row b_1_rast_row, b_2_rast_row;
++ CELL * cat_rast_row;
++
++ struct scScatts * scatts_conds;
++ struct scScatts * scatts_scatt_plts;
++ struct scdScattData * conds;
++
++ struct Range b_1_range, b_2_range;
++ int b_1_range_size;
++
++ int * scatts_bands;
++ struct scdScattData ** scatts_arr;
++
++ CELL * b_1_row;
++ CELL * b_2_row;
++ unsigned char * i_scatt_conds;
++
++ int row_size = Rast_window_cols();
++
++ unsigned short * belongs_pix = (unsigned short *) G_malloc(row_size * sizeof(unsigned short));
++ unsigned char * rast_pixs = (unsigned char *) G_malloc(row_size * sizeof(unsigned char));
++ cat_rast_row = Rast_allocate_c_buf();
++
++
++ for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
++ {
++ scatts_conds = scatt_conds->cats_arr[i_cat];
++
++ cat_id = scatt_conds->cats_ids[i_cat];
++
++ scatt_plts_cat_idx = scatts->cats_idxs[cat_id];
++ if(scatt_plts_cat_idx < 0)
++ continue;
++ scatts_scatt_plts = scatts->cats_arr[scatt_plts_cat_idx];
++
++ G_zero(belongs_pix, row_size * sizeof(unsigned short));
++
++ /* if category has no conditions defined, scatter plots without any constraint are computed (default scatter plots) */
++ if(!scatts_conds->n_a_scatts && !f_cats_rasts_conds[i_cat]) {
++ for(i_scatt = 0; i_scatt < scatts_scatt_plts->n_a_scatts; i_scatt++)
++ {
++ /* all pixels belongs */
++ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
++ belongs_pix[i_rows_pix] = 1;
++ }
++ }
++ /* compute belonging pixels for defined conditions */
++ else
++ {
++ scatts_bands = scatts_conds->scatts_bands;
++
++ /* check conditions from category raster condtitions file */
++ if(f_cats_rasts_conds[i_cat]) {
++ n_pixs = fread(rast_pixs, sizeof(unsigned char), (row_size)/sizeof(unsigned char), f_cats_rasts_conds[i_cat]);
++
++ if (ferror(f_cats_rasts_conds[i_cat]))
++ {
++ G_free(rast_pixs);
++ G_free(belongs_pix);
++ G_warning(_("Unable to read from category raster condtition file."));
++ return -1;
++ }
++ if (n_pixs != n_pixs) {
++ G_free(rast_pixs);
++ G_free(belongs_pix);
++ G_warning(_("Invalid size of category raster conditions file."));
++ return -1;
++
++ }
++
++ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
++ {
++ if(rast_pixs[i_rows_pix] != 0 & 255)
++ belongs_pix[i_rows_pix] = 1;
++ }
++ }
++
++ /* check condtions defined in scatter plots*/
++ for(i_scatt = 0; i_scatt < scatts_conds->n_a_scatts; i_scatt++)
++ {
++ b_1_rast_row = bands_rows[scatts_bands[i_scatt * 2]];
++ b_2_rast_row = bands_rows[scatts_bands[i_scatt * 2 + 1]];
++
++ b_1_row = b_1_rast_row.row;
++ b_2_row = b_2_rast_row.row;
++
++ b_1_null_row = b_1_rast_row.null_row;
++ b_2_null_row = b_2_rast_row.null_row;
++
++ b_1_range = b_1_rast_row.rast_range;
++ b_2_range = b_2_rast_row.rast_range;
++
++ b_1_range_size = b_1_range.max - b_1_range.min + 1;
++ max_arr_idx = (b_1_range.max - b_1_range.min + 1) * (b_2_range.max - b_2_range.min + 1);
++
++ i_scatt_conds = scatts_conds->scatts_arr[i_scatt]->b_conds_arr;
++
++ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
++ {
++ /* pixels already belongs to category from category raster conditions file or contains null value in one of the bands */
++ if(belongs_pix[i_rows_pix] ||
++ b_1_null_row[i_rows_pix] == 1 ||
++ b_2_null_row[i_rows_pix] == 1)
++ continue;
++
++ array_idx = b_1_row[i_rows_pix] - b_1_range.min + (b_2_row[i_rows_pix] - b_2_range.min) * b_1_range_size;
++ if(array_idx < 0 || array_idx >= max_arr_idx) {
++ G_warning ("Data inconsistent. Value computed for scatter plot is out of initialized range.");
++ continue;
++ }
++ /* pixels meets condtion defined in scatter plot */
++ if(i_scatt_conds[array_idx])
++ belongs_pix[i_rows_pix] = 1;
++ }
++ }
++ }
++
++ /* update category raster with belonging pixels */
++ if(fd_cats_rasts[i_cat] >= 0) {
++ Rast_set_null_value(cat_rast_row, Rast_window_cols(), CELL_TYPE);
++
++ for(i_rows_pix = 0; i_rows_pix < row_size; i_rows_pix++)
++ if(belongs_pix[i_rows_pix])
++ cat_rast_row[i_rows_pix] = belongs_pix[i_rows_pix];
++
++ Rast_put_c_row (fd_cats_rasts[i_cat], cat_rast_row);
++ }
++
++ /* update scatter plots with belonging pixels */
++ update_cat_scatt_plts(bands_rows, belongs_pix, scatts_scatt_plts);
++ }
++
++ G_free(cat_rast_row);
++ G_free(rast_pixs);
++ G_free(belongs_pix);
++
++ return 0;
++}
++
++/*!
++ \brief Get list if bands needed to be opened for analysis from scCats struct.
++*/
++static void get_needed_bands(struct scCats * cats, int * b_needed_bands)
++{
++ // results in b_needed_bands - array of bools - if item has value 1, band (defined by item index) is needed to be opened
++ int i_cat, i_scatt, cat_id;
++
++ for(i_cat = 0; i_cat < cats->n_a_cats; i_cat++)
++ {
++ for(i_scatt = 0; i_scatt < cats->cats_arr[i_cat]->n_a_scatts; i_scatt++)
++ {
++ G_debug(3, "Active scatt %d in catt %d", i_scatt, i_cat);
++
++ b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2]] = 1;
++ b_needed_bands[cats->cats_arr[i_cat]->scatts_bands[i_scatt * 2 + 1]] = 1;
++ }
++ }
++ return;
++}
++
++/*!
++ \brief Helper function for clean up.
++*/
++static void free_compute_scatts_data(int * fd_bands, struct rast_row * bands_rows, int n_a_bands, int * bands_ids,
++ int * fd_cats_rasts, FILE ** f_cats_rasts_conds, int n_a_cats)
++{
++ int i, band_id;
++
++ for(i = 0; i < n_a_bands; i++)
++ {
++ band_id = bands_ids[i];
++ if(band_id >= 0) {
++ Rast_close(fd_bands[i]);
++ G_free(bands_rows[band_id].row);
++ G_free(bands_rows[band_id].null_row);
++ }
++ }
++
++ if(f_cats_rasts_conds)
++ for(i = 0; i < n_a_cats; i++)
++ if(f_cats_rasts_conds[i])
++ fclose(f_cats_rasts_conds[i]);
++
++ if(fd_cats_rasts)
++ for(i = 0; i < n_a_cats; i++)
++ if(fd_cats_rasts[i] >= 0)
++ Rast_close(fd_cats_rasts[i]);
++
++}
++
++/*!
++ \brief Compute scatter plots data.
++
++ If category has not defined no category raster condition file and no scatter plot with consdtion,
++ default scatter plot is computed.
++
++ \param region analysis region, beaware that all input data must be prepared for this region (bands (their ranges), cats_rasts_conds rasters...)
++ \param region function calls Rast_set_window for this region
++ \param scatt_conds pointer to scScatts struct of type SC_SCATT_CONDITIONS, where are stored selected areas (conditions) in scatter plots
++ \param cats_rasts_conds paths to category raster conditions files representing selected areas (conditions) in rasters for every category
++ \param cats_rasts_conds index in array represents corresponding category id
++ \param cats_rasts_conds for manupulation with category raster conditions file see also I_id_scatt_to_bands() and I_insert_patch_to_cat_rast()
++ \param bands names of analyzed bands, order of bands is defined by their id
++ \param n_bands number of bands
++ \param [out] scatts pointer to scScatts struct of type SC_SCATT_DATA, where are computed scatter plots stored
++ \param [out] cats_rasts array of raster maps names where will be stored all selected pixels for every category
++
++ \return 0 on success
++ \return -1 on failure
++*/
++int I_compute_scatts(struct Cell_head *region, struct scCats * scatt_conds, const char ** cats_rasts_conds,
++ const char ** bands, int n_bands, struct scCats * scatts, const char ** cats_rasts)
++{
++ const char *mapset;
++ char header[1024];
++
++ int fd_cats_rasts[scatt_conds->n_a_cats];
++ FILE * f_cats_rasts_conds[scatt_conds->n_a_cats];
++
++ struct rast_row bands_rows[n_bands];
++
++ RASTER_MAP_TYPE data_type;
++
++ int nrows, i_band, n_a_bands, band_id,
++ i, i_row, head_nchars, i_cat, id_cat;
++
++ int fd_bands[n_bands];
++ int bands_ids[n_bands];
++ int b_needed_bands[n_bands];
++
++ Rast_set_window(region);
++
++ for(i_band = 0; i_band < n_bands; i_band++)
++ fd_bands[i_band] = -1;
++
++ for(i_band = 0; i_band < n_bands; i_band++)
++ bands_ids[i_band] = -1;
++
++ if (n_bands != scatts->n_bands ||
++ n_bands != scatt_conds->n_bands)
++ return -1;
++
++ memset(b_needed_bands, 0, (size_t)n_bands * sizeof(int));
++
++ get_needed_bands(scatt_conds, &b_needed_bands[0]);
++ get_needed_bands(scatts, &b_needed_bands[0]);
++
++ n_a_bands = 0;
++
++ /* open band rasters, which are needed for computation */
++ for(band_id = 0; band_id < n_bands; band_id++)
++ {
++ if(b_needed_bands[band_id])
++ {
++ G_debug(3, "Opening raster no. %d with name: %s", band_id, bands[band_id]);
++
++ if ((mapset = G_find_raster2(bands[band_id],"")) == NULL) {
++ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands,
++ bands_ids, NULL, NULL, scatt_conds->n_a_cats);
++ G_warning(_("Unbale to read find raster <%s>"), bands[band_id]);
++ return -1;
++ }
++
++ if ((fd_bands[n_a_bands] = Rast_open_old(bands[band_id], mapset)) < 0) {
++ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands,
++ bands_ids, NULL, NULL, scatt_conds->n_a_cats);
++ G_warning(_("Unbale to open raster <%s>"), bands[band_id]);
++ return -1;
++ }
++
++ data_type = Rast_get_map_type(fd_bands[n_a_bands]);
++ if(data_type != CELL_TYPE) {
++ G_warning(_("Raster <%s> type is not <%s>"), bands[band_id], "CELL");
++ return -1;
++ }
++
++ bands_rows[band_id].row = Rast_allocate_c_buf();
++ bands_rows[band_id].null_row = Rast_allocate_null_buf();
++
++ if(Rast_read_range(bands[band_id], mapset, &bands_rows[band_id].rast_range) != 1){
++ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands,
++ bands_ids, NULL, NULL, scatt_conds->n_a_cats);
++ G_warning(_("Unable to read range of raster <%s>"), bands[band_id]);
++ return -1;
++ }
++
++ bands_ids[n_a_bands] = band_id;
++ ++n_a_bands;
++ }
++ }
++
++ /* open category rasters condition files and category rasters */
++ for(i_cat = 0; i_cat < scatts->n_a_cats; i_cat++)
++ {
++ id_cat = scatts->cats_ids[i_cat];
++ if(cats_rasts[id_cat]) {
++ fd_cats_rasts[i_cat] = Rast_open_new(cats_rasts[id_cat], CELL_TYPE);
++ }
++ else
++ fd_cats_rasts[i_cat] = -1;
++
++ if(cats_rasts_conds[id_cat]) {
++ f_cats_rasts_conds[i_cat] = fopen(cats_rasts_conds[id_cat], "r");
++ if(!f_cats_rasts_conds[i_cat]) {
++ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids,
++ f_cats_rasts_conds, f_cats_rasts_conds, scatt_conds->n_a_cats);
++ G_warning(_("Unable to open category raster condtition file <%s>"), bands[band_id]);
++ return -1;
++ }
++ }
++ else
++ f_cats_rasts_conds[i_cat] = NULL;
++ }
++
++ head_nchars = get_cat_rast_header(region, header);
++ for(i_cat = 0; i_cat < scatt_conds->n_a_cats; i_cat++)
++ if(f_cats_rasts_conds[i_cat])
++ if( fseek(f_cats_rasts_conds[i_cat] , head_nchars, SEEK_SET) != 0) {
++ G_warning(_("Corrupted category raster conditions file (fseek failed)"));
++ return -1;
++ }
++
++ nrows = Rast_window_rows();
++
++ /* analyze bands by rows */
++ for (i_row = 0; i_row < nrows; i_row++)
++ {
++ for(i_band = 0; i_band < n_a_bands; i_band++)
++ {
++ band_id = bands_ids[i_band];
++ Rast_get_c_row(fd_bands[i_band], bands_rows[band_id].row, i_row);
++ Rast_get_null_value_row (fd_bands[i_band], bands_rows[band_id].null_row, i_row);
++ }
++ if(compute_scatts_from_chunk_row(region, scatt_conds, f_cats_rasts_conds, bands_rows, scatts, fd_cats_rasts) == -1)
++ {
++ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids, fd_cats_rasts,
++ f_cats_rasts_conds, scatt_conds->n_a_cats);
++ return -1;
++ }
++
++ }
++ free_compute_scatts_data(fd_bands, bands_rows, n_a_bands, bands_ids,
++ fd_cats_rasts, f_cats_rasts_conds, scatt_conds->n_a_cats);
++ return 0;
++}
+\ No newline at end of file
+Index: lib/vector/Vlib/open.c
+===================================================================
+--- lib/vector/Vlib/open.c (revision 57556)
++++ lib/vector/Vlib/open.c (working copy)
+@@ -240,7 +240,9 @@
+ }
+ else {
+ char file_path[GPATH_MAX];
+-
++ /* reduce to current mapset if search path was set */
++ if(strcmp(Map->mapset, "") == 0)
++ Map->mapset = G_store(G_mapset());
+ /* temporary map: reduce to current mapset if search path
+ * was set */
+ if (strcmp(Map->mapset, "") == 0)
More information about the grass-commit
mailing list